From a25cf4825c39158026802d150eef13523adde622 Mon Sep 17 00:00:00 2001 From: Rex Date: Sat, 28 Sep 2024 22:38:13 +0800 Subject: [PATCH] export plugins --- dist/rextrees.js | 8 ++++---- dist/rextrees.min.js | 2 +- dist/rexuiplugin.js | 8 ++++---- dist/rexuiplugin.min.js | 2 +- docs/site/search/search_index.json | 2 +- docs/site/sitemap.xml.gz | Bin 2827 -> 2827 bytes docs/site/ui-trees/index.html | 10 +++++----- 7 files changed, 16 insertions(+), 16 deletions(-) diff --git a/dist/rextrees.js b/dist/rextrees.js index 22725b9e97..b82968eb61 100644 --- a/dist/rextrees.js +++ b/dist/rextrees.js @@ -34114,19 +34114,19 @@ this .on('expand.start', function () { toggleButton.emit('expand.start', toggleButton); - FireTreesSizerEvent(this, 'tree.expand.start'); + FireTreesSizerEvent(this, 'expand.start'); }, this) .on('expand.complete', function () { toggleButton.emit('expand.complete', toggleButton); - FireTreesSizerEvent(this, 'tree.expand.complete'); + FireTreesSizerEvent(this, 'expand.complete'); }) .on('collapse.start', function () { toggleButton.emit('collapse.start', toggleButton); - FireTreesSizerEvent(this, 'tree.collapse.start'); + FireTreesSizerEvent(this, 'collapse.start'); }) .on('collapse.complete', function () { toggleButton.emit('collapse.complete', toggleButton); - FireTreesSizerEvent(this, 'tree.collapse.complete'); + FireTreesSizerEvent(this, 'collapse.complete'); }); // Run this callback after adding to parent tree diff --git a/dist/rextrees.min.js b/dist/rextrees.min.js index 4d308e2243..fbe06f215a 100644 --- a/dist/rextrees.min.js +++ b/dist/rextrees.min.js @@ -3,4 +3,4 @@ var t,e;t=void 0,e=function(){var t=!1,e=function(e){t||(void 0===e&&(e=60),pars * @author Richard Davey * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} - */const Xc=Phaser.Display.Canvas.CanvasPool;var Wc=function(t){var e=Xc.create(this),i=e.getContext("2d",{willReadFrequently:!0});t.syncFont(e,i);var s=i.measureText(t.testString);if("actualBoundingBoxAscent"in s){var r=s.actualBoundingBoxAscent,n=s.actualBoundingBoxDescent,h={ascent:r,descent:n,fontSize:r+n};return Xc.remove(e),h}var a=Math.ceil(s.width*t.baselineX),o=a,l=2*o;if(o=o*t.baselineY|0,e.width=a,e.height=l,i.fillStyle="#f00",i.fillRect(0,0,a,l),i.font=t._font,i.textBaseline="alphabetic",i.fillStyle="#000",i.fillText(t.testString,0,o),h={ascent:0,descent:0,fontSize:0},!i.getImageData(0,0,a,l))return h.ascent=o,h.descent=o+6,h.fontSize=h.ascent+h.descent,Xc.remove(e),h;var d,c,u=i.getImageData(0,0,a,l).data,p=u.length,v=4*a,g=0,f=!1;for(d=0;do;d--){for(c=0;c0&&this.wrapMode!==vl&&0===this.wrapWidth}setStyle(t,e,i){if(void 0===e&&(e=!0),void 0===i&&(i=!1),t&&t.hasOwnProperty("wordWrap")){var s=t.wordWrap;s.hasOwnProperty("width")&&(t.wrap={mode:"word",width:s.width})}if(t&&t.hasOwnProperty("wrap")){var r=t.wrap;if(r.hasOwnProperty("mode")){var n=r.mode;"string"==typeof n&&(r.mode=yl[n])}else r.hasOwnProperty("width")&&(r.mode=1)}t&&t.rtl&&i&&!t.hasOwnProperty("halign")&&(t.halign="right"),t&&t.hasOwnProperty("fontSize")&&"number"==typeof t.fontSize&&(t.fontSize=t.fontSize.toString()+"px");var h=this.propertyMap;for(var a in h){var o=h[a],l=o[0],d=i?o[1]:this[a],c=o[2];if("wrapCallback"===a||"wrapCallbackScope"===a)this[a]=Fc(t,l,d);else{var u=jc(t,l,d);c&&(u=c(u)),this[a]=u}}var p=Fc(t,"font",null);this._font=null===p?this.fontStyle+" "+this.fontSize+" "+this.fontFamily:p;var v=Fc(t,"fill",null);null!==v&&(this.color=Zl(v));var g=Fc(t,"metrics",!1);return g?this.metrics={ascent:Fc(g,"ascent",0),descent:Fc(g,"descent",0),fontSize:Fc(g,"fontSize",0)}:!e&&this.metrics||(this.metrics=Wc(this)),e?this.parent.updateText():this.parent}syncFont(t,e){e.font=this._font}syncStyle(t,e){e.textBaseline="alphabetic",e.fillStyle=this.color,e.strokeStyle=this.stroke,e.lineWidth=this.strokeThickness,e.lineCap="round",e.lineJoin="round"}syncShadow(t,e){e?(t.shadowOffsetX=this.shadowOffsetX,t.shadowOffsetY=this.shadowOffsetY,t.shadowColor=this.shadowColor,t.shadowBlur=this.shadowBlur):(t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowColor=0,t.shadowBlur=0)}update(t){return t&&(this._font=`${this.fontStyle} ${this.fontSize} ${this.fontFamily}`.trim(),this.metrics=Wc(this)),this.parent.updateText(t)}buildFont(){var t=`${this.fontStyle} ${this.fontSize} ${this.fontFamily}`.trim();return t!==this._font&&(this._font=t),this}setFont(t){return"string"==typeof t?(this.fontFamily=t,this.fontSize="",this.fontStyle=""):(this.fontFamily=Fc(t,"fontFamily","Courier"),this.fontSize=Fc(t,"fontSize","16px"),this.fontStyle=Fc(t,"fontStyle","")),this.update(!0)}setFontFamily(t){return this.fontFamily=t,this.update(!0)}setFontStyle(t){return this.fontStyle=t,this.update(!0)}setFontSize(t){return"number"==typeof t&&(t=t.toString()+"px"),this.fontSize=t,this.update(!0)}setTestString(t){return this.testString=t,this.update(!0)}setFixedSize(t,e){return this.fixedWidth=t,this.fixedHeight=e,t&&(this.parent.width=t),e&&(this.parent.height=e),this.update(this.isWrapFitMode)}setResolution(t){return this.resolution=t,this.update(!1)}setXOffset(t){return this.xOffset=t,this.update(!1)}setBackgroundColor(t,e,i){return void 0===i&&(i=!0),this.backgroundColor=Zl(t,this.parent.canvas,this.parent.context),this.backgroundColor2=Zl(e,this.parent.canvas,this.parent.context),this.backgroundHorizontalGradient=i,this.update(!1)}setBackgroundStrokeColor(t,e){return this.backgroundStrokeColor=Zl(t,this.parent.canvas,this.parent.context),this.backgroundStrokeLineWidth=e,this.update(!1)}setBackgroundCornerRadius(t,e){return this.backgroundCornerRadius=t,this.backgroundCornerIteration=e,this.update(!1)}setFill(t){return this.color=Zl(t,this.parent.canvas,this.parent.context),this.update(!1)}setColor(t){return this.color=Zl(t,this.parent.canvas,this.parent.context),this.update(!1)}setStroke(t,e){return void 0===t?this.strokeThickness=0:(void 0===e&&(e=this.strokeThickness),this.stroke=Zl(t,this.parent.canvas,this.parent.context),this.strokeThickness=e),this.update(!0)}setShadow(t,e,i,s,r,n){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i="#000"),void 0===s&&(s=0),void 0===r&&(r=!1),void 0===n&&(n=!0),this.shadowOffsetX=t,this.shadowOffsetY=e,this.shadowColor=Zl(i,this.parent.canvas,this.parent.context),this.shadowBlur=s,this.shadowStroke=r,this.shadowFill=n,this.update(!1)}setShadowOffset(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.shadowOffsetX=t,this.shadowOffsetY=e,this.update(!1)}setShadowColor(t){return void 0===t&&(t="#000"),this.shadowColor=Zl(t,this.parent.canvas,this.parent.context),this.update(!1)}setShadowBlur(t){return void 0===t&&(t=0),this.shadowBlur=t,this.update(!1)}setShadowStroke(t){return this.shadowStroke=t,this.update(!1)}setShadowFill(t){return this.shadowFill=t,this.update(!1)}setUnderline(t,e,i){return void 0===t&&(t="#000"),void 0===e&&(e=0),void 0===i&&(i=0),this.underlineColor=Zl(t,this.parent.canvas,this.parent.context),this.underlineThickness=e,this.underlineOffset=i,this.update(!1)}setUnderlineColor(t){return void 0===t&&(t="#000"),this.underlineColor=Zl(t,this.parent.canvas,this.parent.context),this.update(!1)}setUnderlineThickness(t){return void 0===t&&(t=0),this.underlineThickness=t,this.update(!1)}setUnderlineOffset(t){return void 0===t&&(t=0),this.underlineOffset=t,this.update(!1)}setStrikethrough(t,e,i){return void 0===t&&(t="#000"),void 0===e&&(e=0),void 0===i&&(i=0),this.strikethroughColor=Zl(t,this.parent.canvas,this.parent.context),this.strikethroughThickness=e,this.strikethroughOffset=i,this.update(!1)}setStrikethroughColor(t){return void 0===t&&(t="#000"),this.strikethroughColor=Zl(t,this.parent.canvas,this.parent.context),this.update(!1)}setStrikethroughThickness(t){return void 0===t&&(t=0),this.strikethroughThickness=t,this.update(!1)}setStrikethroughOffset(t){return void 0===t&&(t=0),this.strikethroughOffset=t,this.update(!1)}setWrapMode(t){return"string"==typeof t&&(t=yl[t.toLowerCase()]||0),this.wrapMode=t,this.update(!0)}setWrapWidth(t){return this.wrapWidth=t,this.update(!1)}setAlign(t,e){return void 0===t&&(t="left"),void 0===e&&(e="top"),this.halign=t,this.valign=e,this.update(!1)}setHAlign(t){return void 0===t&&(t="left"),this.halign=t,this.update(!1)}setVAlign(t){return void 0===t&&(t="top"),this.valign=t,this.update(!1)}setMaxLines(t){return void 0===t&&(t=0),this.maxLines=t,this.update(!1)}getTextMetrics(){var t=this.metrics;return{ascent:t.ascent,descent:t.descent,fontSize:t.fontSize}}setTextMetrics(t,e){return this.metrics.ascent=t.ascent,this.metrics.descent=t.descent,this.metrics.fontSize=t.fontSize,e&&("string"==typeof e?(this.fontFamily=e,this.fontSize="",this.fontStyle=""):(this.fontFamily=Fc(e,"fontFamily",this.fontFamily),this.fontSize=Fc(e,"fontSize",this.fontSize),this.fontStyle=Fc(e,"fontStyle",this.fontStyle))),this.parent.updateText(!0)}get lineHeight(){return this.metrics.fontSize+this.parent.lineSpacing}toJSON(){var t={},e=this.propertyMap;for(var i in e)t[i]=this[i];return t.metrics=this.getTextMetrics(),t}destroy(){this.parent=void 0}}var Bc={draw(t,e,i,s){var r=this.penManager;this.hitAreaManager.clear();var n=this.context;n.save();var h=this.defaultStyle;this.clear(),nd(this,h.backgroundColor,h.backgroundStrokeColor,h.backgroundStrokeLineWidth,h.backgroundCornerRadius,h.backgroundColor2,h.backgroundHorizontalGradient,h.backgroundCornerIteration),t+=this.startXOffset,e+=this.startYOffset;var a,o,l,d,c,u,p=h.halign,v=h.valign,g=h.lineHeight,f=r.lines,m=f.length,y=h.maxLines;y>0&&m>y?(o=y,l="center"===v?Math.floor((m-o)/2):"bottom"===v?m-o:0):(o=m,l=0),d=l+o;var b=this.rtl,x=b?this.parent.width:void 0;u="center"===v?Math.max((s-o*g)/2,0):"bottom"===v?Math.max(s-o*g-2,0):0,u+=e;for(var w=l;w0){var a=this.defaultStyle.metrics,o=i-a.ascent,l=a.fontSize;this.drawRectangle(e,o,t.width,l,h.bgcolor,h)}if(h.underlineThickness>0&&t.width>0){var d=i+h.underlineOffset-h.underlineThickness/2;this.drawLine(e,d,t.width,h.underlineThickness,h.underlineColor,h)}if(t.isTextPen&&(h.buildFont(),h.syncFont(r,n),h.syncStyle(r,n),this.drawText(e,i,t.text,h)),t.isImagePen&&this.drawImage(e,i,t.prop.img,t.prop.color,h),h.strikethroughThickness>0&&t.width>0&&(d=i+h.strikethroughOffset-h.strikethroughThickness/2,this.drawLine(e,d,t.width,h.strikethroughThickness,h.strikethroughColor,h)),n.restore(),t.hasAreaMarker&&t.width>0){var c,u=t.prop.area;if(u)c={key:u};else{var p=t.prop.url;c={key:`url:${p}`,url:p}}this.hitAreaManager.add(e,i-this.startYOffset,t.width,this.defaultStyle.lineHeight,c)}},clear(){var t=this.canvas;this.context.clearRect(0,0,t.width,t.height)},drawRectangle(t,e,i,s,r,n){this.autoRound&&(t=Math.round(t),e=Math.round(e));var h=this.context;h.fillStyle=r,h.fillRect(t,e,i,s)},drawLine(t,e,i,s,r,n){this.autoRound&&(t=Math.round(t),e=Math.round(e));var h=this.context;n.syncShadow(h,n.shadowStroke);var a=h.lineCap;h.lineCap="butt",h.strokeStyle=r,h.lineWidth=s,h.beginPath(),h.moveTo(t,e),h.lineTo(t+i,e),h.stroke(),h.lineCap=a},drawText(t,e,i,s){this.autoRound&&(t=Math.round(t),e=Math.round(e));var r=this.context;s.stroke&&"none"!==s.stroke&&s.strokeThickness>0&&(s.syncShadow(r,s.shadowStroke),r.strokeText(i,t,e)),s.color&&"none"!==s.color&&(s.syncShadow(r,s.shadowFill),r.fillText(i,t,e))},drawImage(t,e,i,s,r){e-=this.startYOffset,this.parent.imageManager.draw(i,this.context,t,e,s,this.autoRound)}};const Hc=Phaser.Utils.Objects.GetValue,Nc=cl,Gc=ul;class Vc{constructor(t){this.prop={},this.resetFromJSON(t)}resetFromJSON(t){this.text=Hc(t,"text",""),this.x=Hc(t,"x",0),this.y=Hc(t,"y",0),this.width=Hc(t,"width",0);var e=Hc(t,"prop",null);null===e&&(e={}),this.prop=e,this.newLineMode=Hc(t,"newLineMode",0),this.startIndex=Hc(t,"startIndex",0)}get plainText(){var t=this.text;return this.newLineMode===Gc&&(t+="\n"),t}get wrapText(){var t=this.text;return this.newLineMode!==Nc&&(t+="\n"),t}get rawTextLength(){var t=this.text.length;return this.newLineMode===Gc&&(t+=1),t}get endIndex(){return this.startIndex+this.rawTextLength}get lastX(){return this.x+this.width}get isTextPen(){return""!==this.text}get isImagePen(){return!!this.prop.img}get hasAreaMarker(){return!!this.prop.area||!!this.prop.url}}const Uc=Phaser.Utils.Objects.GetFastValue,$c=cl,Jc=pl;class Kc{constructor(t){this.pens=[],this.lines=[],this.maxLinesWidth=void 0,this.pensPool=t.pensPool,this.linesPool=t.linesPool,this.tagToText=Uc(t,"tagToText",zt),this.tagToTextScope=Uc(t,"tagToTextScope",void 0)}destroy(){this.clear(),this.tagToText=void 0,this.tagToTextScope=void 0}clear(){for(var t=0,e=this.lines.length;t=this.lines.length)return this.getLineEndIndex(t);var e=this.lines[t];return e&&e[0]?e[0].startIndex:0}getLineEndIndex(t){t>=this.lines.length&&(t=this.lines.length-1);var e,i,s=!1;for(e=t;e>=0&&!(s=null!=(i=this.lines[e])&&i.length>0);e--);return s?i[i.length-1].endIndex:0}getLineWidth(t){var e=this.lines[t];if(!e)return 0;var i=e[e.length-1];return null==i?0:i.lastX}getMaxLineWidth(){if(void 0!==this.maxLinesWidth)return this.maxLinesWidth;for(var t,e=0,i=0,s=this.lines.length;ie&&(e=t);return this.maxLinesWidth=e,e}getLineWidths(){for(var t=[],e=0,i=this.lines.length;e=t&&o<=e||(h=h.substring(t-a,e-a)),this.tagToTextScope?c+=this.tagToText.call(this.tagToTextScope,h,l,d):c+=this.tagToText(h,l,d),d=l,!(o>=e)));u++);return c}get length(){return this.lines.length}set length(t){this.clear()}}var qc={};const Zc=Phaser.Geom.Rectangle;var Qc=new cc;class tu{constructor(){this.hitAreas=[]}destroy(){this.clear()}clear(){for(var t=0,e=this.hitAreas.length;ts&&vu(g)){""!==b?h.push(n.getLine(b,x,au)):0===w&&r>0&&h.push(n.getLine("",0,au)),h.push(...uu(g,e,du,s,0,n));var C=h.pop();b=C.text,x=C.width,n.freeLine(C)," "===b&&(b="",x=0)}else(m=x+f)>o?(h.push(n.getLine(b,x,au)),b=g,x=f,o=s):(b+=g,x=m),w===S-1&&h.push(n.getLine(b,x,l))}return h},pu=function(t,e){var i;switch(e){case lu:i=[];for(var s=0,r=(t=t.split(" ")).length;s0&&e!==fu&&i0&&t>e&&(t=e),t}get linesWidth(){return Math.ceil(this.penManager.getMaxLineWidth())}get linesHeight(){var t=this.displayLinesCount,e=this.defaultStyle.lineHeight*t;return t>0&&(e-=this.defaultStyle.lineSpacing),e}get imageManager(){return this.parent.imageManager}get rtl(){return this.parent.style.rtl}newPenManager(){return new Kc({pensPool:this.pensPool,linesPool:this.linesPool,tagToText:this.parser.propToTagText,tagToTextScope:this.parser})}get tmpPenManager(){return null===this._tmpPenManager&&(this._tmpPenManager=this.newPenManager()),this._tmpPenManager}getPlainText(t,e,i){var s;if(null==t)s=this.penManager.plainText;else{var r=this.parser.splitText(t,1);s="";for(var n=0,h=r.length;n=0;e--){var i=this.sizerChildren[e];i&&this.remove(i,t)}return this},clear(t){return Sp(this.sizerChildren,null),ch.call(this,t),this}},Op={setColumnSpace(t){if(this.space.column||(this.space.column=[]),this.space.column.length=this.columnCount-1,"number"==typeof t)Sp(this.space.column,t);else for(var e=0,i=this.columnCount-1;e=0;s--){var r=s*this.columnCount+t;this.sizerChildren.splice(r,0,null)}return this.columnProportions.push(e),this.columnWidth.length+=1,this.space.column.splice(t,0,i),this},kp={getChildrenWidth:function(t){if(this.rexSizer.hidden)return 0;void 0===t&&(t=!0);var e,i,s,r,n,h=0,a=this.sizerChildren,o=!1;this.totalColumnProportions;for(var l=0;l0){var i=t-this.getChildrenWidth(!1);i>=0&&(this.proportionWidthLength=i/e)}else this.proportionWidthLength=0}return t},resolveHeight:function(t){if(void 0!==(t=Ae.call(this,t))&&void 0===this.proportionHeightLength){var e=this.totalRowProportions;if(e>0){var i=t-this.getChildrenHeight(!1);i>=0&&(this.proportionHeightLength=i/e)}else this.proportionHeightLength=0}return t},resolveChildrenWidth:function(t){var e,i,s,r;for(var n in this.sizerChildren)(e=this.sizerChildren[n])&&e.isRexSizer&&!e.ignoreLayout&&(r=this.getColumnWidth(parseInt(n)%this.columnCount),i=this.getExpandedChildWidth(e,r),void 0===(s=e.resolveWidth(i))&&(s=i),e.resolveChildrenWidth(s))},resolveChildrenHeight:function(t){var e,i,s,r;for(var n in this.sizerChildren)(e=this.sizerChildren[n])&&e.isRexSizer&&!e.ignoreLayout&&(r=this.getRowHeight(Math.floor(parseInt(n)/this.rowCount)),i=this.getExpandedChildHeight(e,r),void 0===(s=e.resolveHeight(i))&&(s=i),e.resolveChildrenHeight(s))},runWidthWrap:function(t){var e,i,s,r;for(var n in this.sizerChildren)!(e=this.sizerChildren[n])||e.isRexSizer&&e.ignoreLayout||!e.runWidthWrap||(r=this.getColumnWidth(parseInt(n)%this.columnCount),i=this.getExpandedChildWidth(e,r),e.isRexSizer&&void 0===(s=e.resolveWidth(i))&&(s=i),e.runWidthWrap(s));return this},runHeightWrap:function(t){var e,i,s,r;for(var n in this.sizerChildren)!(e=this.sizerChildren[n])||e.isRexSizer&&e.ignoreLayout||!e.runHeightWrap||(r=this.getRowHeight(Math.floor(parseInt(n)/this.rowCount)),i=this.getExpandedChildHeight(e,r),e.isRexSizer&&void 0===(s=e.resolveHeight(i))&&(s=i),e.runHeightWrap(s));return this},resetGrid:function(t,e,i,s,r){if(void 0===i&&(i=0),void 0===s&&(s=0),this.columnCount=t,this.rowCount=e,this.gridCount=t*e,this.removeAll(),this.sizerChildren.length=t*e,Sp(this.sizerChildren,null),this.columnProportions=[],this.columnProportions.length=t,"number"==typeof i)Sp(this.columnProportions,i);else for(var n=0;n0?e+=t:0===t&&(this.hasColumnProportion0Child=!0);return e},Mp=function(){for(var t,e=0,i=0;i0?e+=t:0===t&&(this.hasRowProportion0Child=!0);return e};const Rp=Phaser.Utils.Objects.IsPlainObject,Lp=Phaser.Utils.Objects.GetValue;class Dp extends qn{constructor(t,e,i,s,r,n,h,a,o,l){Rp(e)?(e=Lp(l=e,"x",0),i=Lp(l,"y",0),s=Lp(l,"width",void 0),r=Lp(l,"height",void 0),n=Lp(l,"column",l.col||0),h=Lp(l,"row",0),a=Lp(l,"columnProportions",0),o=Lp(l,"rowProportions",0)):Rp(s)?(s=Lp(l=s,"width",void 0),r=Lp(l,"height",void 0),n=Lp(l,"column",l.col||0),h=Lp(l,"row",0),a=Lp(l,"columnProportions",0),o=Lp(l,"rowProportions",0)):Rp(n)?(n=Lp(l=n,"column",l.col||0),h=Lp(l,"row",0),a=Lp(l,"columnProportions",0),o=Lp(l,"rowProportions",0)):Rp(a)&&(a=Lp(l=a,"columnProportions",0),o=Lp(l,"rowProportions",0)),super(t,e,i,s,r,l),this.type="rexGridSizer",this.sizerChildren=[],this.addChildrenMap("items",this.sizerChildren),this.setCreateCellContainerCallback(Lp(l,"createCellContainerCallback")),this.setIndentLeft(Lp(l,"space.indentLeftOdd",0),Lp(l,"space.indentLeftEven",0)),this.setIndentTop(Lp(l,"space.indentTopOdd",0),Lp(l,"space.indentTopEven",0)),this.resetGrid(n,h,a,o,Lp(l,"space",void 0))}destroy(t){this.scene&&!this.ignoreDestroy&&(super.destroy(t),this.columnProportions=void 0,this.rowProportions=void 0,this.columnWidth=void 0,this.rowHeight=void 0,this.createCellContainerCallback=void 0)}setColumnProportion(t,e){return t>=this.columnProportions.length||(this.columnProportions[t]=e),this}setRowProportion(t,e){return t>=this.rowProportions.length||(this.rowProportions[t]=e),this}get totalColumnProportions(){return void 0===this._totalColumnProportions&&(this._totalColumnProportions=Ep.call(this)),this._totalColumnProportions}get totalRowProportions(){return void 0===this._totalRowProportions&&(this._totalRowProportions=Mp.call(this)),this._totalRowProportions}getChildAt(t,e){return this.sizerChildren[e*this.columnCount+t]}childToGridIndex(t,e){if(!t)return null;var i=this.sizerChildren.indexOf(t);return-1===i?null:(void 0===e&&(e={}),e.x=i%this.columnCount,e.y=Math.floor(i/this.columnCount),e)}getColumnWidth(t){var e=this.columnProportions[t];return 0===e?this.columnWidth[t]:e*this.proportionWidthLength}getRowHeight(t){var e=this.rowProportions[t];return 0===e?this.rowHeight[t]:e*this.proportionHeightLength}setCreateCellContainerCallback(t){return this.createCellContainerCallback=t,this}}Object.assign(Dp.prototype,kp);const Ap=Phaser.Utils.Objects.GetValue,Yp=Phaser.Math.Percent;var zp=function(t,e,i){var s;return t.y===e.y?s=Yp(i.x,t.x,e.x):t.x===e.x&&(s=Yp(i.y,t.y,e.y)),s},Xp=function(t,e,i){var s,r;this.enable&&(Wp.x=e,Wp.y=i,this.reverseAxis?(s=this.getEndPoint(),r=this.getStartPoint()):(s=this.getStartPoint(),r=this.getEndPoint()),this.value=zp(s,r,Wp))},Wp={},jp=function(t,e,i){if(this.enable&&t.isDown){var s,r;Fp.x=t.worldX,Fp.y=t.worldY,this.reverseAxis?(s=this.getEndPoint(),r=this.getStartPoint()):(s=this.getStartPoint(),r=this.getEndPoint());var n=zp(s,r,Fp);this.stopEaseValue(),0===this.easeValueDuration||Math.abs(this.value-n)<.1?this.value=n:this.easeValueTo(n)}},Fp={},Ip=function(t,e){void 0===e&&(e=Bp);var i=this.childrenMap.thumb,s=i.x,r=i.y;return he(i,this.innerLeft,this.innerTop,this.innerWidth,this.innerHeight,t),e.x=i.x,e.y=i.y,i.x=s,i.y=r,e},Bp={};const Hp=Phaser.Display.Align.LEFT_CENTER,Np=Phaser.Display.Align.TOP_CENTER;var Gp={};const Vp=Phaser.Display.Align.RIGHT_CENTER,Up=Phaser.Display.Align.BOTTOM_CENTER;var $p={};const Jp=Phaser.Math.Linear;var Kp={};const qp=Phaser.Display.Align.LEFT_CENTER,Zp=Phaser.Display.Align.TOP_CENTER,Qp=Phaser.Display.Align.RIGHT_CENTER,tv=Phaser.Display.Align.BOTTOM_CENTER,ev=Phaser.Utils.Objects.GetValue,iv=Phaser.Utils.Objects.IsPlainObject,sv=Phaser.Math.Clamp,rv=Phaser.Math.Snap.To;class nv extends(_a(Oh)){constructor(t,e){super(t,e),this.type="rexSlider",this.bootProgressBase(e),this.reverseAxis=ev(e,"reverseAxis",!1);var i=ev(e,"background",void 0),s=ev(e,"track",void 0),r=ev(e,"indicator",void 0),n=ev(e,"thumb",void 0);if(i&&(iv(i)&&(i=Go(t,i)),this.addBackground(i)),s&&(iv(s)&&(s=Go(t,s)),this.add(s,{proportion:1,expand:!0,minWidth:0===this.orientation?0:void 0,minHeight:1===this.orientation?0:void 0})),r&&(iv(r)&&(r=Go(t,r)),this.pin(r)),n){iv(n)&&(n=Go(t,n)),this.pin(n);var h=ev(e,"thumbOffsetX",0),a=ev(e,"thumbOffsetY",0);this.setThumbOffset(h,a)}var o=ev(e,"input",0);switch("string"==typeof o&&(o=hv[o]),o){case 0:n&&(n.setInteractive(),this.scene.input.setDraggable(n),n.on("drag",Xp,this).on("dragstart",(function(t){this.eventEmitter.emit("inputstart",t)}),this).on("dragend",(function(t){this.eventEmitter.emit("inputend",t)}),this));break;case 1:this.on("pointerdown",jp,this).on("pointermove",jp,this).on("pointerdown",(function(t){this.eventEmitter.emit("inputstart",t)}),this).on("pointerup",(function(t){this.eventEmitter.emit("inputend",t)}),this).on("pointerover",(function(t){t.isDown&&this.eventEmitter.emit("inputstart",t)}),this).on("pointerout",(function(t){t.isDown&&this.eventEmitter.emit("inputend",t)}),this).setInteractive()}this.addChildrenMap("background",i),this.addChildrenMap("track",s),this.addChildrenMap("indicator",r),this.addChildrenMap("thumb",n),this.setEnable(ev(e,"enable",void 0)),this.setGap(ev(e,"gap",void 0)),this.setValue(ev(e,"value",0),ev(e,"min",void 0),ev(e,"max",void 0))}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}setGap(t,e,i){return t&&void 0!==e&&(t/=i-e),this.gap=t,this}setThumbOffset(t,e){return this.thumbOffsetX=t,this.thumbOffsetY=e,this}get value(){return this._value}set value(t){void 0!==this.gap&&(t=rv(t,this.gap));var e=this._value;this._value=sv(t,0,1),e!==this._value&&(this.updateThumb(this._value),this.updateIndicator(this._value),this.eventEmitter.emit("valuechange",this._value,e,this.eventEmitter))}postLayout(t,e,i){return this.updateThumb(),this.updateIndicator(),super.postLayout(t,e,i),this}}const hv={pan:0,drag:0,click:1,none:-1};var av={getStartPoint:function(t){if(void 0===t&&(t=Gp),this.childrenMap.thumb){var e=0===this.orientation?Hp:Np;Ip.call(this,e,t)}else 0===this.orientation?(t.x=this.innerLeft+1,t.y=this.centerY):(t.x=this.centerX,t.y=this.innerTop+1);return t},getEndPoint:function(t){if(void 0===t&&(t=$p),this.childrenMap.thumb){var e=0===this.orientation?Vp:Up;Ip.call(this,e,t)}else 0===this.orientation?(t.x=this.innerRight-1,t.y=this.centerY):(t.x=this.centerX,t.y=this.innerBottom-1);return t},updateThumb:function(t){var e,i,s=this.childrenMap.thumb;return void 0===s||(void 0===t&&(t=this.value),this.reverseAxis?(e=this.getEndPoint(),i=this.getStartPoint()):(e=this.getStartPoint(),i=this.getEndPoint()),function(t,e,i,s){void 0===s&&(s=Kp),s.x=Jp(e.x,i.x,t),s.y=Jp(e.y,i.y,t)}(t,e,i,s),s.x+=this.thumbOffsetX,s.y+=this.thumbOffsetY,this.resetChildPositionState(s)),this},updateIndicator:function(t){var e=this.childrenMap.indicator;if(void 0===e)return this;void 0===t&&(t=this.value);var i,s,r,n=this.reverseAxis,h=this.childrenMap.thumb;if(h)if(0===this.orientation){var a,o=Q(h);if(n)a=h.x-o*h.originX,i=this.right-a;else i=(a=h.x-o*h.originX)+o-this.left}else{var l,d=tt(h);if(n)l=h.y-d*h.originY,s=this.bottom-l;else s=(l=h.y-d*h.originY)+d-this.top}else 0===this.orientation?i=this.width*t:s=this.height*t;Ie(e,i,s),r=n?0===this.orientation?Qp:tv:0===this.orientation?qp:Zp,ne(e,this,r),this.resetChildPositionState(e)}};Object.assign(nv.prototype,av);const ov=Phaser.Utils.Objects.GetValue;class lv extends Oh{constructor(t,e){super(t,e),this.type="rexScrollBar";var i,s,r=ov(e,"background",void 0),n=ov(e,"buttons",void 0),h=ov(n,"top",ov(n,"left",void 0)),a=ov(n,"bottom",ov(n,"right",void 0)),o=ov(e,"slider",void 0);(r&&this.addBackground(r),h&&(this.add(h),new _r(h).on("intouch",(function(){if(this.enable){var t=i.reverseAxis?this.scrollStep:-this.scrollStep;this.value+=t}}),this)),o)&&(o.orientation=this.orientation,o.eventEmitter=this,o.value=null,s=0===this.orientation?void 0===ov(o,"width",void 0)?1:0:void 0===ov(o,"height",void 0)?1:0,i=new nv(t,o),t.add.existing(i),this.add(i,{proportion:s}));a&&(this.add(a),new _r(a).on("intouch",(function(){if(this.enable){var t=i.reverseAxis?-this.scrollStep:this.scrollStep;this.value+=t}}),this));var l=[h,a];this.addChildrenMap("background",r),this.addChildrenMap("slider",i),this.addChildrenMap("buttons",l);var d=ov(e,"valuechangeCallback",null);if(null!==d){var c=ov(e,"valuechangeCallbackScope",void 0);this.on("valuechange",d,c)}this.setEnable(ov(e,"enable",void 0)),this.setValue(ov(e,"value",0)),this.setScrollStep(ov(n,"step",.01))}setScrollStep(t){return this.scrollStep=t,this}get enable(){return!!this.childrenMap.slider&&this.childrenMap.slider.enable}set enable(t){this.childrenMap.slider&&this.childrenMap.slider.setEnable(t)}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}get value(){return this.childrenMap.slider?this.childrenMap.slider.value:0}set value(t){this.childrenMap.slider&&(this.childrenMap.slider.value=t)}setValue(t,e,i){return this.childrenMap.slider&&this.childrenMap.slider.setValue(t,e,i),this}addValue(t,e,i){return this.childrenMap.slider&&this.childrenMap.slider.addValue(t,e,i),this}getValue(t,e){return this.childrenMap.slider?this.childrenMap.slider.getValue(t,e):0}easeValueTo(t,e,i){return this.childrenMap.slider&&this.childrenMap.slider.easeValueTo(t,e,i),this}stopEaseValue(){return this.childrenMap.slider&&this.childrenMap.slider.stopEaseValue(),this}setEaseValueDuration(t){return this.childrenMap.slider&&this.childrenMap.slider.setEaseValueDuration(t),this}setEaseValueFunction(t){return this.childrenMap.slider&&this.childrenMap.slider.setEaseValueFunction(t),this}}class dv extends ks{constructor(t,e){super(e),this.parent=t,this.init()}init(){this.start("IDLE")}next_IDLE(){var t,e=this.parent;return e.dragState.isDown&&(t=0===e.dragThreshold?"DRAG":"DRAGBEGIN"),t}update_IDLE(t,e){this.next()}next_DRAGBEGIN(){var t=this.parent,e=t.dragState;return e.isDown?e.pointer.getDistance()>=t.dragThreshold?"DRAG":"DRAGBEGIN":"IDLE"}update_DRAGBEGIN(t,e){this.next()}next_DRAG(){var t,e=this.parent;return e.dragState.isUp&&(t=e.outOfBounds?"BACK":e.slidingEnable?"SLIDE":"IDLE"),t}update_DRAG(t,e){var i=this.parent;i.dragState.justMoved&&i.dragging(),this.next()}enter_DRAG(){this.parent.onDragStart()}exit_DRAG(){this.parent.onDragEnd()}next_SLIDE(){var t,e=this.parent;return e.dragState.isDown?t="DRAG":e.isSliding||(t="IDLE"),t}enter_SLIDE(){this.parent.onSliding()}exit_SLIDE(){this.parent.stop()}update_SLIDE(t,e){this.parent.sliding(t,e),this.next()}next_BACK(){var t,e=this.parent;return e.dragState.isDown?t="DRAG":e.isPullBack||(t="IDLE"),t}enter_BACK(){this.parent.onPullBack()}exit_BACK(){this.parent.stop()}update_BACK(t,e){this.parent.pullBack(t,e),this.next()}}const cv=Phaser.Utils.Objects.GetValue,uv=Phaser.Math.Distance.Between;class pv extends Qe{constructor(t,e){super(t,e),this._enable=void 0,this.rectBoundsInteractive=cv(e,"rectBoundsInteractive",!1),this.rectBoundsInteractive||t.setInteractive(cv(e,"inputConfig",void 0)),this.resetFromJSON(e),this.boot()}resetFromJSON(t){return this.pointer=void 0,this.isInTouched=!1,this.holdStartTime=void 0,this.x=void 0,this.y=void 0,this.preX=void 0,this.preY=void 0,this.localX=void 0,this.localY=void 0,this.justMoved=!1,this.setEnable(cv(t,"enable",!0)),this.holdThreshold=cv(t,"holdThreshold",50),this.pointerOutReleaseEnable=cv(t,"pointerOutRelease",!0),this}boot(){var t=this.scene,e=this.parent;this.rectBoundsInteractive?(t.input.on("pointerdown",this.onPointIn,this),t.input.on("pointerup",this.onPointOut,this),t.input.on("pointermove",this.onPointerMove,this)):(e.on("pointerdown",this.onPointIn,this),e.on("pointerup",this.onPointOut,this),this.pointerOutReleaseEnable&&e.on("pointerout",this.onPointOut,this),e.on("pointermove",this.onPointerMove,this)),t.sys.events.on("preupdate",this.preupdate,this)}shutdown(t){if(!this.isShutdown){var e=this.scene;this.parent,this.rectBoundsInteractive&&(e.input.off("pointerdown",this.onPointIn,this),e.input.off("pointerup",this.onPointOut,this),e.input.off("pointermove",this.onPointerMove,this)),e.sys.events.off("preupdate",this.preupdate,this),this.pointer=void 0,super.shutdown(t)}}get enable(){return this._enable}set enable(t){this._enable!==t&&(t||(this.isInTouched=!1,this.pointer=void 0),this._enable=t)}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}toggleEnable(){return this.setEnable(!this.enable),this}setPointerOutReleaseEnable(t){return void 0===t&&(t=!0),this.pointerOutReleaseEnable=t,this}get isDown(){return this.pointer&&this.pointer.isDown}get isUp(){return!this.isDown}get dx(){return this.x-this.preX}get dy(){return this.y-this.preY}get dt(){return an(this.scene)}get speed(){return this.x===this.preX&&this.y===this.preY?0:uv(this.preX,this.preY,this.x,this.y)/(.001*this.dt)}get speedX(){return this.dx/(.001*this.dt)}get speedY(){return this.dy/(.001*this.dt)}onPointIn(t,e,i){this.enable&&t.isDown&&void 0===this.pointer&&(this.rectBoundsInteractive&&!nr(this.parent,t)||(this.pointer=t,this.localX=e,this.localY=i))}onPointOut(t){this.enable&&this.pointer===t&&(this.pointer=void 0)}onPointerMove(t,e,i){this.enable&&t.isDown&&this.pointer===t&&(this.rectBoundsInteractive&&this.pointerOutReleaseEnable&&!nr(this.parent,t)?this.onPointOut(t):(this.localX=e,this.localY=i))}preupdate(t,e){if(this.enable){var i=this.pointer;this.justMoved=!1,i&&!this.isInTouched?(this.x=i.worldX,this.y=i.worldY,this.preX=i.worldX,this.preY=i.worldY,this.isInTouched=!0,this.holdStartTime=void 0,this.emit("touchstart",i,this.localX,this.localY)):i&&this.isInTouched?this.x===i.x&&this.y===i.y?void 0===this.holdStartTime?this.holdStartTime=t:t-this.holdStartTime>this.holdThreshold&&(this.preX=this.x,this.preY=this.y):(this.preX=this.x,this.preY=this.y,this.x=i.worldX,this.y=i.worldY,this.holdStartTime=void 0,this.justMoved=!0,this.emit("touchmove",i,this.localX,this.localY)):!i&&this.isInTouched&&(this.isInTouched=!1,this.holdStartTime=void 0,this.emit("touchend",i))}}}const vv=Phaser.Utils.Objects.GetValue;class gv{constructor(t){this.resetFromJSON(t)}resetFromJSON(t){return this.setValue(vv(t,"value",0)),this.setSpeed(vv(t,"speed",0)),this.setAcceleration(vv(t,"acceleration",0)),this}reset(){this.setValue(0),this.setSpeed(0),this.setAcceleration(0)}setValue(t){return this.value=t,this}setSpeed(t){return this.speed=t,this}setAcceleration(t){return this.acceleration=t,this}updateSpeed(t){return 0!==this.acceleration&&(this.speed+=this.acceleration*t,this.speed<0&&(this.speed=0)),this}getDeltaValue(t){return this.updateSpeed(t),this.speed<=0?0:this.speed*t}update(t){return this.updateSpeed(t),this.speed>0&&(this.value+=this.getDeltaValue(t)),this}get isMoving(){return this.speed>0}}class fv{constructor(){this.value,this.dir,this.movement=new gv}init(t,e,i,s,r){return this.value=t,this.end=r,this.dir=void 0!==r?tthis.end&&(this.value=this.end):this.valuethis.maxValue}overMin(t){return null!=this.minValue&&t0,Math.abs(e),i)}sliding(t,e){e*=.001;var i=this._slowDown.update(e).value;this.overMax(i)?(this.value=this.maxValue,this._slowDown.stop()):this.overMin(i)?(this.value=this.minValue,this._slowDown.stop()):this.value=i}onPullBack(){var t=this.value,e=this.outOfMinBound?this.minValue:this.maxValue,i=Math.abs(e-t),s=this.backDeceleration,r=Math.sqrt(2*s*i);this._slowDown.init(t,void 0,r,s,e)}pullBack(t,e){e*=.001,this.value=this._slowDown.update(e).value,this._slowDown.isMoving||this._state.next()}stop(){this._slowDown.stop()}}const xv={y:0,v:0,vertical:0,x:1,h:1,horizontal:1},wv=Phaser.Utils.Objects.GetValue;class Sv extends Qe{constructor(t,e){switch(super(t,e),this.parent!==this.scene?this.focusMode=wv(e,"focus",!0):this.focusMode=!1,"boolean"==typeof this.focusMode&&(this.focusMode=this.focusMode?1:0),this.setSpeed(wv(e,"speed",.1)),this.setEnable(wv(e,"enable",!0)),this.focusMode){case 0:case 2:this.scene.input.on("wheel",this.onSceneScroll,this);break;default:t.setInteractive(wv(e,"inputConfig",void 0)).on("wheel",(function(t,e,i,s,r){this.tryScroll(i)}),this)}}destroy(){switch(this.focusMode){case 0:case 2:this.scene.input.off("wheel",this.onSceneScroll,this)}}onSceneScroll(t,e,i,s,r,n){(2!==this.focusMode||nr(this.parent,t))&&this.tryScroll(s)}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}setSpeed(t){return this.speed=t,this}tryScroll(t){if(this.enable)return this.scroll(t),this}scroll(t){return t*=this.speed,this.emit("scroll",t,this.parent,this),this}}const Cv=Phaser.Utils.Objects.GetValue;var Ov=function(t,e,i,s){var r,n,h="Y"===(i=i.toUpperCase()),a=2===t.scrollMode,o=t.childrenMap.child,l=`slider${i}`;if(r=a||s.hasOwnProperty(l)?Cv(s,l,void 0):Cv(s,"slider",void 0)){var d,c,u;!0===r&&(r={}),r.orientation=h?1:0,n=function(t,e){void 0===e&&(e={});var i=ft(e);(e={slider:i}).orientation=i.orientation,delete i.orientation,e.background=i.background,delete i.background,e.buttons=i.buttons,delete i.buttons,e.value=null;var s=new lv(t,e);t.add.existing(s);var r=s.childrenMap.slider;return s.addChildrenMap("track",r.childrenMap.track),s.addChildrenMap("indicator",r.childrenMap.indicator),s.addChildrenMap("thumb",r.childrenMap.thumb),s}(t.scene,r);var p=Cv(r,"position",0);"string"==typeof p&&(p=Pv[p]);var v,g,f=Cv(s,`space.slider${i}`,void 0);void 0===f&&void 0===(f=Cv(s,"space.slider",void 0))&&(a?f=0:v=Cv(s,"space.child",0)),g=void 0===v?"number"==typeof f:"number"==typeof v,h?0===p?(d=2,c=1,u=void 0===v?g?{left:f}:f:{left:Cv(v,"right",v)}):(d=0,c=1,u=void 0===v?g?{right:f}:f:{right:Cv(v,"left",v)}):0===p?(d=1,c=2,u=void 0===v?g?{top:f}:f:{top:Cv(v,"bottom",v)}):(d=1,c=0,u=void 0===v?g?{bottom:f}:f:{bottom:Cv(v,"top",v)}),e.add(n,{column:d,row:c,align:"center",padding:u,expand:!0}),t[`hideUnscrollableSlider${i}`]=Cv(r,"hideUnscrollableSlider",!1),t[`adaptThumb${i}SizeMode`]=Cv(r,"adaptThumbSize",!1),t[`minThumb${i}Size`]=Cv(r,"minThumbSize",void 0)}else t[`hideUnscrollableSlider${i}`]=!1,t[`adaptThumb${i}SizeMode`]=!1,t[`minThumb${i}Size`]=void 0;var m,y,b=Cv(s,"scrollDetectionMode");"string"==typeof b&&(b=Tv[b]);var x=`scroller${i}`;(m=a||s.hasOwnProperty(x)?Cv(s,x,!0):Cv(s,"scroller",!0))&&o&&(!0===m&&(m={}),m.orientation=h?0:1,void 0!==b&&(m.rectBoundsInteractive=1===b),y=new bv(o,m),o.isRexContainerLite&&o.sendChildToBack(o));var w,S,C,O,P,T=Cv(s,a?`mouseWheelScroller${i}`:"mouseWheelScroller",!1);T&&o&&(void 0!==b&&(T.focus=1===b?2:0),w=new Sv(o,T)),t.addChildrenMap(`slider${i}`,n),t.addChildrenMap(`scroller${i}`,y),t.addChildrenMap(`mouseWheelScroller${i}`,w),a&&!h||(t.hideUnscrollableSlider=t[`hideUnscrollableSlider${i}`],t.adaptThumbSizeMode=t[`adaptThumb${i}SizeMode`],t.minThumbSize=t[`minThumb${i}Size`],t.addChildrenMap("slider",n),t.addChildrenMap("scroller",y),t.addChildrenMap("mouseWheelScroller",w)),n&&(a?(S=h?"t":"s",O=`scroll${i}`):(S="t",O="scroll"),n.on("valuechange",(function(e){t[S]=e,t.emit(O,t)}))),y&&(a?(C=`childO${i}`,O=`scroll${i}`):(C="childOY",O="scroll"),y.on("valuechange",(function(e){t[C]=e,t.emit(O,t)}))),w&&(P=a?`addChildO${i}`:"addChildOY",w.on("scroll",(function(e){t[P](-e,!0)})))};const Pv={right:0,left:1,bottom:0,top:1},Tv={gameObject:0,rectBounds:1},_v=Phaser.Utils.Objects.GetValue;var kv=function(t,e){var i=t.scene,s=[0,1,0],r=[0,1,0],n=_v(e,"width"),h=_v(e,"height");n||_v(e,"child.expandWidth",!0)||(s[1]=0),h||_v(e,"child.expandHeight",!0)||(r[1]=0);var a=new Dp(i,{column:3,row:3,columnProportions:s,rowProportions:r});switch(function(t,e,i){var s=Ap(i,"child"),r=Ap(s,"gameObject",void 0);if(r){var n=Ap(i,"space.child",0);t.childMargin={};var h=t.childMargin,a={};if("number"==typeof n)switch(t.scrollMode){case 0:case 1:h.top=0,h.bottom=0,h.left=0,h.right=0;break;default:h.top=n,h.bottom=n,h.left=n,h.right=n}else switch(t.scrollMode){case 0:h.top=Ap(n,"top",0),h.bottom=Ap(n,"bottom",0),a.left=Ap(n,"left",0),a.right=Ap(n,"right",0);break;case 1:h.top=Ap(n,"left",0),h.bottom=Ap(n,"right",0),a.top=Ap(n,"top",0),a.bottom=Ap(n,"bottom",0);break;default:h.top=Ap(n,"top",0),h.bottom=Ap(n,"bottom",0),h.left=Ap(n,"left",0),h.right=Ap(n,"right",0)}e.add(r,{column:1,row:1,align:Ap(s,"align","center"),padding:a,expand:{width:Ap(s,"expandWidth",!0),height:Ap(s,"expandHeight",!0)}})}t.addChildrenMap("child",r)}(t,a,e),t.scrollMode){case 0:Ov(t,a,"y",e);break;case 1:Ov(t,a,"x",e);break;default:Ov(t,a,"y",e),Ov(t,a,"x",e)}return a},Ev=function(t){var e,i,s,r;switch(this.scrollMode){case 0:case 1:e=this.topChildOY,i=this.bottomChildOY,s=this.childrenMap.scroller,r=this.childrenMap.slider,t=0===this.scrollMode?"Y":"X";break;default:"Y"===(t=t.toUpperCase())?(e=this.topChildOY,i=this.bottomChildOY):(e=this.leftChildOX,i=this.rightChildOX),s=this.childrenMap[`scroller${t}`],r=this.childrenMap[`slider${t}`]}if(s){var n="Y"===t?this.scaleY:this.scaleX;s.setBounds(e,i*n)}r&&r.setEnable(e!==i)},Mv=function(t){switch(this.scrollMode){case 0:case 1:(e=this.childrenMap.slider)&&this.hideUnscrollableSlider&&this.setChildVisible(e,this.isOverflow);break;default:t=t.toUpperCase();var e=this.childrenMap[`slider${t}`],i=this[`hideUnscrollableSlider${t}`],s=this[`isOverflow${t}`];e&&i&&this.setChildVisible(e,s)}},Rv=function(t){switch(this.scrollMode){case 0:case 1:if(!this.adaptThumbSizeMode)return;if(!(a=this.childrenMap.slider))return;var e=Math.min(this.childVisibleHeight/this.childHeight,1),i=a.childrenMap.track,s=a.childrenMap.thumb,r=this.minThumbSize;if(0===this.scrollMode){var n=i.displayHeight*e;void 0!==r&&n0?t.setText(e).getTextBounds().wrappedText.split("\n"):e.split("\n")}return i}(this.textObject,this.text,this.lines),this.linesCount=this.lines.length,this._textHeight=void 0,this._textVisibleHeight=void 0,this.updateTextObject(),this},updateTextObject:function(){var t=Math.max(Math.floor(Xv.call(this,-this.textOY)),0),e=Wv.call(this,t)+this.textOY,i=jv.call(this,t);return function(t,e){switch(hl(t)){case 0:var i=(r=t.style).wordWrapWidth,s=r.wordWrapCallback;r.wordWrapWidth=0,r.wordWrapCallback=void 0,t.setText(e),r.wordWrapWidth=i,r.wordWrapCallback=s;break;case 1:var r,n=(r=t.style).wrapMode;r.wrapMode=0,t.setText(e),r.wrapMode=n;break;case 2:var h=t._maxWidth;t._maxWidth=0,t.setText(e),t._maxWidth=h}}(this.textObject,i),this.textObject.rexSizer.offsetY=e,Fv.call(this),this},preLayout:function(){return this._textLineHeight=void 0,this._textLineSpacing=void 0,this._visibleLinesCount=void 0,this._textHeight=void 0,this._textVisibleHeight=void 0,We.call(this),this},layoutChildren:function(){var t,e,i,s,r,n,h,a=this.left,o=this.top;(t=this.textObject).rexSizer.hidden||(s=a+(i=(e=t.rexSizer).padding).left*this.scaleX,r=o+i.top*this.scaleY,n=this.width*this.scaleX-(i.left+i.right)*this.scaleX,h=this.height*this.scaleY-(i.top+i.bottom)*this.scaleY,Bv.call(this,t,n,h),he(t,s,r,n,h,e.align),e.preOffsetY=0,Fv.call(this),this.textMask&&(this.textMask.setPosition().resize(),this.resetChildPositionState(this.textMask)))}};const Nv=Phaser.Utils.Objects.IsPlainObject,Gv=Phaser.Utils.Objects.GetValue,Vv=Phaser.Display.Align.TOP_LEFT;class Uv extends qn{constructor(t,e,i,s,r,n){Nv(e)?(e=Gv(n=e,"x",0),i=Gv(n,"y",0),s=Gv(n,"width",void 0),r=Gv(n,"height",void 0)):Nv(s)&&(s=Gv(n=s,"width",void 0),r=Gv(n,"height",void 0)),super(t,e,i,s,r,n),this.type="rexTextBlock",this.textObject=void 0,this.linesCount=0,this.textMask=void 0,this.textObjectType=void 0,this._textLineHeight=void 0,this._textLineSpacing=void 0,this._visibleLinesCount=void 0,this._textHeight=void 0,this._textVisibleHeight=void 0,this._textObjectRealHeight=0,this.lines=void 0,this.text=Gv(n,"content",""),this._textOY=0,this.execeedTopState=!1,this.execeedBottomState=!1,this.setClampMode(Gv(n,"clampTextOY",!0)),this.alwaysScrollable=Gv(n,"alwaysScrollable",!1);var h=Gv(n,"background",void 0),a=Gv(n,"text",void 0);void 0===a&&(a=$v(t)),this.textCropEnable=Gv(n,"textCrop",!!a.setCrop);var o=Gv(n,"textMask",!this.textCropEnable);h&&this.addBackground(h),this.add(a),this.sizerChildren=[a];var l=this.getSizerConfig(a);l.align=Vv,l.padding=ue(0),l.expand=!0,this.textObject=a,this.textObjectType=hl(a),l.preOffsetY=0,l.offsetY=0,o&&(this.textMask=el.call(this,this.textObject,this)),this.addChildrenMap("background",h),this.addChildrenMap("text",a)}destroy(t){if(this.scene&&!this.ignoreDestroy){if(this.textObject=void 0,this.textMask=void 0,this.lines){switch(this.textObjectType){case 0:case 2:this.lines.length=0;break;case 1:this.lines.destroy()}this.lines=void 0}super.destroy(t)}}setClampMode(t){return void 0===t&&(t=!0),this.clampTextOY=t,this}get textLineHeight(){if(void 0===this._textLineHeight){var t;switch(this.textObjectType){case 0:case 1:var e=this.textObject.style;t=e.metrics.fontSize+e.strokeThickness;break;case 2:var i=this.textObject.fontSize/this.textObject.fontData.size;t=this.textObject.fontData.lineHeight*i}this._textLineHeight=t}return this._textLineHeight}get textLineSpacing(){if(void 0===this._textLineSpacing){var t;switch(this.textObjectType){case 0:case 1:t=this.textObject.lineSpacing;break;case 2:t=0}this._textLineSpacing=t}return this._textLineSpacing}get visibleLinesCount(){return void 0===this._visibleLinesCount&&(this._visibleLinesCount=Math.floor(Xv.call(this,this._textObjectRealHeight))),this._visibleLinesCount}get topTextOY(){return 0}get bottomTextOY(){return-this.textVisibleHeight}get textHeight(){return void 0===this._textHeight&&(this._textHeight=Wv.call(this,this.linesCount)),this._textHeight}get textObjectHeight(){return this._textObjectRealHeight-(this.textLineHeight+this.textLineSpacing)}get textVisibleHeight(){if(void 0===this._textVisibleHeight){var t=this.textHeight-this.textObjectHeight;!this.alwaysScrollable&&t<0&&(t=0),this._textVisibleHeight=t}return this._textVisibleHeight}textOYExceedTop(t){return void 0===t&&(t=this.textOY),t>this.topTextOY}textOYExeceedBottom(t){return void 0===t&&(t=this.textOY),tthis.linesCount?t=0:s?t=e:r&&(t=i)),this._textOY!==t&&(this._textOY=t,this.updateTextObject()),s&&(this.execeedTopState||this.emit("execeedtop",this,t,e)),this.execeedTopState=s,r&&(this.execeedBottomState||this.emit("execeedbottom",this,t,i)),this.execeedBottomState=r}setTextOY(t){return this.textOY=t,this}set t(t){this.textOY=-this.textVisibleHeight*t}get t(){var t=this.textVisibleHeight;return 0===t?0:this.textOY/-t}setTextOYByPercentage(t){return this.t=t,this}}var $v=function(t){return t.add.text(0,0,"")};Object.assign(Uv.prototype,Hv);var Jv={setText(t){return this.childrenMap.child.setText(t),this.resizeController(),this},appendText(t){return this.setText(this.text+t),this}},Kv={scrollToLine(t){return this.setChildOY(-this.lineHeight*t),this},scrollToNextLine(t){void 0===t&&(t=1);var e=this.lineIndex+t;return this.scrollToLine(e),this}};const qv=Phaser.Utils.Objects.GetValue;class Zv extends Yv{constructor(t,e){void 0===e&&(e={});var i=qv(e,"text",void 0),s=qv(e,"textWidth",void 0),r=qv(e,"textHeight",void 0),n=qv(e,"textCrop",!!i.setCrop),h=qv(e,"textMask",!n),a=qv(e,"content",""),o=new Uv(t,{width:s,height:r,text:i,textMask:h,textCrop:n&&!h,content:a,clampTextOY:qv(e,"clampChildOY",!1),alwaysScrollable:qv(e,"alwaysScrollable",!1)});t.add.existing(o),function(t){Object.defineProperty(t,"childOY",{configurable:!0,get:function(){return t.textOY},set:function(e){t.textOY=e}}),Object.defineProperty(t,"topChildOY",{get:function(){return t.topTextOY}}),Object.defineProperty(t,"bottomChildOY",{get:function(){return t.bottomTextOY}}),Object.defineProperty(t,"childVisibleHeight",{get:function(){return t.textObjectHeight}}),Object.defineProperty(t,"childHeight",{get:function(){return t.textHeight}})}(o),e.scrollMode=0,e.type="rexTextArea",e.child={gameObject:o,expandWidth:void 0===s,expandHeight:void 0===r};var l=qv(e,"space",void 0);l&&(l.child=qv(l,"text",0)),super(t,e),this.addChildrenMap("text",i)}get text(){return this.childrenMap.child.text}get lineHeight(){var t=this.childrenMap.child;return t.textLineHeight+t.textLineSpacing}get lineIndex(){return Math.floor(-this.childOY/this.lineHeight)}get linesCount(){return this.childrenMap.child.linesCount}get contentHeight(){return this.childrenMap.child.textHeight}}Object.assign(Zv.prototype,Jv,Kv);const Qv=Phaser.Utils.Objects.GetValue;var tg=function(t,e){var i,s;switch(e&&(e.hasOwnProperty("$type")?i=e.$type:e.hasOwnProperty("key")&&(i="bitmaptext",e.font=e.key)),i){case"bitmaptext":case"bitmap":s=new up(t,e);break;case"bbcodetext":case"bbcode":s=new op(t,0,0,"",e);break;case"label":s=new sg(t,e);break;case"textarea":s=function(t,e,i){e=e?Po(e):{};var s=Qv(i,"background",Go),r=Qv(i,"text",tg),n=Qv(i,"track",Go),h=Qv(i,"thumb",Go);s?e.background=s(t,e.background):delete e.background,r?e.text=r(t,e.text):delete e.text;var a=e.slider;!1!==a&&null!==a&&(void 0===a&&(a={}),n?a.track=n(t,a.track):delete a.track,h?a.thumb=h(t,a.thumb):delete a.thumb,e.slider=a);var o=new Zv(t,e);return t.add.existing(o),o}(t,e);break;default:s=new Ec(t,e)}return No(s,e),t.add.existing(s),s},eg=function(t,e){var i,s;switch(e&&(e.hasOwnProperty("$type")?i=e.$type:e.hasOwnProperty("leftWidth")?i="nineSlice":(e.hasOwnProperty("color")||e.hasOwnProperty("strokeColor"))&&(i="roundRectangle")),i){case"nineSlice":s=e.hasOwnProperty("stretchMode")?new Bo(t,e):new bo(t,e);break;case"roundRectangle":s=new ua(t,e);break;default:s=new Co(t,e)}return No(s,e),t.add.existing(s),s};const ig=Phaser.Utils.Objects.GetValue;class sg extends Tc{constructor(t,e,i){e=function(t,e,i){e=e?Po(e):{};var s=ig(i,"background",Go),r=ig(i,"text",tg),n=ig(i,"icon",eg),h=ig(i,"action",eg);return null!==e.background&&s?e.background=s(t,e.background):delete e.background,null!==e.text&&r?e.text=r(t,e.text):delete e.text,null!==e.icon&&n?e.icon=n(t,e.icon):delete e.icon,null!==e.action&&h?e.action=h(t,e.action):delete e.action,e}(t,e,i),super(t,e),this.type="rexSimpleLabel"}setActiveState(t){return rg(this.getChildren(),"setActiveState",t),this}setHoverState(t){return rg(this.getChildren(),"setHoverState",t),this}setDisableState(t){return rg(this.getChildren(),"setDisableState",t),this}}var rg=function(t,e,i){for(var s=0,r=t.length;s0&&void 0!==this._direction?this.previousDirection=this._direction:this.previousDirection=void 0,this._direction=t,this.verticeAngle=90*t,this.dirty=!0,void 0!==this.previousDirection?this.playEaseDirectionation():this.stopEaseDirection())}setDirection(t,e){return void 0!==e&&this.setEaseDuration(e),this.direction=t,this}toggleDirection(t){return this.setDirection(this.direction+2,t),this}get easeDirectionProgress(){return this._easeDirectionProgress}set easeDirectionProgress(t){this._easeDirectionProgress!==t&&(this._easeDirectionProgress=t,this.dirty=!0)}setPadding(t,e,i,s){if("object"==typeof t){var r=t,n=xg(r,"x",null);null!==n?(t=n,i=n):(t=xg(r,"left",0),i=xg(r,"right",t));var h=xg(r,"y",null);null!==h?(e=h,s=h):(e=xg(r,"top",0),s=xg(r,"bottom",e))}else void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=t),void 0===s&&(s=e);return void 0===this.padding&&(this.padding={}),this.dirty=this.dirty||this.padding.left!=t||this.padding.top!=e||this.padding.right!=i||this.padding.bottom!=s,this.padding.left=t,this.padding.top=e,this.padding.right=i,this.padding.bottom=s,this.setRadius(),this}get radius(){return this._radius}set radius(t){this.dirty=this.dirty||this._radius!=t,this._radius=t}setRadius(t){return this.radius=t,this.shapeMode=null==t?0:1,this}get verticeRotation(){return this._verticeRotation}set verticeRotation(t){this.dirty=this.dirty||this._verticeRotation!=t,this._verticeRotation=t}setVerticeRotation(t){return this.verticeRotation=t,this}get verticeAngle(){return Cg(this.verticeRotation)}set verticeAngle(t){this.verticeRotation=Sg(t)}setVerticeAngle(t){return this.verticeAngle=t,this}}const Pg={right:0,down:1,left:2,up:3};var Tg=function(t){return"string"==typeof t&&(t=Pg[t]),t%=4};Object.assign(Og.prototype,yg,bg);var _g=function(t,e,i){var s=new Og(t,e);return t.add.existing(s),s.on("expand.start",(function(t){t.setDirection("down")})).on("collapse.complete",(function(t){t.setDirection("right")})),s};const kg=Phaser.Utils.Objects.GetValue,Eg=Phaser.Utils.Objects.GetValue,Mg=Phaser.Utils.Objects.Clone,Rg=Phaser.Utils.Objects.GetValue;class Lg extends(Ph(Lh)){constructor(t,e){void 0===e&&(e={});var i=Ah(t,Rg(e,"background"),{isLeaf:!1},Vo,!1),s=function(t,e){var i=new Oh(t,{orientation:Eg(e,"childrenOrientation","y")});t.add.existing(i);var s=Ah(t,Eg(e,"childrenBackground"),{isLeaf:!1},Vo,!1);return s&&i.addBackground(s),i}(t,e),r=s.childrenMap.items,n=function(t,e){var i=new ag(t,e,{isLeaf:!1});t.add.existing(i);var s=Ah(t,kg(e,"toggleButton"),{isLeaf:!1},_g,!0);return i.insert(0,s,{padding:{right:kg(e,"space.toggleButton",0)},fitRatio:1}),i.addChildrenMap("toggleButton",s),i}(t,e),h=n.childrenMap.toggleButton,a=n.childrenMap.nodeBody,o=wh(Rg(e,"orientation","y")),l=e.space;if(l){var d=Rg(l,"indent",0);l.childLeft=Rg(l,"indentLeft",1===o?d:0),l.childRight=Rg(l,"indentRight",0),l.childTop=Rg(l,"indentTop",0===o?d:0),l.childBottom=Rg(l,"indentBottom",0)}super(t,{background:i,title:n,child:s,toggleByTarget:h,transition:e.transition,orientation:o,space:l,align:e.align,expand:e.expand}),this.type="rexTree",this.rexSizer.treeParent=null,this.nodesMap={},this.configSave=e,this.nodeBody=a,this.addChildrenMap("toggleButton",h),this.addChildrenMap("nodeBody",a),this.addChildrenMap("childrenNodes",r),this.on("expand.start",(function(){h.emit("expand.start",h),Dg(this,"tree.expand.start")}),this).on("expand.complete",(function(){h.emit("expand.complete",h),Dg(this,"tree.expand.complete")})).on("collapse.start",(function(){h.emit("collapse.start",h),Dg(this,"tree.collapse.start")})).on("collapse.complete",(function(){h.emit("collapse.complete",h),Dg(this,"tree.collapse.complete")}));var c=this;c._postAddCallback=function(){var t=Rg(e,"expanded",!0);void 0!==t&&c.setExpandedState(t),delete c._postAddCallback}}destroy(t){this.scene&&!this.ignoreDestroy&&(this.configSave=void 0,Clear(this.nodesMap),this.nodesMap=void 0,super.destroy(t))}get isTree(){return!0}createTree(t){return Lg.CreateTree(this.scene,this.configSave,t)}isTreeObject(t){return t&&t instanceof Lg}}Lg.CreateTree=function(t,e,i){return new Lg(t,function(t,e){var i=t?Mg(t):{};if(!e)return i;for(var s in e)i[s]=e[s];return i}(e,i))};var Dg=function(t,e){var i=t.getTreesSizer();i&&i.emit(e,t)};Object.assign(Lg.prototype,pg);const Ag=Phaser.Utils.String.UUID;var Yg={addTree(t){return yt(t)&&(t={nodeBody:t,nodeKey:nodeKey}),this.insertTree(void 0,t)},insertTree(t,e){var i;"string"==typeof e?(i=e,e=void 0):e&&(i=e.nodeKey,delete e.nodeKey),void 0===i&&(i=Ag());var s=Lg.CreateTree(this.scene,this.treeConfig,e);return og(this,s),s.nodeKey=i,this.treesMap[i]=s,this.insert(t,s,{expand:!0}),s._postAddCallback(),s}},zg={removeTree(t,e){return"string"==typeof t&&(t=this.getTree(t)),t?(delete this.treesMap[t.nodeKey],t.nodeKey=null,this.remove(t,e),this):this},removeAllNodes(t){var e=this.treesMap;for(var i in e)this.removeTree(e[i],t);return this}},Xg={getTree(t){return this.treesMap[t]},getTrees(t){for(var e in void 0===t&&(t=[]),this.treesMap)t.push(this.treesMap[e]);return t},getNode(t){var e=t.indexOf(".");if(-1===e)return this.getTree(t);var i=this.getTree(t.substring(0,e));return i?i.getNode(t.substring(e+1)):void 0}},Wg={pointToChild:function(t,e,i,s){for(var r in this.treesMap){var n=this.treesMap[r];if(hr(n.nodeBody,t,e,i,s))return n;var h=n.pointToChild(t,e,i,s);if(h)return h}return null},setChildrenInteractive:function(t){return void 0===t&&(t={}),t.targetMode="parent",t.targetSizers=[this],$n(this,t),this}};Object.assign(Wg,Yg,zg,Xg);const jg=Phaser.Utils.Objects.GetValue;class Fg extends Oh{constructor(t,e){void 0===e&&(e={}),e.hasOwnProperty("orientation")||(e.orientation="y"),super(t,e),this.type="rexTrees",this.treesMap={},this.treeConfig=jg(e,"tree")}destroy(t){this.scene&&!this.ignoreDestroy&&(this.treeConfig=void 0,Clear(this.treesMap),this.treesMap=void 0,super.destroy(t))}}return Object.assign(Fg.prototype,Wg),Fg},"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).rextrees=e(); + */const Xc=Phaser.Display.Canvas.CanvasPool;var Wc=function(t){var e=Xc.create(this),i=e.getContext("2d",{willReadFrequently:!0});t.syncFont(e,i);var s=i.measureText(t.testString);if("actualBoundingBoxAscent"in s){var r=s.actualBoundingBoxAscent,n=s.actualBoundingBoxDescent,h={ascent:r,descent:n,fontSize:r+n};return Xc.remove(e),h}var a=Math.ceil(s.width*t.baselineX),o=a,l=2*o;if(o=o*t.baselineY|0,e.width=a,e.height=l,i.fillStyle="#f00",i.fillRect(0,0,a,l),i.font=t._font,i.textBaseline="alphabetic",i.fillStyle="#000",i.fillText(t.testString,0,o),h={ascent:0,descent:0,fontSize:0},!i.getImageData(0,0,a,l))return h.ascent=o,h.descent=o+6,h.fontSize=h.ascent+h.descent,Xc.remove(e),h;var d,c,u=i.getImageData(0,0,a,l).data,p=u.length,v=4*a,g=0,f=!1;for(d=0;do;d--){for(c=0;c0&&this.wrapMode!==vl&&0===this.wrapWidth}setStyle(t,e,i){if(void 0===e&&(e=!0),void 0===i&&(i=!1),t&&t.hasOwnProperty("wordWrap")){var s=t.wordWrap;s.hasOwnProperty("width")&&(t.wrap={mode:"word",width:s.width})}if(t&&t.hasOwnProperty("wrap")){var r=t.wrap;if(r.hasOwnProperty("mode")){var n=r.mode;"string"==typeof n&&(r.mode=yl[n])}else r.hasOwnProperty("width")&&(r.mode=1)}t&&t.rtl&&i&&!t.hasOwnProperty("halign")&&(t.halign="right"),t&&t.hasOwnProperty("fontSize")&&"number"==typeof t.fontSize&&(t.fontSize=t.fontSize.toString()+"px");var h=this.propertyMap;for(var a in h){var o=h[a],l=o[0],d=i?o[1]:this[a],c=o[2];if("wrapCallback"===a||"wrapCallbackScope"===a)this[a]=Fc(t,l,d);else{var u=jc(t,l,d);c&&(u=c(u)),this[a]=u}}var p=Fc(t,"font",null);this._font=null===p?this.fontStyle+" "+this.fontSize+" "+this.fontFamily:p;var v=Fc(t,"fill",null);null!==v&&(this.color=Zl(v));var g=Fc(t,"metrics",!1);return g?this.metrics={ascent:Fc(g,"ascent",0),descent:Fc(g,"descent",0),fontSize:Fc(g,"fontSize",0)}:!e&&this.metrics||(this.metrics=Wc(this)),e?this.parent.updateText():this.parent}syncFont(t,e){e.font=this._font}syncStyle(t,e){e.textBaseline="alphabetic",e.fillStyle=this.color,e.strokeStyle=this.stroke,e.lineWidth=this.strokeThickness,e.lineCap="round",e.lineJoin="round"}syncShadow(t,e){e?(t.shadowOffsetX=this.shadowOffsetX,t.shadowOffsetY=this.shadowOffsetY,t.shadowColor=this.shadowColor,t.shadowBlur=this.shadowBlur):(t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowColor=0,t.shadowBlur=0)}update(t){return t&&(this._font=`${this.fontStyle} ${this.fontSize} ${this.fontFamily}`.trim(),this.metrics=Wc(this)),this.parent.updateText(t)}buildFont(){var t=`${this.fontStyle} ${this.fontSize} ${this.fontFamily}`.trim();return t!==this._font&&(this._font=t),this}setFont(t){return"string"==typeof t?(this.fontFamily=t,this.fontSize="",this.fontStyle=""):(this.fontFamily=Fc(t,"fontFamily","Courier"),this.fontSize=Fc(t,"fontSize","16px"),this.fontStyle=Fc(t,"fontStyle","")),this.update(!0)}setFontFamily(t){return this.fontFamily=t,this.update(!0)}setFontStyle(t){return this.fontStyle=t,this.update(!0)}setFontSize(t){return"number"==typeof t&&(t=t.toString()+"px"),this.fontSize=t,this.update(!0)}setTestString(t){return this.testString=t,this.update(!0)}setFixedSize(t,e){return this.fixedWidth=t,this.fixedHeight=e,t&&(this.parent.width=t),e&&(this.parent.height=e),this.update(this.isWrapFitMode)}setResolution(t){return this.resolution=t,this.update(!1)}setXOffset(t){return this.xOffset=t,this.update(!1)}setBackgroundColor(t,e,i){return void 0===i&&(i=!0),this.backgroundColor=Zl(t,this.parent.canvas,this.parent.context),this.backgroundColor2=Zl(e,this.parent.canvas,this.parent.context),this.backgroundHorizontalGradient=i,this.update(!1)}setBackgroundStrokeColor(t,e){return this.backgroundStrokeColor=Zl(t,this.parent.canvas,this.parent.context),this.backgroundStrokeLineWidth=e,this.update(!1)}setBackgroundCornerRadius(t,e){return this.backgroundCornerRadius=t,this.backgroundCornerIteration=e,this.update(!1)}setFill(t){return this.color=Zl(t,this.parent.canvas,this.parent.context),this.update(!1)}setColor(t){return this.color=Zl(t,this.parent.canvas,this.parent.context),this.update(!1)}setStroke(t,e){return void 0===t?this.strokeThickness=0:(void 0===e&&(e=this.strokeThickness),this.stroke=Zl(t,this.parent.canvas,this.parent.context),this.strokeThickness=e),this.update(!0)}setShadow(t,e,i,s,r,n){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i="#000"),void 0===s&&(s=0),void 0===r&&(r=!1),void 0===n&&(n=!0),this.shadowOffsetX=t,this.shadowOffsetY=e,this.shadowColor=Zl(i,this.parent.canvas,this.parent.context),this.shadowBlur=s,this.shadowStroke=r,this.shadowFill=n,this.update(!1)}setShadowOffset(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.shadowOffsetX=t,this.shadowOffsetY=e,this.update(!1)}setShadowColor(t){return void 0===t&&(t="#000"),this.shadowColor=Zl(t,this.parent.canvas,this.parent.context),this.update(!1)}setShadowBlur(t){return void 0===t&&(t=0),this.shadowBlur=t,this.update(!1)}setShadowStroke(t){return this.shadowStroke=t,this.update(!1)}setShadowFill(t){return this.shadowFill=t,this.update(!1)}setUnderline(t,e,i){return void 0===t&&(t="#000"),void 0===e&&(e=0),void 0===i&&(i=0),this.underlineColor=Zl(t,this.parent.canvas,this.parent.context),this.underlineThickness=e,this.underlineOffset=i,this.update(!1)}setUnderlineColor(t){return void 0===t&&(t="#000"),this.underlineColor=Zl(t,this.parent.canvas,this.parent.context),this.update(!1)}setUnderlineThickness(t){return void 0===t&&(t=0),this.underlineThickness=t,this.update(!1)}setUnderlineOffset(t){return void 0===t&&(t=0),this.underlineOffset=t,this.update(!1)}setStrikethrough(t,e,i){return void 0===t&&(t="#000"),void 0===e&&(e=0),void 0===i&&(i=0),this.strikethroughColor=Zl(t,this.parent.canvas,this.parent.context),this.strikethroughThickness=e,this.strikethroughOffset=i,this.update(!1)}setStrikethroughColor(t){return void 0===t&&(t="#000"),this.strikethroughColor=Zl(t,this.parent.canvas,this.parent.context),this.update(!1)}setStrikethroughThickness(t){return void 0===t&&(t=0),this.strikethroughThickness=t,this.update(!1)}setStrikethroughOffset(t){return void 0===t&&(t=0),this.strikethroughOffset=t,this.update(!1)}setWrapMode(t){return"string"==typeof t&&(t=yl[t.toLowerCase()]||0),this.wrapMode=t,this.update(!0)}setWrapWidth(t){return this.wrapWidth=t,this.update(!1)}setAlign(t,e){return void 0===t&&(t="left"),void 0===e&&(e="top"),this.halign=t,this.valign=e,this.update(!1)}setHAlign(t){return void 0===t&&(t="left"),this.halign=t,this.update(!1)}setVAlign(t){return void 0===t&&(t="top"),this.valign=t,this.update(!1)}setMaxLines(t){return void 0===t&&(t=0),this.maxLines=t,this.update(!1)}getTextMetrics(){var t=this.metrics;return{ascent:t.ascent,descent:t.descent,fontSize:t.fontSize}}setTextMetrics(t,e){return this.metrics.ascent=t.ascent,this.metrics.descent=t.descent,this.metrics.fontSize=t.fontSize,e&&("string"==typeof e?(this.fontFamily=e,this.fontSize="",this.fontStyle=""):(this.fontFamily=Fc(e,"fontFamily",this.fontFamily),this.fontSize=Fc(e,"fontSize",this.fontSize),this.fontStyle=Fc(e,"fontStyle",this.fontStyle))),this.parent.updateText(!0)}get lineHeight(){return this.metrics.fontSize+this.parent.lineSpacing}toJSON(){var t={},e=this.propertyMap;for(var i in e)t[i]=this[i];return t.metrics=this.getTextMetrics(),t}destroy(){this.parent=void 0}}var Bc={draw(t,e,i,s){var r=this.penManager;this.hitAreaManager.clear();var n=this.context;n.save();var h=this.defaultStyle;this.clear(),nd(this,h.backgroundColor,h.backgroundStrokeColor,h.backgroundStrokeLineWidth,h.backgroundCornerRadius,h.backgroundColor2,h.backgroundHorizontalGradient,h.backgroundCornerIteration),t+=this.startXOffset,e+=this.startYOffset;var a,o,l,d,c,u,p=h.halign,v=h.valign,g=h.lineHeight,f=r.lines,m=f.length,y=h.maxLines;y>0&&m>y?(o=y,l="center"===v?Math.floor((m-o)/2):"bottom"===v?m-o:0):(o=m,l=0),d=l+o;var b=this.rtl,x=b?this.parent.width:void 0;u="center"===v?Math.max((s-o*g)/2,0):"bottom"===v?Math.max(s-o*g-2,0):0,u+=e;for(var w=l;w0){var a=this.defaultStyle.metrics,o=i-a.ascent,l=a.fontSize;this.drawRectangle(e,o,t.width,l,h.bgcolor,h)}if(h.underlineThickness>0&&t.width>0){var d=i+h.underlineOffset-h.underlineThickness/2;this.drawLine(e,d,t.width,h.underlineThickness,h.underlineColor,h)}if(t.isTextPen&&(h.buildFont(),h.syncFont(r,n),h.syncStyle(r,n),this.drawText(e,i,t.text,h)),t.isImagePen&&this.drawImage(e,i,t.prop.img,t.prop.color,h),h.strikethroughThickness>0&&t.width>0&&(d=i+h.strikethroughOffset-h.strikethroughThickness/2,this.drawLine(e,d,t.width,h.strikethroughThickness,h.strikethroughColor,h)),n.restore(),t.hasAreaMarker&&t.width>0){var c,u=t.prop.area;if(u)c={key:u};else{var p=t.prop.url;c={key:`url:${p}`,url:p}}this.hitAreaManager.add(e,i-this.startYOffset,t.width,this.defaultStyle.lineHeight,c)}},clear(){var t=this.canvas;this.context.clearRect(0,0,t.width,t.height)},drawRectangle(t,e,i,s,r,n){this.autoRound&&(t=Math.round(t),e=Math.round(e));var h=this.context;h.fillStyle=r,h.fillRect(t,e,i,s)},drawLine(t,e,i,s,r,n){this.autoRound&&(t=Math.round(t),e=Math.round(e));var h=this.context;n.syncShadow(h,n.shadowStroke);var a=h.lineCap;h.lineCap="butt",h.strokeStyle=r,h.lineWidth=s,h.beginPath(),h.moveTo(t,e),h.lineTo(t+i,e),h.stroke(),h.lineCap=a},drawText(t,e,i,s){this.autoRound&&(t=Math.round(t),e=Math.round(e));var r=this.context;s.stroke&&"none"!==s.stroke&&s.strokeThickness>0&&(s.syncShadow(r,s.shadowStroke),r.strokeText(i,t,e)),s.color&&"none"!==s.color&&(s.syncShadow(r,s.shadowFill),r.fillText(i,t,e))},drawImage(t,e,i,s,r){e-=this.startYOffset,this.parent.imageManager.draw(i,this.context,t,e,s,this.autoRound)}};const Hc=Phaser.Utils.Objects.GetValue,Nc=cl,Gc=ul;class Vc{constructor(t){this.prop={},this.resetFromJSON(t)}resetFromJSON(t){this.text=Hc(t,"text",""),this.x=Hc(t,"x",0),this.y=Hc(t,"y",0),this.width=Hc(t,"width",0);var e=Hc(t,"prop",null);null===e&&(e={}),this.prop=e,this.newLineMode=Hc(t,"newLineMode",0),this.startIndex=Hc(t,"startIndex",0)}get plainText(){var t=this.text;return this.newLineMode===Gc&&(t+="\n"),t}get wrapText(){var t=this.text;return this.newLineMode!==Nc&&(t+="\n"),t}get rawTextLength(){var t=this.text.length;return this.newLineMode===Gc&&(t+=1),t}get endIndex(){return this.startIndex+this.rawTextLength}get lastX(){return this.x+this.width}get isTextPen(){return""!==this.text}get isImagePen(){return!!this.prop.img}get hasAreaMarker(){return!!this.prop.area||!!this.prop.url}}const Uc=Phaser.Utils.Objects.GetFastValue,$c=cl,Jc=pl;class Kc{constructor(t){this.pens=[],this.lines=[],this.maxLinesWidth=void 0,this.pensPool=t.pensPool,this.linesPool=t.linesPool,this.tagToText=Uc(t,"tagToText",zt),this.tagToTextScope=Uc(t,"tagToTextScope",void 0)}destroy(){this.clear(),this.tagToText=void 0,this.tagToTextScope=void 0}clear(){for(var t=0,e=this.lines.length;t=this.lines.length)return this.getLineEndIndex(t);var e=this.lines[t];return e&&e[0]?e[0].startIndex:0}getLineEndIndex(t){t>=this.lines.length&&(t=this.lines.length-1);var e,i,s=!1;for(e=t;e>=0&&!(s=null!=(i=this.lines[e])&&i.length>0);e--);return s?i[i.length-1].endIndex:0}getLineWidth(t){var e=this.lines[t];if(!e)return 0;var i=e[e.length-1];return null==i?0:i.lastX}getMaxLineWidth(){if(void 0!==this.maxLinesWidth)return this.maxLinesWidth;for(var t,e=0,i=0,s=this.lines.length;ie&&(e=t);return this.maxLinesWidth=e,e}getLineWidths(){for(var t=[],e=0,i=this.lines.length;e=t&&o<=e||(h=h.substring(t-a,e-a)),this.tagToTextScope?c+=this.tagToText.call(this.tagToTextScope,h,l,d):c+=this.tagToText(h,l,d),d=l,!(o>=e)));u++);return c}get length(){return this.lines.length}set length(t){this.clear()}}var qc={};const Zc=Phaser.Geom.Rectangle;var Qc=new cc;class tu{constructor(){this.hitAreas=[]}destroy(){this.clear()}clear(){for(var t=0,e=this.hitAreas.length;ts&&vu(g)){""!==b?h.push(n.getLine(b,x,au)):0===w&&r>0&&h.push(n.getLine("",0,au)),h.push(...uu(g,e,du,s,0,n));var C=h.pop();b=C.text,x=C.width,n.freeLine(C)," "===b&&(b="",x=0)}else(m=x+f)>o?(h.push(n.getLine(b,x,au)),b=g,x=f,o=s):(b+=g,x=m),w===S-1&&h.push(n.getLine(b,x,l))}return h},pu=function(t,e){var i;switch(e){case lu:i=[];for(var s=0,r=(t=t.split(" ")).length;s0&&e!==fu&&i0&&t>e&&(t=e),t}get linesWidth(){return Math.ceil(this.penManager.getMaxLineWidth())}get linesHeight(){var t=this.displayLinesCount,e=this.defaultStyle.lineHeight*t;return t>0&&(e-=this.defaultStyle.lineSpacing),e}get imageManager(){return this.parent.imageManager}get rtl(){return this.parent.style.rtl}newPenManager(){return new Kc({pensPool:this.pensPool,linesPool:this.linesPool,tagToText:this.parser.propToTagText,tagToTextScope:this.parser})}get tmpPenManager(){return null===this._tmpPenManager&&(this._tmpPenManager=this.newPenManager()),this._tmpPenManager}getPlainText(t,e,i){var s;if(null==t)s=this.penManager.plainText;else{var r=this.parser.splitText(t,1);s="";for(var n=0,h=r.length;n=0;e--){var i=this.sizerChildren[e];i&&this.remove(i,t)}return this},clear(t){return Sp(this.sizerChildren,null),ch.call(this,t),this}},Op={setColumnSpace(t){if(this.space.column||(this.space.column=[]),this.space.column.length=this.columnCount-1,"number"==typeof t)Sp(this.space.column,t);else for(var e=0,i=this.columnCount-1;e=0;s--){var r=s*this.columnCount+t;this.sizerChildren.splice(r,0,null)}return this.columnProportions.push(e),this.columnWidth.length+=1,this.space.column.splice(t,0,i),this},kp={getChildrenWidth:function(t){if(this.rexSizer.hidden)return 0;void 0===t&&(t=!0);var e,i,s,r,n,h=0,a=this.sizerChildren,o=!1;this.totalColumnProportions;for(var l=0;l0){var i=t-this.getChildrenWidth(!1);i>=0&&(this.proportionWidthLength=i/e)}else this.proportionWidthLength=0}return t},resolveHeight:function(t){if(void 0!==(t=Ae.call(this,t))&&void 0===this.proportionHeightLength){var e=this.totalRowProportions;if(e>0){var i=t-this.getChildrenHeight(!1);i>=0&&(this.proportionHeightLength=i/e)}else this.proportionHeightLength=0}return t},resolveChildrenWidth:function(t){var e,i,s,r;for(var n in this.sizerChildren)(e=this.sizerChildren[n])&&e.isRexSizer&&!e.ignoreLayout&&(r=this.getColumnWidth(parseInt(n)%this.columnCount),i=this.getExpandedChildWidth(e,r),void 0===(s=e.resolveWidth(i))&&(s=i),e.resolveChildrenWidth(s))},resolveChildrenHeight:function(t){var e,i,s,r;for(var n in this.sizerChildren)(e=this.sizerChildren[n])&&e.isRexSizer&&!e.ignoreLayout&&(r=this.getRowHeight(Math.floor(parseInt(n)/this.rowCount)),i=this.getExpandedChildHeight(e,r),void 0===(s=e.resolveHeight(i))&&(s=i),e.resolveChildrenHeight(s))},runWidthWrap:function(t){var e,i,s,r;for(var n in this.sizerChildren)!(e=this.sizerChildren[n])||e.isRexSizer&&e.ignoreLayout||!e.runWidthWrap||(r=this.getColumnWidth(parseInt(n)%this.columnCount),i=this.getExpandedChildWidth(e,r),e.isRexSizer&&void 0===(s=e.resolveWidth(i))&&(s=i),e.runWidthWrap(s));return this},runHeightWrap:function(t){var e,i,s,r;for(var n in this.sizerChildren)!(e=this.sizerChildren[n])||e.isRexSizer&&e.ignoreLayout||!e.runHeightWrap||(r=this.getRowHeight(Math.floor(parseInt(n)/this.rowCount)),i=this.getExpandedChildHeight(e,r),e.isRexSizer&&void 0===(s=e.resolveHeight(i))&&(s=i),e.runHeightWrap(s));return this},resetGrid:function(t,e,i,s,r){if(void 0===i&&(i=0),void 0===s&&(s=0),this.columnCount=t,this.rowCount=e,this.gridCount=t*e,this.removeAll(),this.sizerChildren.length=t*e,Sp(this.sizerChildren,null),this.columnProportions=[],this.columnProportions.length=t,"number"==typeof i)Sp(this.columnProportions,i);else for(var n=0;n0?e+=t:0===t&&(this.hasColumnProportion0Child=!0);return e},Mp=function(){for(var t,e=0,i=0;i0?e+=t:0===t&&(this.hasRowProportion0Child=!0);return e};const Rp=Phaser.Utils.Objects.IsPlainObject,Lp=Phaser.Utils.Objects.GetValue;class Dp extends qn{constructor(t,e,i,s,r,n,h,a,o,l){Rp(e)?(e=Lp(l=e,"x",0),i=Lp(l,"y",0),s=Lp(l,"width",void 0),r=Lp(l,"height",void 0),n=Lp(l,"column",l.col||0),h=Lp(l,"row",0),a=Lp(l,"columnProportions",0),o=Lp(l,"rowProportions",0)):Rp(s)?(s=Lp(l=s,"width",void 0),r=Lp(l,"height",void 0),n=Lp(l,"column",l.col||0),h=Lp(l,"row",0),a=Lp(l,"columnProportions",0),o=Lp(l,"rowProportions",0)):Rp(n)?(n=Lp(l=n,"column",l.col||0),h=Lp(l,"row",0),a=Lp(l,"columnProportions",0),o=Lp(l,"rowProportions",0)):Rp(a)&&(a=Lp(l=a,"columnProportions",0),o=Lp(l,"rowProportions",0)),super(t,e,i,s,r,l),this.type="rexGridSizer",this.sizerChildren=[],this.addChildrenMap("items",this.sizerChildren),this.setCreateCellContainerCallback(Lp(l,"createCellContainerCallback")),this.setIndentLeft(Lp(l,"space.indentLeftOdd",0),Lp(l,"space.indentLeftEven",0)),this.setIndentTop(Lp(l,"space.indentTopOdd",0),Lp(l,"space.indentTopEven",0)),this.resetGrid(n,h,a,o,Lp(l,"space",void 0))}destroy(t){this.scene&&!this.ignoreDestroy&&(super.destroy(t),this.columnProportions=void 0,this.rowProportions=void 0,this.columnWidth=void 0,this.rowHeight=void 0,this.createCellContainerCallback=void 0)}setColumnProportion(t,e){return t>=this.columnProportions.length||(this.columnProportions[t]=e),this}setRowProportion(t,e){return t>=this.rowProportions.length||(this.rowProportions[t]=e),this}get totalColumnProportions(){return void 0===this._totalColumnProportions&&(this._totalColumnProportions=Ep.call(this)),this._totalColumnProportions}get totalRowProportions(){return void 0===this._totalRowProportions&&(this._totalRowProportions=Mp.call(this)),this._totalRowProportions}getChildAt(t,e){return this.sizerChildren[e*this.columnCount+t]}childToGridIndex(t,e){if(!t)return null;var i=this.sizerChildren.indexOf(t);return-1===i?null:(void 0===e&&(e={}),e.x=i%this.columnCount,e.y=Math.floor(i/this.columnCount),e)}getColumnWidth(t){var e=this.columnProportions[t];return 0===e?this.columnWidth[t]:e*this.proportionWidthLength}getRowHeight(t){var e=this.rowProportions[t];return 0===e?this.rowHeight[t]:e*this.proportionHeightLength}setCreateCellContainerCallback(t){return this.createCellContainerCallback=t,this}}Object.assign(Dp.prototype,kp);const Ap=Phaser.Utils.Objects.GetValue,Yp=Phaser.Math.Percent;var zp=function(t,e,i){var s;return t.y===e.y?s=Yp(i.x,t.x,e.x):t.x===e.x&&(s=Yp(i.y,t.y,e.y)),s},Xp=function(t,e,i){var s,r;this.enable&&(Wp.x=e,Wp.y=i,this.reverseAxis?(s=this.getEndPoint(),r=this.getStartPoint()):(s=this.getStartPoint(),r=this.getEndPoint()),this.value=zp(s,r,Wp))},Wp={},jp=function(t,e,i){if(this.enable&&t.isDown){var s,r;Fp.x=t.worldX,Fp.y=t.worldY,this.reverseAxis?(s=this.getEndPoint(),r=this.getStartPoint()):(s=this.getStartPoint(),r=this.getEndPoint());var n=zp(s,r,Fp);this.stopEaseValue(),0===this.easeValueDuration||Math.abs(this.value-n)<.1?this.value=n:this.easeValueTo(n)}},Fp={},Ip=function(t,e){void 0===e&&(e=Bp);var i=this.childrenMap.thumb,s=i.x,r=i.y;return he(i,this.innerLeft,this.innerTop,this.innerWidth,this.innerHeight,t),e.x=i.x,e.y=i.y,i.x=s,i.y=r,e},Bp={};const Hp=Phaser.Display.Align.LEFT_CENTER,Np=Phaser.Display.Align.TOP_CENTER;var Gp={};const Vp=Phaser.Display.Align.RIGHT_CENTER,Up=Phaser.Display.Align.BOTTOM_CENTER;var $p={};const Jp=Phaser.Math.Linear;var Kp={};const qp=Phaser.Display.Align.LEFT_CENTER,Zp=Phaser.Display.Align.TOP_CENTER,Qp=Phaser.Display.Align.RIGHT_CENTER,tv=Phaser.Display.Align.BOTTOM_CENTER,ev=Phaser.Utils.Objects.GetValue,iv=Phaser.Utils.Objects.IsPlainObject,sv=Phaser.Math.Clamp,rv=Phaser.Math.Snap.To;class nv extends(_a(Oh)){constructor(t,e){super(t,e),this.type="rexSlider",this.bootProgressBase(e),this.reverseAxis=ev(e,"reverseAxis",!1);var i=ev(e,"background",void 0),s=ev(e,"track",void 0),r=ev(e,"indicator",void 0),n=ev(e,"thumb",void 0);if(i&&(iv(i)&&(i=Go(t,i)),this.addBackground(i)),s&&(iv(s)&&(s=Go(t,s)),this.add(s,{proportion:1,expand:!0,minWidth:0===this.orientation?0:void 0,minHeight:1===this.orientation?0:void 0})),r&&(iv(r)&&(r=Go(t,r)),this.pin(r)),n){iv(n)&&(n=Go(t,n)),this.pin(n);var h=ev(e,"thumbOffsetX",0),a=ev(e,"thumbOffsetY",0);this.setThumbOffset(h,a)}var o=ev(e,"input",0);switch("string"==typeof o&&(o=hv[o]),o){case 0:n&&(n.setInteractive(),this.scene.input.setDraggable(n),n.on("drag",Xp,this).on("dragstart",(function(t){this.eventEmitter.emit("inputstart",t)}),this).on("dragend",(function(t){this.eventEmitter.emit("inputend",t)}),this));break;case 1:this.on("pointerdown",jp,this).on("pointermove",jp,this).on("pointerdown",(function(t){this.eventEmitter.emit("inputstart",t)}),this).on("pointerup",(function(t){this.eventEmitter.emit("inputend",t)}),this).on("pointerover",(function(t){t.isDown&&this.eventEmitter.emit("inputstart",t)}),this).on("pointerout",(function(t){t.isDown&&this.eventEmitter.emit("inputend",t)}),this).setInteractive()}this.addChildrenMap("background",i),this.addChildrenMap("track",s),this.addChildrenMap("indicator",r),this.addChildrenMap("thumb",n),this.setEnable(ev(e,"enable",void 0)),this.setGap(ev(e,"gap",void 0)),this.setValue(ev(e,"value",0),ev(e,"min",void 0),ev(e,"max",void 0))}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}setGap(t,e,i){return t&&void 0!==e&&(t/=i-e),this.gap=t,this}setThumbOffset(t,e){return this.thumbOffsetX=t,this.thumbOffsetY=e,this}get value(){return this._value}set value(t){void 0!==this.gap&&(t=rv(t,this.gap));var e=this._value;this._value=sv(t,0,1),e!==this._value&&(this.updateThumb(this._value),this.updateIndicator(this._value),this.eventEmitter.emit("valuechange",this._value,e,this.eventEmitter))}postLayout(t,e,i){return this.updateThumb(),this.updateIndicator(),super.postLayout(t,e,i),this}}const hv={pan:0,drag:0,click:1,none:-1};var av={getStartPoint:function(t){if(void 0===t&&(t=Gp),this.childrenMap.thumb){var e=0===this.orientation?Hp:Np;Ip.call(this,e,t)}else 0===this.orientation?(t.x=this.innerLeft+1,t.y=this.centerY):(t.x=this.centerX,t.y=this.innerTop+1);return t},getEndPoint:function(t){if(void 0===t&&(t=$p),this.childrenMap.thumb){var e=0===this.orientation?Vp:Up;Ip.call(this,e,t)}else 0===this.orientation?(t.x=this.innerRight-1,t.y=this.centerY):(t.x=this.centerX,t.y=this.innerBottom-1);return t},updateThumb:function(t){var e,i,s=this.childrenMap.thumb;return void 0===s||(void 0===t&&(t=this.value),this.reverseAxis?(e=this.getEndPoint(),i=this.getStartPoint()):(e=this.getStartPoint(),i=this.getEndPoint()),function(t,e,i,s){void 0===s&&(s=Kp),s.x=Jp(e.x,i.x,t),s.y=Jp(e.y,i.y,t)}(t,e,i,s),s.x+=this.thumbOffsetX,s.y+=this.thumbOffsetY,this.resetChildPositionState(s)),this},updateIndicator:function(t){var e=this.childrenMap.indicator;if(void 0===e)return this;void 0===t&&(t=this.value);var i,s,r,n=this.reverseAxis,h=this.childrenMap.thumb;if(h)if(0===this.orientation){var a,o=Q(h);if(n)a=h.x-o*h.originX,i=this.right-a;else i=(a=h.x-o*h.originX)+o-this.left}else{var l,d=tt(h);if(n)l=h.y-d*h.originY,s=this.bottom-l;else s=(l=h.y-d*h.originY)+d-this.top}else 0===this.orientation?i=this.width*t:s=this.height*t;Ie(e,i,s),r=n?0===this.orientation?Qp:tv:0===this.orientation?qp:Zp,ne(e,this,r),this.resetChildPositionState(e)}};Object.assign(nv.prototype,av);const ov=Phaser.Utils.Objects.GetValue;class lv extends Oh{constructor(t,e){super(t,e),this.type="rexScrollBar";var i,s,r=ov(e,"background",void 0),n=ov(e,"buttons",void 0),h=ov(n,"top",ov(n,"left",void 0)),a=ov(n,"bottom",ov(n,"right",void 0)),o=ov(e,"slider",void 0);(r&&this.addBackground(r),h&&(this.add(h),new _r(h).on("intouch",(function(){if(this.enable){var t=i.reverseAxis?this.scrollStep:-this.scrollStep;this.value+=t}}),this)),o)&&(o.orientation=this.orientation,o.eventEmitter=this,o.value=null,s=0===this.orientation?void 0===ov(o,"width",void 0)?1:0:void 0===ov(o,"height",void 0)?1:0,i=new nv(t,o),t.add.existing(i),this.add(i,{proportion:s}));a&&(this.add(a),new _r(a).on("intouch",(function(){if(this.enable){var t=i.reverseAxis?-this.scrollStep:this.scrollStep;this.value+=t}}),this));var l=[h,a];this.addChildrenMap("background",r),this.addChildrenMap("slider",i),this.addChildrenMap("buttons",l);var d=ov(e,"valuechangeCallback",null);if(null!==d){var c=ov(e,"valuechangeCallbackScope",void 0);this.on("valuechange",d,c)}this.setEnable(ov(e,"enable",void 0)),this.setValue(ov(e,"value",0)),this.setScrollStep(ov(n,"step",.01))}setScrollStep(t){return this.scrollStep=t,this}get enable(){return!!this.childrenMap.slider&&this.childrenMap.slider.enable}set enable(t){this.childrenMap.slider&&this.childrenMap.slider.setEnable(t)}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}get value(){return this.childrenMap.slider?this.childrenMap.slider.value:0}set value(t){this.childrenMap.slider&&(this.childrenMap.slider.value=t)}setValue(t,e,i){return this.childrenMap.slider&&this.childrenMap.slider.setValue(t,e,i),this}addValue(t,e,i){return this.childrenMap.slider&&this.childrenMap.slider.addValue(t,e,i),this}getValue(t,e){return this.childrenMap.slider?this.childrenMap.slider.getValue(t,e):0}easeValueTo(t,e,i){return this.childrenMap.slider&&this.childrenMap.slider.easeValueTo(t,e,i),this}stopEaseValue(){return this.childrenMap.slider&&this.childrenMap.slider.stopEaseValue(),this}setEaseValueDuration(t){return this.childrenMap.slider&&this.childrenMap.slider.setEaseValueDuration(t),this}setEaseValueFunction(t){return this.childrenMap.slider&&this.childrenMap.slider.setEaseValueFunction(t),this}}class dv extends ks{constructor(t,e){super(e),this.parent=t,this.init()}init(){this.start("IDLE")}next_IDLE(){var t,e=this.parent;return e.dragState.isDown&&(t=0===e.dragThreshold?"DRAG":"DRAGBEGIN"),t}update_IDLE(t,e){this.next()}next_DRAGBEGIN(){var t=this.parent,e=t.dragState;return e.isDown?e.pointer.getDistance()>=t.dragThreshold?"DRAG":"DRAGBEGIN":"IDLE"}update_DRAGBEGIN(t,e){this.next()}next_DRAG(){var t,e=this.parent;return e.dragState.isUp&&(t=e.outOfBounds?"BACK":e.slidingEnable?"SLIDE":"IDLE"),t}update_DRAG(t,e){var i=this.parent;i.dragState.justMoved&&i.dragging(),this.next()}enter_DRAG(){this.parent.onDragStart()}exit_DRAG(){this.parent.onDragEnd()}next_SLIDE(){var t,e=this.parent;return e.dragState.isDown?t="DRAG":e.isSliding||(t="IDLE"),t}enter_SLIDE(){this.parent.onSliding()}exit_SLIDE(){this.parent.stop()}update_SLIDE(t,e){this.parent.sliding(t,e),this.next()}next_BACK(){var t,e=this.parent;return e.dragState.isDown?t="DRAG":e.isPullBack||(t="IDLE"),t}enter_BACK(){this.parent.onPullBack()}exit_BACK(){this.parent.stop()}update_BACK(t,e){this.parent.pullBack(t,e),this.next()}}const cv=Phaser.Utils.Objects.GetValue,uv=Phaser.Math.Distance.Between;class pv extends Qe{constructor(t,e){super(t,e),this._enable=void 0,this.rectBoundsInteractive=cv(e,"rectBoundsInteractive",!1),this.rectBoundsInteractive||t.setInteractive(cv(e,"inputConfig",void 0)),this.resetFromJSON(e),this.boot()}resetFromJSON(t){return this.pointer=void 0,this.isInTouched=!1,this.holdStartTime=void 0,this.x=void 0,this.y=void 0,this.preX=void 0,this.preY=void 0,this.localX=void 0,this.localY=void 0,this.justMoved=!1,this.setEnable(cv(t,"enable",!0)),this.holdThreshold=cv(t,"holdThreshold",50),this.pointerOutReleaseEnable=cv(t,"pointerOutRelease",!0),this}boot(){var t=this.scene,e=this.parent;this.rectBoundsInteractive?(t.input.on("pointerdown",this.onPointIn,this),t.input.on("pointerup",this.onPointOut,this),t.input.on("pointermove",this.onPointerMove,this)):(e.on("pointerdown",this.onPointIn,this),e.on("pointerup",this.onPointOut,this),this.pointerOutReleaseEnable&&e.on("pointerout",this.onPointOut,this),e.on("pointermove",this.onPointerMove,this)),t.sys.events.on("preupdate",this.preupdate,this)}shutdown(t){if(!this.isShutdown){var e=this.scene;this.parent,this.rectBoundsInteractive&&(e.input.off("pointerdown",this.onPointIn,this),e.input.off("pointerup",this.onPointOut,this),e.input.off("pointermove",this.onPointerMove,this)),e.sys.events.off("preupdate",this.preupdate,this),this.pointer=void 0,super.shutdown(t)}}get enable(){return this._enable}set enable(t){this._enable!==t&&(t||(this.isInTouched=!1,this.pointer=void 0),this._enable=t)}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}toggleEnable(){return this.setEnable(!this.enable),this}setPointerOutReleaseEnable(t){return void 0===t&&(t=!0),this.pointerOutReleaseEnable=t,this}get isDown(){return this.pointer&&this.pointer.isDown}get isUp(){return!this.isDown}get dx(){return this.x-this.preX}get dy(){return this.y-this.preY}get dt(){return an(this.scene)}get speed(){return this.x===this.preX&&this.y===this.preY?0:uv(this.preX,this.preY,this.x,this.y)/(.001*this.dt)}get speedX(){return this.dx/(.001*this.dt)}get speedY(){return this.dy/(.001*this.dt)}onPointIn(t,e,i){this.enable&&t.isDown&&void 0===this.pointer&&(this.rectBoundsInteractive&&!nr(this.parent,t)||(this.pointer=t,this.localX=e,this.localY=i))}onPointOut(t){this.enable&&this.pointer===t&&(this.pointer=void 0)}onPointerMove(t,e,i){this.enable&&t.isDown&&this.pointer===t&&(this.rectBoundsInteractive&&this.pointerOutReleaseEnable&&!nr(this.parent,t)?this.onPointOut(t):(this.localX=e,this.localY=i))}preupdate(t,e){if(this.enable){var i=this.pointer;this.justMoved=!1,i&&!this.isInTouched?(this.x=i.worldX,this.y=i.worldY,this.preX=i.worldX,this.preY=i.worldY,this.isInTouched=!0,this.holdStartTime=void 0,this.emit("touchstart",i,this.localX,this.localY)):i&&this.isInTouched?this.x===i.x&&this.y===i.y?void 0===this.holdStartTime?this.holdStartTime=t:t-this.holdStartTime>this.holdThreshold&&(this.preX=this.x,this.preY=this.y):(this.preX=this.x,this.preY=this.y,this.x=i.worldX,this.y=i.worldY,this.holdStartTime=void 0,this.justMoved=!0,this.emit("touchmove",i,this.localX,this.localY)):!i&&this.isInTouched&&(this.isInTouched=!1,this.holdStartTime=void 0,this.emit("touchend",i))}}}const vv=Phaser.Utils.Objects.GetValue;class gv{constructor(t){this.resetFromJSON(t)}resetFromJSON(t){return this.setValue(vv(t,"value",0)),this.setSpeed(vv(t,"speed",0)),this.setAcceleration(vv(t,"acceleration",0)),this}reset(){this.setValue(0),this.setSpeed(0),this.setAcceleration(0)}setValue(t){return this.value=t,this}setSpeed(t){return this.speed=t,this}setAcceleration(t){return this.acceleration=t,this}updateSpeed(t){return 0!==this.acceleration&&(this.speed+=this.acceleration*t,this.speed<0&&(this.speed=0)),this}getDeltaValue(t){return this.updateSpeed(t),this.speed<=0?0:this.speed*t}update(t){return this.updateSpeed(t),this.speed>0&&(this.value+=this.getDeltaValue(t)),this}get isMoving(){return this.speed>0}}class fv{constructor(){this.value,this.dir,this.movement=new gv}init(t,e,i,s,r){return this.value=t,this.end=r,this.dir=void 0!==r?tthis.end&&(this.value=this.end):this.valuethis.maxValue}overMin(t){return null!=this.minValue&&t0,Math.abs(e),i)}sliding(t,e){e*=.001;var i=this._slowDown.update(e).value;this.overMax(i)?(this.value=this.maxValue,this._slowDown.stop()):this.overMin(i)?(this.value=this.minValue,this._slowDown.stop()):this.value=i}onPullBack(){var t=this.value,e=this.outOfMinBound?this.minValue:this.maxValue,i=Math.abs(e-t),s=this.backDeceleration,r=Math.sqrt(2*s*i);this._slowDown.init(t,void 0,r,s,e)}pullBack(t,e){e*=.001,this.value=this._slowDown.update(e).value,this._slowDown.isMoving||this._state.next()}stop(){this._slowDown.stop()}}const xv={y:0,v:0,vertical:0,x:1,h:1,horizontal:1},wv=Phaser.Utils.Objects.GetValue;class Sv extends Qe{constructor(t,e){switch(super(t,e),this.parent!==this.scene?this.focusMode=wv(e,"focus",!0):this.focusMode=!1,"boolean"==typeof this.focusMode&&(this.focusMode=this.focusMode?1:0),this.setSpeed(wv(e,"speed",.1)),this.setEnable(wv(e,"enable",!0)),this.focusMode){case 0:case 2:this.scene.input.on("wheel",this.onSceneScroll,this);break;default:t.setInteractive(wv(e,"inputConfig",void 0)).on("wheel",(function(t,e,i,s,r){this.tryScroll(i)}),this)}}destroy(){switch(this.focusMode){case 0:case 2:this.scene.input.off("wheel",this.onSceneScroll,this)}}onSceneScroll(t,e,i,s,r,n){(2!==this.focusMode||nr(this.parent,t))&&this.tryScroll(s)}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}setSpeed(t){return this.speed=t,this}tryScroll(t){if(this.enable)return this.scroll(t),this}scroll(t){return t*=this.speed,this.emit("scroll",t,this.parent,this),this}}const Cv=Phaser.Utils.Objects.GetValue;var Ov=function(t,e,i,s){var r,n,h="Y"===(i=i.toUpperCase()),a=2===t.scrollMode,o=t.childrenMap.child,l=`slider${i}`;if(r=a||s.hasOwnProperty(l)?Cv(s,l,void 0):Cv(s,"slider",void 0)){var d,c,u;!0===r&&(r={}),r.orientation=h?1:0,n=function(t,e){void 0===e&&(e={});var i=ft(e);(e={slider:i}).orientation=i.orientation,delete i.orientation,e.background=i.background,delete i.background,e.buttons=i.buttons,delete i.buttons,e.value=null;var s=new lv(t,e);t.add.existing(s);var r=s.childrenMap.slider;return s.addChildrenMap("track",r.childrenMap.track),s.addChildrenMap("indicator",r.childrenMap.indicator),s.addChildrenMap("thumb",r.childrenMap.thumb),s}(t.scene,r);var p=Cv(r,"position",0);"string"==typeof p&&(p=Pv[p]);var v,g,f=Cv(s,`space.slider${i}`,void 0);void 0===f&&void 0===(f=Cv(s,"space.slider",void 0))&&(a?f=0:v=Cv(s,"space.child",0)),g=void 0===v?"number"==typeof f:"number"==typeof v,h?0===p?(d=2,c=1,u=void 0===v?g?{left:f}:f:{left:Cv(v,"right",v)}):(d=0,c=1,u=void 0===v?g?{right:f}:f:{right:Cv(v,"left",v)}):0===p?(d=1,c=2,u=void 0===v?g?{top:f}:f:{top:Cv(v,"bottom",v)}):(d=1,c=0,u=void 0===v?g?{bottom:f}:f:{bottom:Cv(v,"top",v)}),e.add(n,{column:d,row:c,align:"center",padding:u,expand:!0}),t[`hideUnscrollableSlider${i}`]=Cv(r,"hideUnscrollableSlider",!1),t[`adaptThumb${i}SizeMode`]=Cv(r,"adaptThumbSize",!1),t[`minThumb${i}Size`]=Cv(r,"minThumbSize",void 0)}else t[`hideUnscrollableSlider${i}`]=!1,t[`adaptThumb${i}SizeMode`]=!1,t[`minThumb${i}Size`]=void 0;var m,y,b=Cv(s,"scrollDetectionMode");"string"==typeof b&&(b=Tv[b]);var x=`scroller${i}`;(m=a||s.hasOwnProperty(x)?Cv(s,x,!0):Cv(s,"scroller",!0))&&o&&(!0===m&&(m={}),m.orientation=h?0:1,void 0!==b&&(m.rectBoundsInteractive=1===b),y=new bv(o,m),o.isRexContainerLite&&o.sendChildToBack(o));var w,S,C,O,P,T=Cv(s,a?`mouseWheelScroller${i}`:"mouseWheelScroller",!1);T&&o&&(void 0!==b&&(T.focus=1===b?2:0),w=new Sv(o,T)),t.addChildrenMap(`slider${i}`,n),t.addChildrenMap(`scroller${i}`,y),t.addChildrenMap(`mouseWheelScroller${i}`,w),a&&!h||(t.hideUnscrollableSlider=t[`hideUnscrollableSlider${i}`],t.adaptThumbSizeMode=t[`adaptThumb${i}SizeMode`],t.minThumbSize=t[`minThumb${i}Size`],t.addChildrenMap("slider",n),t.addChildrenMap("scroller",y),t.addChildrenMap("mouseWheelScroller",w)),n&&(a?(S=h?"t":"s",O=`scroll${i}`):(S="t",O="scroll"),n.on("valuechange",(function(e){t[S]=e,t.emit(O,t)}))),y&&(a?(C=`childO${i}`,O=`scroll${i}`):(C="childOY",O="scroll"),y.on("valuechange",(function(e){t[C]=e,t.emit(O,t)}))),w&&(P=a?`addChildO${i}`:"addChildOY",w.on("scroll",(function(e){t[P](-e,!0)})))};const Pv={right:0,left:1,bottom:0,top:1},Tv={gameObject:0,rectBounds:1},_v=Phaser.Utils.Objects.GetValue;var kv=function(t,e){var i=t.scene,s=[0,1,0],r=[0,1,0],n=_v(e,"width"),h=_v(e,"height");n||_v(e,"child.expandWidth",!0)||(s[1]=0),h||_v(e,"child.expandHeight",!0)||(r[1]=0);var a=new Dp(i,{column:3,row:3,columnProportions:s,rowProportions:r});switch(function(t,e,i){var s=Ap(i,"child"),r=Ap(s,"gameObject",void 0);if(r){var n=Ap(i,"space.child",0);t.childMargin={};var h=t.childMargin,a={};if("number"==typeof n)switch(t.scrollMode){case 0:case 1:h.top=0,h.bottom=0,h.left=0,h.right=0;break;default:h.top=n,h.bottom=n,h.left=n,h.right=n}else switch(t.scrollMode){case 0:h.top=Ap(n,"top",0),h.bottom=Ap(n,"bottom",0),a.left=Ap(n,"left",0),a.right=Ap(n,"right",0);break;case 1:h.top=Ap(n,"left",0),h.bottom=Ap(n,"right",0),a.top=Ap(n,"top",0),a.bottom=Ap(n,"bottom",0);break;default:h.top=Ap(n,"top",0),h.bottom=Ap(n,"bottom",0),h.left=Ap(n,"left",0),h.right=Ap(n,"right",0)}e.add(r,{column:1,row:1,align:Ap(s,"align","center"),padding:a,expand:{width:Ap(s,"expandWidth",!0),height:Ap(s,"expandHeight",!0)}})}t.addChildrenMap("child",r)}(t,a,e),t.scrollMode){case 0:Ov(t,a,"y",e);break;case 1:Ov(t,a,"x",e);break;default:Ov(t,a,"y",e),Ov(t,a,"x",e)}return a},Ev=function(t){var e,i,s,r;switch(this.scrollMode){case 0:case 1:e=this.topChildOY,i=this.bottomChildOY,s=this.childrenMap.scroller,r=this.childrenMap.slider,t=0===this.scrollMode?"Y":"X";break;default:"Y"===(t=t.toUpperCase())?(e=this.topChildOY,i=this.bottomChildOY):(e=this.leftChildOX,i=this.rightChildOX),s=this.childrenMap[`scroller${t}`],r=this.childrenMap[`slider${t}`]}if(s){var n="Y"===t?this.scaleY:this.scaleX;s.setBounds(e,i*n)}r&&r.setEnable(e!==i)},Mv=function(t){switch(this.scrollMode){case 0:case 1:(e=this.childrenMap.slider)&&this.hideUnscrollableSlider&&this.setChildVisible(e,this.isOverflow);break;default:t=t.toUpperCase();var e=this.childrenMap[`slider${t}`],i=this[`hideUnscrollableSlider${t}`],s=this[`isOverflow${t}`];e&&i&&this.setChildVisible(e,s)}},Rv=function(t){switch(this.scrollMode){case 0:case 1:if(!this.adaptThumbSizeMode)return;if(!(a=this.childrenMap.slider))return;var e=Math.min(this.childVisibleHeight/this.childHeight,1),i=a.childrenMap.track,s=a.childrenMap.thumb,r=this.minThumbSize;if(0===this.scrollMode){var n=i.displayHeight*e;void 0!==r&&n0?t.setText(e).getTextBounds().wrappedText.split("\n"):e.split("\n")}return i}(this.textObject,this.text,this.lines),this.linesCount=this.lines.length,this._textHeight=void 0,this._textVisibleHeight=void 0,this.updateTextObject(),this},updateTextObject:function(){var t=Math.max(Math.floor(Xv.call(this,-this.textOY)),0),e=Wv.call(this,t)+this.textOY,i=jv.call(this,t);return function(t,e){switch(hl(t)){case 0:var i=(r=t.style).wordWrapWidth,s=r.wordWrapCallback;r.wordWrapWidth=0,r.wordWrapCallback=void 0,t.setText(e),r.wordWrapWidth=i,r.wordWrapCallback=s;break;case 1:var r,n=(r=t.style).wrapMode;r.wrapMode=0,t.setText(e),r.wrapMode=n;break;case 2:var h=t._maxWidth;t._maxWidth=0,t.setText(e),t._maxWidth=h}}(this.textObject,i),this.textObject.rexSizer.offsetY=e,Fv.call(this),this},preLayout:function(){return this._textLineHeight=void 0,this._textLineSpacing=void 0,this._visibleLinesCount=void 0,this._textHeight=void 0,this._textVisibleHeight=void 0,We.call(this),this},layoutChildren:function(){var t,e,i,s,r,n,h,a=this.left,o=this.top;(t=this.textObject).rexSizer.hidden||(s=a+(i=(e=t.rexSizer).padding).left*this.scaleX,r=o+i.top*this.scaleY,n=this.width*this.scaleX-(i.left+i.right)*this.scaleX,h=this.height*this.scaleY-(i.top+i.bottom)*this.scaleY,Bv.call(this,t,n,h),he(t,s,r,n,h,e.align),e.preOffsetY=0,Fv.call(this),this.textMask&&(this.textMask.setPosition().resize(),this.resetChildPositionState(this.textMask)))}};const Nv=Phaser.Utils.Objects.IsPlainObject,Gv=Phaser.Utils.Objects.GetValue,Vv=Phaser.Display.Align.TOP_LEFT;class Uv extends qn{constructor(t,e,i,s,r,n){Nv(e)?(e=Gv(n=e,"x",0),i=Gv(n,"y",0),s=Gv(n,"width",void 0),r=Gv(n,"height",void 0)):Nv(s)&&(s=Gv(n=s,"width",void 0),r=Gv(n,"height",void 0)),super(t,e,i,s,r,n),this.type="rexTextBlock",this.textObject=void 0,this.linesCount=0,this.textMask=void 0,this.textObjectType=void 0,this._textLineHeight=void 0,this._textLineSpacing=void 0,this._visibleLinesCount=void 0,this._textHeight=void 0,this._textVisibleHeight=void 0,this._textObjectRealHeight=0,this.lines=void 0,this.text=Gv(n,"content",""),this._textOY=0,this.execeedTopState=!1,this.execeedBottomState=!1,this.setClampMode(Gv(n,"clampTextOY",!0)),this.alwaysScrollable=Gv(n,"alwaysScrollable",!1);var h=Gv(n,"background",void 0),a=Gv(n,"text",void 0);void 0===a&&(a=$v(t)),this.textCropEnable=Gv(n,"textCrop",!!a.setCrop);var o=Gv(n,"textMask",!this.textCropEnable);h&&this.addBackground(h),this.add(a),this.sizerChildren=[a];var l=this.getSizerConfig(a);l.align=Vv,l.padding=ue(0),l.expand=!0,this.textObject=a,this.textObjectType=hl(a),l.preOffsetY=0,l.offsetY=0,o&&(this.textMask=el.call(this,this.textObject,this)),this.addChildrenMap("background",h),this.addChildrenMap("text",a)}destroy(t){if(this.scene&&!this.ignoreDestroy){if(this.textObject=void 0,this.textMask=void 0,this.lines){switch(this.textObjectType){case 0:case 2:this.lines.length=0;break;case 1:this.lines.destroy()}this.lines=void 0}super.destroy(t)}}setClampMode(t){return void 0===t&&(t=!0),this.clampTextOY=t,this}get textLineHeight(){if(void 0===this._textLineHeight){var t;switch(this.textObjectType){case 0:case 1:var e=this.textObject.style;t=e.metrics.fontSize+e.strokeThickness;break;case 2:var i=this.textObject.fontSize/this.textObject.fontData.size;t=this.textObject.fontData.lineHeight*i}this._textLineHeight=t}return this._textLineHeight}get textLineSpacing(){if(void 0===this._textLineSpacing){var t;switch(this.textObjectType){case 0:case 1:t=this.textObject.lineSpacing;break;case 2:t=0}this._textLineSpacing=t}return this._textLineSpacing}get visibleLinesCount(){return void 0===this._visibleLinesCount&&(this._visibleLinesCount=Math.floor(Xv.call(this,this._textObjectRealHeight))),this._visibleLinesCount}get topTextOY(){return 0}get bottomTextOY(){return-this.textVisibleHeight}get textHeight(){return void 0===this._textHeight&&(this._textHeight=Wv.call(this,this.linesCount)),this._textHeight}get textObjectHeight(){return this._textObjectRealHeight-(this.textLineHeight+this.textLineSpacing)}get textVisibleHeight(){if(void 0===this._textVisibleHeight){var t=this.textHeight-this.textObjectHeight;!this.alwaysScrollable&&t<0&&(t=0),this._textVisibleHeight=t}return this._textVisibleHeight}textOYExceedTop(t){return void 0===t&&(t=this.textOY),t>this.topTextOY}textOYExeceedBottom(t){return void 0===t&&(t=this.textOY),tthis.linesCount?t=0:s?t=e:r&&(t=i)),this._textOY!==t&&(this._textOY=t,this.updateTextObject()),s&&(this.execeedTopState||this.emit("execeedtop",this,t,e)),this.execeedTopState=s,r&&(this.execeedBottomState||this.emit("execeedbottom",this,t,i)),this.execeedBottomState=r}setTextOY(t){return this.textOY=t,this}set t(t){this.textOY=-this.textVisibleHeight*t}get t(){var t=this.textVisibleHeight;return 0===t?0:this.textOY/-t}setTextOYByPercentage(t){return this.t=t,this}}var $v=function(t){return t.add.text(0,0,"")};Object.assign(Uv.prototype,Hv);var Jv={setText(t){return this.childrenMap.child.setText(t),this.resizeController(),this},appendText(t){return this.setText(this.text+t),this}},Kv={scrollToLine(t){return this.setChildOY(-this.lineHeight*t),this},scrollToNextLine(t){void 0===t&&(t=1);var e=this.lineIndex+t;return this.scrollToLine(e),this}};const qv=Phaser.Utils.Objects.GetValue;class Zv extends Yv{constructor(t,e){void 0===e&&(e={});var i=qv(e,"text",void 0),s=qv(e,"textWidth",void 0),r=qv(e,"textHeight",void 0),n=qv(e,"textCrop",!!i.setCrop),h=qv(e,"textMask",!n),a=qv(e,"content",""),o=new Uv(t,{width:s,height:r,text:i,textMask:h,textCrop:n&&!h,content:a,clampTextOY:qv(e,"clampChildOY",!1),alwaysScrollable:qv(e,"alwaysScrollable",!1)});t.add.existing(o),function(t){Object.defineProperty(t,"childOY",{configurable:!0,get:function(){return t.textOY},set:function(e){t.textOY=e}}),Object.defineProperty(t,"topChildOY",{get:function(){return t.topTextOY}}),Object.defineProperty(t,"bottomChildOY",{get:function(){return t.bottomTextOY}}),Object.defineProperty(t,"childVisibleHeight",{get:function(){return t.textObjectHeight}}),Object.defineProperty(t,"childHeight",{get:function(){return t.textHeight}})}(o),e.scrollMode=0,e.type="rexTextArea",e.child={gameObject:o,expandWidth:void 0===s,expandHeight:void 0===r};var l=qv(e,"space",void 0);l&&(l.child=qv(l,"text",0)),super(t,e),this.addChildrenMap("text",i)}get text(){return this.childrenMap.child.text}get lineHeight(){var t=this.childrenMap.child;return t.textLineHeight+t.textLineSpacing}get lineIndex(){return Math.floor(-this.childOY/this.lineHeight)}get linesCount(){return this.childrenMap.child.linesCount}get contentHeight(){return this.childrenMap.child.textHeight}}Object.assign(Zv.prototype,Jv,Kv);const Qv=Phaser.Utils.Objects.GetValue;var tg=function(t,e){var i,s;switch(e&&(e.hasOwnProperty("$type")?i=e.$type:e.hasOwnProperty("key")&&(i="bitmaptext",e.font=e.key)),i){case"bitmaptext":case"bitmap":s=new up(t,e);break;case"bbcodetext":case"bbcode":s=new op(t,0,0,"",e);break;case"label":s=new sg(t,e);break;case"textarea":s=function(t,e,i){e=e?Po(e):{};var s=Qv(i,"background",Go),r=Qv(i,"text",tg),n=Qv(i,"track",Go),h=Qv(i,"thumb",Go);s?e.background=s(t,e.background):delete e.background,r?e.text=r(t,e.text):delete e.text;var a=e.slider;!1!==a&&null!==a&&(void 0===a&&(a={}),n?a.track=n(t,a.track):delete a.track,h?a.thumb=h(t,a.thumb):delete a.thumb,e.slider=a);var o=new Zv(t,e);return t.add.existing(o),o}(t,e);break;default:s=new Ec(t,e)}return No(s,e),t.add.existing(s),s},eg=function(t,e){var i,s;switch(e&&(e.hasOwnProperty("$type")?i=e.$type:e.hasOwnProperty("leftWidth")?i="nineSlice":(e.hasOwnProperty("color")||e.hasOwnProperty("strokeColor"))&&(i="roundRectangle")),i){case"nineSlice":s=e.hasOwnProperty("stretchMode")?new Bo(t,e):new bo(t,e);break;case"roundRectangle":s=new ua(t,e);break;default:s=new Co(t,e)}return No(s,e),t.add.existing(s),s};const ig=Phaser.Utils.Objects.GetValue;class sg extends Tc{constructor(t,e,i){e=function(t,e,i){e=e?Po(e):{};var s=ig(i,"background",Go),r=ig(i,"text",tg),n=ig(i,"icon",eg),h=ig(i,"action",eg);return null!==e.background&&s?e.background=s(t,e.background):delete e.background,null!==e.text&&r?e.text=r(t,e.text):delete e.text,null!==e.icon&&n?e.icon=n(t,e.icon):delete e.icon,null!==e.action&&h?e.action=h(t,e.action):delete e.action,e}(t,e,i),super(t,e),this.type="rexSimpleLabel"}setActiveState(t){return rg(this.getChildren(),"setActiveState",t),this}setHoverState(t){return rg(this.getChildren(),"setHoverState",t),this}setDisableState(t){return rg(this.getChildren(),"setDisableState",t),this}}var rg=function(t,e,i){for(var s=0,r=t.length;s0&&void 0!==this._direction?this.previousDirection=this._direction:this.previousDirection=void 0,this._direction=t,this.verticeAngle=90*t,this.dirty=!0,void 0!==this.previousDirection?this.playEaseDirectionation():this.stopEaseDirection())}setDirection(t,e){return void 0!==e&&this.setEaseDuration(e),this.direction=t,this}toggleDirection(t){return this.setDirection(this.direction+2,t),this}get easeDirectionProgress(){return this._easeDirectionProgress}set easeDirectionProgress(t){this._easeDirectionProgress!==t&&(this._easeDirectionProgress=t,this.dirty=!0)}setPadding(t,e,i,s){if("object"==typeof t){var r=t,n=xg(r,"x",null);null!==n?(t=n,i=n):(t=xg(r,"left",0),i=xg(r,"right",t));var h=xg(r,"y",null);null!==h?(e=h,s=h):(e=xg(r,"top",0),s=xg(r,"bottom",e))}else void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=t),void 0===s&&(s=e);return void 0===this.padding&&(this.padding={}),this.dirty=this.dirty||this.padding.left!=t||this.padding.top!=e||this.padding.right!=i||this.padding.bottom!=s,this.padding.left=t,this.padding.top=e,this.padding.right=i,this.padding.bottom=s,this.setRadius(),this}get radius(){return this._radius}set radius(t){this.dirty=this.dirty||this._radius!=t,this._radius=t}setRadius(t){return this.radius=t,this.shapeMode=null==t?0:1,this}get verticeRotation(){return this._verticeRotation}set verticeRotation(t){this.dirty=this.dirty||this._verticeRotation!=t,this._verticeRotation=t}setVerticeRotation(t){return this.verticeRotation=t,this}get verticeAngle(){return Cg(this.verticeRotation)}set verticeAngle(t){this.verticeRotation=Sg(t)}setVerticeAngle(t){return this.verticeAngle=t,this}}const Pg={right:0,down:1,left:2,up:3};var Tg=function(t){return"string"==typeof t&&(t=Pg[t]),t%=4};Object.assign(Og.prototype,yg,bg);var _g=function(t,e,i){var s=new Og(t,e);return t.add.existing(s),s.on("expand.start",(function(t){t.setDirection("down")})).on("collapse.complete",(function(t){t.setDirection("right")})),s};const kg=Phaser.Utils.Objects.GetValue,Eg=Phaser.Utils.Objects.GetValue,Mg=Phaser.Utils.Objects.Clone,Rg=Phaser.Utils.Objects.GetValue;class Lg extends(Ph(Lh)){constructor(t,e){void 0===e&&(e={});var i=Ah(t,Rg(e,"background"),{isLeaf:!1},Vo,!1),s=function(t,e){var i=new Oh(t,{orientation:Eg(e,"childrenOrientation","y")});t.add.existing(i);var s=Ah(t,Eg(e,"childrenBackground"),{isLeaf:!1},Vo,!1);return s&&i.addBackground(s),i}(t,e),r=s.childrenMap.items,n=function(t,e){var i=new ag(t,e,{isLeaf:!1});t.add.existing(i);var s=Ah(t,kg(e,"toggleButton"),{isLeaf:!1},_g,!0);return i.insert(0,s,{padding:{right:kg(e,"space.toggleButton",0)},fitRatio:1}),i.addChildrenMap("toggleButton",s),i}(t,e),h=n.childrenMap.toggleButton,a=n.childrenMap.nodeBody,o=wh(Rg(e,"orientation","y")),l=e.space;if(l){var d=Rg(l,"indent",0);l.childLeft=Rg(l,"indentLeft",1===o?d:0),l.childRight=Rg(l,"indentRight",0),l.childTop=Rg(l,"indentTop",0===o?d:0),l.childBottom=Rg(l,"indentBottom",0)}super(t,{background:i,title:n,child:s,toggleByTarget:h,transition:e.transition,orientation:o,space:l,align:e.align,expand:e.expand}),this.type="rexTree",this.rexSizer.treeParent=null,this.nodesMap={},this.configSave=e,this.nodeBody=a,this.addChildrenMap("toggleButton",h),this.addChildrenMap("nodeBody",a),this.addChildrenMap("childrenNodes",r),this.on("expand.start",(function(){h.emit("expand.start",h),Dg(this,"expand.start")}),this).on("expand.complete",(function(){h.emit("expand.complete",h),Dg(this,"expand.complete")})).on("collapse.start",(function(){h.emit("collapse.start",h),Dg(this,"collapse.start")})).on("collapse.complete",(function(){h.emit("collapse.complete",h),Dg(this,"collapse.complete")}));var c=this;c._postAddCallback=function(){var t=Rg(e,"expanded",!0);void 0!==t&&c.setExpandedState(t),delete c._postAddCallback}}destroy(t){this.scene&&!this.ignoreDestroy&&(this.configSave=void 0,Clear(this.nodesMap),this.nodesMap=void 0,super.destroy(t))}get isTree(){return!0}createTree(t){return Lg.CreateTree(this.scene,this.configSave,t)}isTreeObject(t){return t&&t instanceof Lg}}Lg.CreateTree=function(t,e,i){return new Lg(t,function(t,e){var i=t?Mg(t):{};if(!e)return i;for(var s in e)i[s]=e[s];return i}(e,i))};var Dg=function(t,e){var i=t.getTreesSizer();i&&i.emit(e,t)};Object.assign(Lg.prototype,pg);const Ag=Phaser.Utils.String.UUID;var Yg={addTree(t){return yt(t)&&(t={nodeBody:t,nodeKey:nodeKey}),this.insertTree(void 0,t)},insertTree(t,e){var i;"string"==typeof e?(i=e,e=void 0):e&&(i=e.nodeKey,delete e.nodeKey),void 0===i&&(i=Ag());var s=Lg.CreateTree(this.scene,this.treeConfig,e);return og(this,s),s.nodeKey=i,this.treesMap[i]=s,this.insert(t,s,{expand:!0}),s._postAddCallback(),s}},zg={removeTree(t,e){return"string"==typeof t&&(t=this.getTree(t)),t?(delete this.treesMap[t.nodeKey],t.nodeKey=null,this.remove(t,e),this):this},removeAllNodes(t){var e=this.treesMap;for(var i in e)this.removeTree(e[i],t);return this}},Xg={getTree(t){return this.treesMap[t]},getTrees(t){for(var e in void 0===t&&(t=[]),this.treesMap)t.push(this.treesMap[e]);return t},getNode(t){var e=t.indexOf(".");if(-1===e)return this.getTree(t);var i=this.getTree(t.substring(0,e));return i?i.getNode(t.substring(e+1)):void 0}},Wg={pointToChild:function(t,e,i,s){for(var r in this.treesMap){var n=this.treesMap[r];if(hr(n.nodeBody,t,e,i,s))return n;var h=n.pointToChild(t,e,i,s);if(h)return h}return null},setChildrenInteractive:function(t){return void 0===t&&(t={}),t.targetMode="parent",t.targetSizers=[this],$n(this,t),this}};Object.assign(Wg,Yg,zg,Xg);const jg=Phaser.Utils.Objects.GetValue;class Fg extends Oh{constructor(t,e){void 0===e&&(e={}),e.hasOwnProperty("orientation")||(e.orientation="y"),super(t,e),this.type="rexTrees",this.treesMap={},this.treeConfig=jg(e,"tree")}destroy(t){this.scene&&!this.ignoreDestroy&&(this.treeConfig=void 0,Clear(this.treesMap),this.treesMap=void 0,super.destroy(t))}}return Object.assign(Fg.prototype,Wg),Fg},"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).rextrees=e(); diff --git a/dist/rexuiplugin.js b/dist/rexuiplugin.js index 06cb713a96..74dc0cce7d 100644 --- a/dist/rexuiplugin.js +++ b/dist/rexuiplugin.js @@ -68910,19 +68910,19 @@ scene.load.script('chartjs', 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3. this .on('expand.start', function () { toggleButton.emit('expand.start', toggleButton); - FireTreesSizerEvent(this, 'tree.expand.start'); + FireTreesSizerEvent(this, 'expand.start'); }, this) .on('expand.complete', function () { toggleButton.emit('expand.complete', toggleButton); - FireTreesSizerEvent(this, 'tree.expand.complete'); + FireTreesSizerEvent(this, 'expand.complete'); }) .on('collapse.start', function () { toggleButton.emit('collapse.start', toggleButton); - FireTreesSizerEvent(this, 'tree.collapse.start'); + FireTreesSizerEvent(this, 'collapse.start'); }) .on('collapse.complete', function () { toggleButton.emit('collapse.complete', toggleButton); - FireTreesSizerEvent(this, 'tree.collapse.complete'); + FireTreesSizerEvent(this, 'collapse.complete'); }); // Run this callback after adding to parent tree diff --git a/dist/rexuiplugin.min.js b/dist/rexuiplugin.min.js index 34c71693fb..7e70a41b9c 100644 --- a/dist/rexuiplugin.min.js +++ b/dist/rexuiplugin.min.js @@ -3,7 +3,7 @@ var t,e;t=void 0,e=function(){class t{constructor(t){this.scene=t,this.displayLi * @author Richard Davey * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} - */const Se=Phaser.Display.Canvas.CanvasPool;var Pe=function(t){var e=Se.create(this),i=e.getContext("2d",{willReadFrequently:!0});t.syncFont(e,i);var s=i.measureText(t.testString);if("actualBoundingBoxAscent"in s){var r=s.actualBoundingBoxAscent,n=s.actualBoundingBoxDescent,a={ascent:r,descent:n,fontSize:r+n};return Se.remove(e),a}var o=Math.ceil(s.width*t.baselineX),h=o,l=2*h;if(h=h*t.baselineY|0,e.width=o,e.height=l,i.fillStyle="#f00",i.fillRect(0,0,o,l),i.font=t._font,i.textBaseline="alphabetic",i.fillStyle="#000",i.fillText(t.testString,0,h),a={ascent:0,descent:0,fontSize:0},!i.getImageData(0,0,o,l))return a.ascent=h,a.descent=h+6,a.fontSize=a.ascent+a.descent,Se.remove(e),a;var d,c,u=i.getImageData(0,0,o,l).data,p=u.length,g=4*o,v=0,f=!1;for(d=0;dh;d--){for(c=0;c0&&this.wrapMode!==Ee&&0===this.wrapWidth}setStyle(t,e,i){if(void 0===e&&(e=!0),void 0===i&&(i=!1),t&&t.hasOwnProperty("wordWrap")){var s=t.wordWrap;s.hasOwnProperty("width")&&(t.wrap={mode:"word",width:s.width})}if(t&&t.hasOwnProperty("wrap")){var r=t.wrap;if(r.hasOwnProperty("mode")){var n=r.mode;"string"==typeof n&&(r.mode=Be[n])}else r.hasOwnProperty("width")&&(r.mode=1)}t&&t.rtl&&i&&!t.hasOwnProperty("halign")&&(t.halign="right"),t&&t.hasOwnProperty("fontSize")&&"number"==typeof t.fontSize&&(t.fontSize=t.fontSize.toString()+"px");var a=this.propertyMap;for(var o in a){var h=a[o],l=h[0],d=i?h[1]:this[o],c=h[2];if("wrapCallback"===o||"wrapCallbackScope"===o)this[o]=De(t,l,d);else{var u=Ie(t,l,d);c&&(u=c(u)),this[o]=u}}var p=De(t,"font",null);this._font=null===p?this.fontStyle+" "+this.fontSize+" "+this.fontFamily:p;var g=De(t,"fill",null);null!==g&&(this.color=Jt(g));var v=De(t,"metrics",!1);return v?this.metrics={ascent:De(v,"ascent",0),descent:De(v,"descent",0),fontSize:De(v,"fontSize",0)}:!e&&this.metrics||(this.metrics=Pe(this)),e?this.parent.updateText():this.parent}syncFont(t,e){e.font=this._font}syncStyle(t,e){e.textBaseline="alphabetic",e.fillStyle=this.color,e.strokeStyle=this.stroke,e.lineWidth=this.strokeThickness,e.lineCap="round",e.lineJoin="round"}syncShadow(t,e){e?(t.shadowOffsetX=this.shadowOffsetX,t.shadowOffsetY=this.shadowOffsetY,t.shadowColor=this.shadowColor,t.shadowBlur=this.shadowBlur):(t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowColor=0,t.shadowBlur=0)}update(t){return t&&(this._font=`${this.fontStyle} ${this.fontSize} ${this.fontFamily}`.trim(),this.metrics=Pe(this)),this.parent.updateText(t)}buildFont(){var t=`${this.fontStyle} ${this.fontSize} ${this.fontFamily}`.trim();return t!==this._font&&(this._font=t),this}setFont(t){return"string"==typeof t?(this.fontFamily=t,this.fontSize="",this.fontStyle=""):(this.fontFamily=De(t,"fontFamily","Courier"),this.fontSize=De(t,"fontSize","16px"),this.fontStyle=De(t,"fontStyle","")),this.update(!0)}setFontFamily(t){return this.fontFamily=t,this.update(!0)}setFontStyle(t){return this.fontStyle=t,this.update(!0)}setFontSize(t){return"number"==typeof t&&(t=t.toString()+"px"),this.fontSize=t,this.update(!0)}setTestString(t){return this.testString=t,this.update(!0)}setFixedSize(t,e){return this.fixedWidth=t,this.fixedHeight=e,t&&(this.parent.width=t),e&&(this.parent.height=e),this.update(this.isWrapFitMode)}setResolution(t){return this.resolution=t,this.update(!1)}setXOffset(t){return this.xOffset=t,this.update(!1)}setBackgroundColor(t,e,i){return void 0===i&&(i=!0),this.backgroundColor=Jt(t,this.parent.canvas,this.parent.context),this.backgroundColor2=Jt(e,this.parent.canvas,this.parent.context),this.backgroundHorizontalGradient=i,this.update(!1)}setBackgroundStrokeColor(t,e){return this.backgroundStrokeColor=Jt(t,this.parent.canvas,this.parent.context),this.backgroundStrokeLineWidth=e,this.update(!1)}setBackgroundCornerRadius(t,e){return this.backgroundCornerRadius=t,this.backgroundCornerIteration=e,this.update(!1)}setFill(t){return this.color=Jt(t,this.parent.canvas,this.parent.context),this.update(!1)}setColor(t){return this.color=Jt(t,this.parent.canvas,this.parent.context),this.update(!1)}setStroke(t,e){return void 0===t?this.strokeThickness=0:(void 0===e&&(e=this.strokeThickness),this.stroke=Jt(t,this.parent.canvas,this.parent.context),this.strokeThickness=e),this.update(!0)}setShadow(t,e,i,s,r,n){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i="#000"),void 0===s&&(s=0),void 0===r&&(r=!1),void 0===n&&(n=!0),this.shadowOffsetX=t,this.shadowOffsetY=e,this.shadowColor=Jt(i,this.parent.canvas,this.parent.context),this.shadowBlur=s,this.shadowStroke=r,this.shadowFill=n,this.update(!1)}setShadowOffset(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.shadowOffsetX=t,this.shadowOffsetY=e,this.update(!1)}setShadowColor(t){return void 0===t&&(t="#000"),this.shadowColor=Jt(t,this.parent.canvas,this.parent.context),this.update(!1)}setShadowBlur(t){return void 0===t&&(t=0),this.shadowBlur=t,this.update(!1)}setShadowStroke(t){return this.shadowStroke=t,this.update(!1)}setShadowFill(t){return this.shadowFill=t,this.update(!1)}setUnderline(t,e,i){return void 0===t&&(t="#000"),void 0===e&&(e=0),void 0===i&&(i=0),this.underlineColor=Jt(t,this.parent.canvas,this.parent.context),this.underlineThickness=e,this.underlineOffset=i,this.update(!1)}setUnderlineColor(t){return void 0===t&&(t="#000"),this.underlineColor=Jt(t,this.parent.canvas,this.parent.context),this.update(!1)}setUnderlineThickness(t){return void 0===t&&(t=0),this.underlineThickness=t,this.update(!1)}setUnderlineOffset(t){return void 0===t&&(t=0),this.underlineOffset=t,this.update(!1)}setStrikethrough(t,e,i){return void 0===t&&(t="#000"),void 0===e&&(e=0),void 0===i&&(i=0),this.strikethroughColor=Jt(t,this.parent.canvas,this.parent.context),this.strikethroughThickness=e,this.strikethroughOffset=i,this.update(!1)}setStrikethroughColor(t){return void 0===t&&(t="#000"),this.strikethroughColor=Jt(t,this.parent.canvas,this.parent.context),this.update(!1)}setStrikethroughThickness(t){return void 0===t&&(t=0),this.strikethroughThickness=t,this.update(!1)}setStrikethroughOffset(t){return void 0===t&&(t=0),this.strikethroughOffset=t,this.update(!1)}setWrapMode(t){return"string"==typeof t&&(t=Be[t.toLowerCase()]||0),this.wrapMode=t,this.update(!0)}setWrapWidth(t){return this.wrapWidth=t,this.update(!1)}setAlign(t,e){return void 0===t&&(t="left"),void 0===e&&(e="top"),this.halign=t,this.valign=e,this.update(!1)}setHAlign(t){return void 0===t&&(t="left"),this.halign=t,this.update(!1)}setVAlign(t){return void 0===t&&(t="top"),this.valign=t,this.update(!1)}setMaxLines(t){return void 0===t&&(t=0),this.maxLines=t,this.update(!1)}getTextMetrics(){var t=this.metrics;return{ascent:t.ascent,descent:t.descent,fontSize:t.fontSize}}setTextMetrics(t,e){return this.metrics.ascent=t.ascent,this.metrics.descent=t.descent,this.metrics.fontSize=t.fontSize,e&&("string"==typeof e?(this.fontFamily=e,this.fontSize="",this.fontStyle=""):(this.fontFamily=De(e,"fontFamily",this.fontFamily),this.fontSize=De(e,"fontSize",this.fontSize),this.fontStyle=De(e,"fontStyle",this.fontStyle))),this.parent.updateText(!0)}get lineHeight(){return this.metrics.fontSize+this.parent.lineSpacing}toJSON(){var t={},e=this.propertyMap;for(var i in e)t[i]=this[i];return t.metrics=this.getTextMetrics(),t}destroy(){this.parent=void 0}};var Ae=function(t){return null==t?t="":Array.isArray(t)?t=t.join("\n"):"number"==typeof t&&(t=t.toString()),t},ze={draw(t,e,i,s){var r=this.penManager;this.hitAreaManager.clear();var n=this.context;n.save();var a=this.defaultStyle;this.clear(),ie(this,a.backgroundColor,a.backgroundStrokeColor,a.backgroundStrokeLineWidth,a.backgroundCornerRadius,a.backgroundColor2,a.backgroundHorizontalGradient,a.backgroundCornerIteration),t+=this.startXOffset,e+=this.startYOffset;var o,h,l,d,c,u,p=a.halign,g=a.valign,v=a.lineHeight,f=r.lines,m=f.length,y=a.maxLines;y>0&&m>y?(h=y,l="center"===g?Math.floor((m-h)/2):"bottom"===g?m-h:0):(h=m,l=0),d=l+h;var b=this.rtl,x=b?this.parent.width:void 0;u="center"===g?Math.max((s-h*v)/2,0):"bottom"===g?Math.max(s-h*v-2,0):0,u+=e;for(var C=l;C0){var o=this.defaultStyle.metrics,h=i-o.ascent,l=o.fontSize;this.drawRectangle(e,h,t.width,l,a.bgcolor,a)}if(a.underlineThickness>0&&t.width>0){var d=i+a.underlineOffset-a.underlineThickness/2;this.drawLine(e,d,t.width,a.underlineThickness,a.underlineColor,a)}if(t.isTextPen&&(a.buildFont(),a.syncFont(r,n),a.syncStyle(r,n),this.drawText(e,i,t.text,a)),t.isImagePen&&this.drawImage(e,i,t.prop.img,t.prop.color,a),a.strikethroughThickness>0&&t.width>0&&(d=i+a.strikethroughOffset-a.strikethroughThickness/2,this.drawLine(e,d,t.width,a.strikethroughThickness,a.strikethroughColor,a)),n.restore(),t.hasAreaMarker&&t.width>0){var c,u=t.prop.area;if(u)c={key:u};else{var p=t.prop.url;c={key:`url:${p}`,url:p}}this.hitAreaManager.add(e,i-this.startYOffset,t.width,this.defaultStyle.lineHeight,c)}},clear(){var t=this.canvas;this.context.clearRect(0,0,t.width,t.height)},drawRectangle(t,e,i,s,r,n){this.autoRound&&(t=Math.round(t),e=Math.round(e));var a=this.context;a.fillStyle=r,a.fillRect(t,e,i,s)},drawLine(t,e,i,s,r,n){this.autoRound&&(t=Math.round(t),e=Math.round(e));var a=this.context;n.syncShadow(a,n.shadowStroke);var o=a.lineCap;a.lineCap="butt",a.strokeStyle=r,a.lineWidth=s,a.beginPath(),a.moveTo(t,e),a.lineTo(t+i,e),a.stroke(),a.lineCap=o},drawText(t,e,i,s){this.autoRound&&(t=Math.round(t),e=Math.round(e));var r=this.context;s.stroke&&"none"!==s.stroke&&s.strokeThickness>0&&(s.syncShadow(r,s.shadowStroke),r.strokeText(i,t,e)),s.color&&"none"!==s.color&&(s.syncShadow(r,s.shadowFill),r.fillText(i,t,e))},drawImage(t,e,i,s,r){e-=this.startYOffset,this.parent.imageManager.draw(i,this.context,t,e,s,this.autoRound)}};const Fe=Phaser.Utils.Objects.GetValue,Ye=Te,Xe=Oe;class We{constructor(t){this.prop={},this.resetFromJSON(t)}resetFromJSON(t){this.text=Fe(t,"text",""),this.x=Fe(t,"x",0),this.y=Fe(t,"y",0),this.width=Fe(t,"width",0);var e=Fe(t,"prop",null);null===e&&(e={}),this.prop=e,this.newLineMode=Fe(t,"newLineMode",0),this.startIndex=Fe(t,"startIndex",0)}get plainText(){var t=this.text;return this.newLineMode===Xe&&(t+="\n"),t}get wrapText(){var t=this.text;return this.newLineMode!==Ye&&(t+="\n"),t}get rawTextLength(){var t=this.text.length;return this.newLineMode===Xe&&(t+=1),t}get endIndex(){return this.startIndex+this.rawTextLength}get lastX(){return this.x+this.width}get isTextPen(){return""!==this.text}get isImagePen(){return!!this.prop.img}get hasAreaMarker(){return!!this.prop.area||!!this.prop.url}}var Ve=function(t,e){var i=Array.isArray(t);if(void 0===e?e=i?[]:{}:q(e),i){e.length=t.length;for(var s=0,r=t.length;s=this.lines.length)return this.getLineEndIndex(t);var e=this.lines[t];return e&&e[0]?e[0].startIndex:0}getLineEndIndex(t){t>=this.lines.length&&(t=this.lines.length-1);var e,i,s=!1;for(e=t;e>=0&&!(s=null!=(i=this.lines[e])&&i.length>0);e--);return s?i[i.length-1].endIndex:0}getLineWidth(t){var e=this.lines[t];if(!e)return 0;var i=e[e.length-1];return null==i?0:i.lastX}getMaxLineWidth(){if(void 0!==this.maxLinesWidth)return this.maxLinesWidth;for(var t,e=0,i=0,s=this.lines.length;ie&&(e=t);return this.maxLinesWidth=e,e}getLineWidths(){for(var t=[],e=0,i=this.lines.length;e=t&&h<=e||(a=a.substring(t-o,e-o)),this.tagToTextScope?c+=this.tagToText.call(this.tagToTextScope,a,l,d):c+=this.tagToText(a,l,d),d=l,!(h>=e)));u++);return c}get length(){return this.lines.length}set length(t){this.clear()}}var $e={};const Ke=Phaser.Geom.Rectangle;var Je=new I;class qe{constructor(){this.hitAreas=[]}destroy(){this.clear()}clear(){for(var t=0,e=this.hitAreas.length;ts&&pi(v)){""!==b?a.push(n.getLine(b,x,ai)):0===C&&r>0&&a.push(n.getLine("",0,ai)),a.push(...ci(v,e,li,s,0,n));var w=a.pop();b=w.text,x=w.width,n.freeLine(w)," "===b&&(b="",x=0)}else(m=x+f)>h?(a.push(n.getLine(b,x,ai)),b=v,x=f,h=s):(b+=v,x=m),C===k-1&&a.push(n.getLine(b,x,l))}return a},ui=function(t,e){var i;switch(e){case hi:i=[];for(var s=0,r=(t=t.split(" ")).length;s0&&e!==vi&&i0&&t>e&&(t=e),t}get linesWidth(){return Math.ceil(this.penManager.getMaxLineWidth())}get linesHeight(){var t=this.displayLinesCount,e=this.defaultStyle.lineHeight*t;return t>0&&(e-=this.defaultStyle.lineSpacing),e}get imageManager(){return this.parent.imageManager}get rtl(){return this.parent.style.rtl}newPenManager(){return new Ne({pensPool:this.pensPool,linesPool:this.linesPool,tagToText:this.parser.propToTagText,tagToTextScope:this.parser})}get tmpPenManager(){return null===this._tmpPenManager&&(this._tmpPenManager=this.newPenManager()),this._tmpPenManager}getPlainText(t,e,i){var s;if(null==t)s=this.penManager.plainText;else{var r=this.parser.splitText(t,1);s="";for(var n=0,a=r.length;n${t}`:e.hasOwnProperty("_style")?`${t}`:t}destroy(){this.tags=void 0}isTextTag(t){var e=this.tags[t];return!!e&&null==e.img}};var gs=function(t){for(var e,i,s,r={},n=0,a=(t=t.split(";")).length;n=1&&(s.color=o[0]),h>=2&&(s.thickness=parseInt(o[1].replace("px","")));break;case"shadow":o=s.split(" "),s={},(h=o.length)>=1&&(s.color=o[0]),h>=2&&(s.offsetX=parseInt(o[1].replace("px",""))),h>=3&&(s.offsetY=parseInt(o[2].replace("px",""))),h>=4&&(s.blur=parseInt(o[3].replace("px","")));break;case"u":case"underline":case"s":case"strikethrough":var h;o=s.split(" "),s={},(h=o.length)>=1&&(s.color=o[0]),h>=2&&(s.thickness=parseInt(o[1].replace("px",""))),h>=3&&(s.offset=parseInt(o[2].replace("px",""))),"underline"===i?i="u":"strikethrough"===i&&(i="s");break;case"y":s=parseFloat(s)}r[i]=s}return r},vs=function(t){return 0===(t=t.replace(Cs,"")).length},fs=/<\s*class=["|']([^"|']+)["|']\s*\>([\s\S]*?)<\s*\/class\s*\>|<\s*style=["|']([^"|']+)["|']\s*\>([\s\S]*?)<\s*\/style\s*\>/g,ms=/<\s*class=/i,ys=/<\s*class=["|']([^"|']+)["|']\s*\>([\s\S]*?)<\s*\/class\s*\>/,bs=/<\s*style=/i,xs=/<\s*style=["|']([^"|']+)["|']\s*\>([\s\S]*?)<\s*\/style\s*\>/,Cs=/^\s+|\s+$/;const ks=Phaser.Utils.Objects.GetValue;class ws extends Yi{constructor(t,e,i,s,r){var n=ks(r,"tags",void 0);super(t,e,i,s,r,"rexTagText",new ps(n))}addTag(t,e){return this.parser.addTag(t,e),this.updateText(!0)}addTags(t){for(var e in t)this.parser.addTag(e,t[e]);return this.updateText(!0)}getTag(t){return this.parser.getTag(t)}preDestroy(){super.preDestroy(),this.parser.destroy(),this.parser=void 0}}t.register("tagText",(function(t,e,i,s){var r=new ws(this.scene,t,e,i,s);return this.scene.add.existing(r),r})),P(window,"RexPlugins.UI.TagText",ws);const Ss=Phaser.Utils.Objects.GetValue;var Ps=function(t,e){return void 0===e?t:t[e]},Ts=function(t,e,i){void 0===t&&(t={}),void 0===e&&(e=0);var s=typeof e;return"string"===s?t[e]=i:"number"===s?(t.left=e,t.right=e,t.top=e,t.bottom=e):(t.left=Ss(e,"left",0),t.right=Ss(e,"right",0),t.top=Ss(e,"top",0),t.bottom=Ss(e,"bottom",0)),t};let Os=class{constructor(t,e){this.setParent(t),this.type=e,this.renderable=!1,this.reset().setActive()}destroy(){this.parent.removeChild(this)}setParent(t){return this.parent=t,this}get scene(){return this.parent.scene}get canvas(){return this.parent?this.parent.canvas:null}get context(){return this.parent?this.parent.context:null}setDirty(t){return t&&this.parent&&(this.parent.dirty=!0),this}get active(){return this._active}set active(t){this.setDirty(this._active!=t),this._active=t}setActive(t){return void 0===t&&(t=!0),this.active=t,this}modifyPorperties(t){return this}onFree(){this.reset().setParent()}reset(){return this}render(){}contains(t,e){return!1}};Object.assign(Os.prototype,Z);var Ms={renderContent(){},render(){if(!this.willRender)return this;var t=this.context;if(t.save(),t.globalAlpha=this.alpha,this.toLocalPosition){var e=this.drawX,i=this.drawY;this.autoRound&&(e=Math.round(e),i=Math.round(i)),t.translate(e,i),t.scale(this.scaleX,this.scaleY),t.rotate(this.rotation)}return this.drawBelowCallback&&this.drawBelowCallback(this),this.renderContent(),this.drawAboveCallback&&this.drawAboveCallback(this),t.restore(),this}};const Es=Phaser.Math.RotateAround;var _s;const Rs=Phaser.Geom.Rectangle;var Ls,Bs=function(t){void 0===Ls&&(Ls=new Rs);var e=t.drawTLX,i=t.drawTLY;return Ls.setTo(e,i,t.drawTRX-e,t.drawBLY-i),Ls};const Is=Phaser.Math.RotateAround;var Ds,js=function(t,e,i,s){return void 0===s?s={}:!0===s&&(void 0===Ds&&(Ds={}),s=Ds),s.x=e,s.y=i,0!==t.rotation&&Is(s,0,0,t.rotation),s.x=s.x*t.scaleX+t.drawX,s.y=s.y*t.scaleY+t.drawY,s};const As=Phaser.GameObjects.Components.TransformMatrix;var zs,Fs,Ys={},Xs=function(t,e,i,s,r){var n=js(e,i,s,!0),a=function(t,e,i,s){void 0===s?s={}:!0===s&&(s=Ys);var r=e-t.width*t.originX,n=i-t.height*t.originY;return void 0===zs&&(zs=new As,Fs=new As),t.parentContainer?t.getWorldTransformMatrix(zs,Fs):zs.applyITRS(t.x,t.y,t.rotation,t.scaleX,t.scaleY),zs.transformPoint(r,n,s),s}(t,n.x,n.y,r);return a},Ws=function(t,e,i,s,r){"number"!=typeof i&&(r=i,i=0,s=0);var n=e.drawCenterX+i,a=e.drawCenterY+s;return Xs(t,e,n,a,r)},Vs={contains:function(t,e){if(0===this.width||0===this.height)return!1;var i=function(t,e,i,s){return void 0===s?s={}:!0===s&&(void 0===_s&&(_s={}),s=_s),s.x=(t-i.drawX)/i.scaleX,s.y=(e-i.drawY)/i.scaleY,0!==i.rotation&&Es(s,0,0,-i.rotation),s}(t,e,this,!0);return Bs(this).contains(i.x,i.y)},getWorldPosition:function(t,e,i){return Ws(this.parent,this,t,e,i)}};Object.assign(Vs,Ms);const Gs=Phaser.Math.DegToRad,Hs=Phaser.Math.RadToDeg,Us=Phaser.Utils.Objects.GetValue;class Ns extends Os{constructor(t,e){super(t,e),this.renderable=!0,this.scrollFactorX=1,this.scrollFactorY=1,this.toLocalPosition=!0,this.originX=0,this.offsetX=0,this.offsetY=0}get visible(){return this._visible}set visible(t){this.setDirty(this._visible!=t),this._visible=t}setVisible(t){return void 0===t&&(t=!0),this.visible=t,this}get alpha(){return this._alpha}set alpha(t){this.setDirty(this._alpha!=t),this._alpha=t}setAlpha(t){return this.alpha=t,this}get x(){return this._x}set x(t){this.setDirty(this._x!=t),this._x=t}setX(t){return this.x=t,this}get y(){return this._y}set y(t){this.setDirty(this._y!=t),this._y=t}setY(t){return this.y=t,this}setPosition(t,e){return this.x=t,this.y=e,this}setInitialPosition(t,e){return this.x0=t,this.y0=e,this}setScrollFactorX(t){return this.scrollFactorX=t,this}setScrollFactorY(t){return this.scrollFactorY=t,this}setScrollFactor(t,e){return void 0===e&&(e=t),this.scrollFactorX=t,this.scrollFactorY=e,this}get rotation(){return this._rotation}set rotation(t){this.setDirty(this._rotation!=t),this._rotation=t}setRotation(t){return this.rotation=t,this}get angle(){return Hs(this._rotation)}set angle(t){this.rotation=Gs(t)}setAngle(t){return this.angle=t,this}get scaleX(){return this._scaleX}set scaleX(t){this.setDirty(this._scaleX!==t),this._scaleX=t}setScaleX(t){return this.scaleX=t,this}get width(){return 0}set width(t){}setWidth(t,e){return void 0===e&&(e=!1),this.width=t,e&&(this.scaleY=this.scaleX),this}get leftSpace(){return this._leftSpace}set leftSpace(t){this.setDirty(this._leftSpace!==t),this._leftSpace=t}setLeftSpace(t){return this.leftSpace=t,this}get rightSpace(){return this._rightSpace}set rightSpace(t){this.setDirty(this._rightSpace!==t),this._rightSpace=t}setRightSpace(t){return this.rightSpace=t,this}get outerWidth(){return this.width+this.leftSpace+this.rightSpace}get scaleY(){return this._scaleY}set scaleY(t){this.setDirty(this._scaleY!==t),this._scaleY=t}setScaleY(t){return this.scaleY=t,this}get height(){return 0}set height(t){}setHeight(t,e){return void 0===e&&(e=!1),this.height=t,e&&(this.scaleX=this.scaleY),this}setScale(t,e){return void 0===e&&(e=t),this.scaleX=t,this.scaleY=e,this}setOrigin(t){return this.originX=t,this}setAlign(t){return this.align=t,this}modifyPorperties(t){if(!t)return this;t.hasOwnProperty("x")&&this.setX(t.x),t.hasOwnProperty("y")&&this.setY(t.y),t.hasOwnProperty("rotation")?this.setRotation(t.rotation):t.hasOwnProperty("angle")&&this.setAngle(t.angle),t.hasOwnProperty("alpha")&&this.setAlpha(t.alpha);var e=Us(t,"width",void 0),i=Us(t,"height",void 0),s=Us(t,"scaleX",void 0),r=Us(t,"scaleY",void 0);return void 0!==e?void 0===i&&void 0===r?this.setWidth(e,!0):this.setWidth(e):void 0!==s&&this.setScaleX(s),void 0!==i?void 0===e&&void 0===s?this.setHeight(i,!0):this.setHeight(i):void 0!==r&&this.setScaleY(r),t.hasOwnProperty("leftSpace")&&this.setLeftSpace(t.leftSpace),t.hasOwnProperty("rightSpace")&&this.setRightSpace(t.rightSpace),t.hasOwnProperty("align")&&this.setAlign(t.align),this}setDrawBelowCallback(t){return this.drawBelowCallback=t,this}setDrawAboveCallback(t){return this.drawAboveCallback=t,this}reset(){return this.setVisible().setAlpha(1).setPosition(0,0).setRotation(0).setScale(1,1).setLeftSpace(0).setRightSpace(0).setOrigin(0).setAlign().setDrawBelowCallback().setDrawAboveCallback(),this}get willRender(){return this.visible&&this.alpha>0}get drawX(){var t=this.x+this.leftSpace+this.offsetX-this.originX*this.width;return this.parent._textOX*this.scrollFactorX+t}get drawY(){var t=this.y+this.offsetY;return this.parent._textOY*this.scrollFactorY+t}get drawTLX(){return 0}get drawTLY(){return 0}get drawBLX(){return 0}get drawBLY(){return 0}get drawTRX(){return 0}get drawTRY(){return 0}get drawBRX(){return 0}get drawBRY(){return 0}get drawCenterX(){return(this.drawTRX+this.drawTLX)/2}get drawCenterY(){return(this.drawBLY+this.drawTLY)/2}}Object.assign(Ns.prototype,Vs);var $s=function(t,e,i){return e.hasOwnProperty(t)?e[t]:i[t]};const Ks=Phaser.Utils.Objects.GetValue;class Js extends Ns{constructor(t,e){super(t,"background"),this.setScrollFactor(0),this.setColor(Ks(e,"color",null),Ks(e,"color2",null),Ks(e,"horizontalGradient",!0)),this.setStroke(Ks(e,"stroke",null),Ks(e,"strokeThickness",2)),this.setCornerRadius(Ks(e,"cornerRadius",0),Ks(e,"cornerIteration",null))}set color(t){t=Jt(t,this.canvas,this.context),this.setDirty(this._color!=t),this._color=t}get color(){return this._color}set color2(t){t=Jt(t,this.canvas,this.context),this.setDirty(this._color2!=t),this._color2=t}get color2(){return this._color2}set horizontalGradient(t){this.setDirty(this._horizontalGradient!=t),this._horizontalGradient=t}get horizontalGradient(){return this._horizontalGradient}setColor(t,e,i){return void 0===i&&(i=!0),this.color=t,this.color2=e,this.horizontalGradient=i,this}set stroke(t){t=Jt(t,this.canvas,this.context),this.setDirty(this._stroke!=t),this._stroke=t}get stroke(){return this._stroke}set strokeThickness(t){this.setDirty(this._strokeThickness!=t),this._strokeThickness=t}get strokeThickness(){return this._strokeThickness}setStroke(t,e){return null!=t&&void 0===e&&(e=2),this.stroke=t,this.strokeThickness=e,this}set cornerRadius(t){this.setDirty(this._cornerRadius!=t),this._cornerRadius=t}get cornerRadius(){return this._cornerRadius}set cornerIteration(t){this.setDirty(this._cornerIteration!=t),this._cornerIteration=t}get cornerIteration(){return this._cornerIteration}modifyStyle(t){return t.hasOwnProperty("color")&&this.setColor(t.color,$s("color2",t,this),$s("horizontalGradient",t,this)),t.hasOwnProperty("stroke")&&this.setStroke(t.stroke,$s("strokeThickness",t,this)),t.hasOwnProperty("cornerRadius")&&this.setCornerRadius(t.cornerRadius,$s("cornerIteration",t,this)),this}modifyPorperties(t){return super.modifyPorperties(t),this.modifyStyle(t),this}setCornerRadius(t,e){return this.cornerRadius=t,this.cornerIteration=e,this}renderContent(){ie(this.parent,this.color,this.stroke,this.strokeThickness,this.cornerRadius,this.color2,this.horizontalGradient,this.cornerIteration)}}const qs=Phaser.Utils.Objects.GetValue;class Zs extends Ns{constructor(t,e){super(t,"innerbounds"),this.setScrollFactor(0),this.setColor(qs(e,"color",null),qs(e,"color2",null),qs(e,"horizontalGradient",!0)),this.setStroke(qs(e,"stroke",null),qs(e,"strokeThickness",2))}set color(t){t=Jt(t,this.canvas,this.context),this.setDirty(this._color!=t),this._color=t}get color(){return this._color}set color2(t){t=Jt(t,this.canvas,this.context),this.setDirty(this._color2!=t),this._color2=t}get color2(){return this._color2}set horizontalGradient(t){this.setDirty(this._horizontalGradient!=t),this._horizontalGradient=t}get horizontalGradient(){return this._horizontalGradient}setColor(t,e,i){return void 0===i&&(i=!0),this.color=t,this.color2=e,this.horizontalGradient=i,this}set stroke(t){t=Jt(t,this.canvas,this.context),this.setDirty(this._stroke!=t),this._stroke=t}get stroke(){return this._stroke}set strokeThickness(t){this.setDirty(this._strokeThickness!=t),this._strokeThickness=t}get strokeThickness(){return this._strokeThickness}setStroke(t,e){return null!=t&&void 0===e&&(e=2),this.stroke=t,this.strokeThickness=e,this}modifyPorperties(t){super.modifyPorperties(t),t.hasOwnProperty("color")&&this.setColor(t.color,qs(t,"color2",null),qs(t,"horizontalGradient",!0)),t.hasOwnProperty("stroke")&&this.setStroke(t.stroke,qs(t,"strokeThickness",2))}renderContent(){var t,e,i=this.parent.padding,s=i.left,r=i.top,n=this.parent.width-i.left-i.right,a=this.parent.height-i.top-i.bottom,o=this.context;null!=this.color&&(null!=this.color2?((e=this.horizontalGradient?o.createLinearGradient(0,0,n,0):o.createLinearGradient(0,0,0,a)).addColorStop(0,this.color),e.addColorStop(1,this.color2),t=e):t=this.color,o.fillStyle=t,o.fillRect(s,r,n,a));null!=this.stroke&&this.strokeThickness>0&&(o.strokeStyle=this.stroke,o.lineWidth=this.strokeThickness,o.strokeRect(s,r,n,a))}}const Qs=Phaser.Utils.Objects.GetValue;class tr{constructor(t,e){this.parent=t,this.set(e)}toJSON(){return{bold:this.bold,italic:this.italic,fontSize:this.fontSize,fontFamily:this.fontFamily,color:this.color,stroke:this.stroke,strokeThickness:this.strokeThickness,shaodwColor:this.shadowColor,shadowBlur:this.shadowBlur,shadowOffsetX:this.shadowOffsetX,shadowOffsetY:this.shadowOffsetY,offsetX:this.offsetX,offsetY:this.offsetY,leftSpace:this.leftSpace,rightSpace:this.rightSpace,backgroundHeight:this.backgroundHeight,backgroundBottomY:this.backgroundBottomY,align:this.align}}set(t){return this.setBold(Qs(t,"bold",!1)),this.setItalic(Qs(t,"italic",!1)),this.setFontSize(Qs(t,"fontSize","16px")),this.setFontFamily(Qs(t,"fontFamily","Courier")),this.setColor(Qs(t,"color","#fff")),this.setStrokeStyle(Qs(t,"stroke",null),Qs(t,"strokeThickness",0)),this.setShadow(Qs(t,"shadowColor",null),Qs(t,"shadowOffsetX",0),Qs(t,"shadowOffsetY",0),Qs(t,"shadowBlur",0)),this.setOffset(Qs(t,"offsetX",0),Qs(t,"offsetY",0)),this.setSpace(Qs(t,"leftSpace",0),Qs(t,"rightSpace",0)),this.setAlign(Qs(t,"align",void 0)),this.setBackgroundColor(Qs(t,"backgroundColor",null)),this.setBackgroundHeight(Qs(t,"backgroundHeight",void 0)),this.setBackgroundBottomY(Qs(t,"backgroundBottomY",void 0)),this}modify(t){return t.hasOwnProperty("bold")&&this.setBold(t.bold),t.hasOwnProperty("italic")&&this.setItalic(t.italic),t.hasOwnProperty("fontSize")&&this.setFontSize(t.fontSize),t.hasOwnProperty("fontFamily")&&this.setFontFamily(t.fontFamily),t.hasOwnProperty("color")&&this.setColor(t.color),(t.hasOwnProperty("stroke")||t.hasOwnProperty("strokeThickness"))&&this.setStrokeStyle($s("stroke",t,this),$s("strokeThickness",t,this)),t.hasOwnProperty("shadowColor")&&this.setShadowColor(t.shadowColor),(t.hasOwnProperty("shadowOffsetX")||t.hasOwnProperty("shadowOffsetY"))&&this.setShadowOffset($s("shadowOffsetX",t,this),$s("shadowOffsetY",t,this)),t.hasOwnProperty("shadowBlur")&&this.setShadowBlur(t.shaodwBlur),t.hasOwnProperty("offsetX")&&this.setOffsetX(t.offsetX),t.hasOwnProperty("offsetY")&&this.setOffsetY(t.offsetY),t.hasOwnProperty("leftSpace")&&this.setLeftSpace(t.leftSpace),t.hasOwnProperty("rightSpace")&&this.setRightSpace(t.rightSpace),t.hasOwnProperty("align")&&this.setAlign(t.align),t.hasOwnProperty("backgroundColor")&&this.setBackgroundColor(t.backgroundColor),t.hasOwnProperty("backgroundHeight")&&this.setBackgroundHeight(t.backgroundHeight),t.hasOwnProperty("backgroundBottomY")&&this.setBackgroundBottomY(t.backgroundBottomY),this}setUpdateTextFlag(){return this.parent&&(this.parent.updateTextFlag=!0),this}clone(){return new tr(null,this.toJSON())}copyFrom(t){return this.set(t.toJSON()),this}copyTo(t){return t.set(this.toJSON()),this}setBold(t){return void 0===t&&(t=!0),this.bold=t,this.setUpdateTextFlag(),this}setItalic(t){return void 0===t&&(t=!0),this.italic=t,this.setUpdateTextFlag(),this}get fontStyle(){return this.bold&&this.italic?"bold italic":this.bold?"bold":this.italic?"italic":""}setFontSize(t){return"number"==typeof t&&(t=`${t}px`),this.fontSize=t,this.setUpdateTextFlag(),this}setFontFamily(t){return this.fontFamily=t,this.setUpdateTextFlag(),this}get font(){return`${this.fontStyle} ${this.fontSize} ${this.fontFamily}`}setColor(t){return this.color=Jt(t),this}get hasFill(){return null!=this.color}setStrokeStyle(t,e){return this.stroke=Jt(t),void 0!==e&&(this.strokeThickness=e),this}setStrokeThickness(t){return this.strokeThickness=t,this}get hasStroke(){return null!=this.stroke&&this.strokeThickness>0}setShadowColor(t){return this.shadowColor=Jt(t),this}setShadowOffset(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.shadowOffsetX=t,this.shadowOffsetY=e,this}setShadowBlur(t){return void 0===t&&(t=0),this.shaodwBlur=t,this}setShadow(t,e,i,s){return this.setShadowColor(t).setShadowOffset(e,i).setShadowBlur(s),this}setBackgroundColor(t){return this.backgroundColor=Jt(t),this}get hasBackgroundColor(){return null!=this.backgroundColor}setBackgroundHeight(t){return this.backgroundHeight=t,this}setBackgroundBottomY(t){return this.backgroundBottomY=t,this}setOffsetX(t){return void 0===t&&(t=0),this.offsetX=t,this}setOffsetY(t){return void 0===t&&(t=0),this.offsetY=t,this}setOffset(t,e){return this.setOffsetX(t).setOffsetY(e),this}setLeftSpace(t){return void 0===t&&(t=0),this.leftSpace=t,this}setRightSpace(t){return void 0===t&&(t=0),this.rightSpace=t,this}setSpace(t,e){return this.setLeftSpace(t).setRightSpace(e),this}setAlign(t){return this.align=t,this}syncFont(t){return t.font=this.font,this}syncStyle(t){t.textBaseline="alphabetic";var e=this.hasFill,i=this.hasStroke;return t.fillStyle=e?this.color:"#000",t.strokeStyle=i?this.stroke:"#000",t.lineWidth=i?this.strokeThickness:0,t.lineCap="round",t.lineJoin="round",this}syncShadow(t){null!=t.shadowColor?(t.shadowColor=this.shadowColor,t.shadowOffsetX=this.shadowOffsetX,t.shadowOffsetY=this.shadowOffsetY,t.shadowBlur=this.shadowBlur):(t.shadowColor=0,t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowBlur=0)}getTextMetrics(t,e){return this.syncFont(t).syncStyle(t),t.measureText(e)}}const er=Phaser.Utils.Array.Remove,ir=Phaser.Utils.Array.Remove,sr="text",rr="image",nr="drawer",ar="space",or="command";var hr=function(t){return t.type===sr&&"\n"===t.text},lr=function(t){return t.type===sr&&"\f"===t.text},dr=function(t){return t.type===sr},cr=function(t){return t.type===or};class ur extends Ns{constructor(t,e,i){super(t,sr),this.updateTextFlag=!1,this.style=new tr(this,i),this.setText(e)}get autoRound(){return this.parent.autoRound}get offsetX(){return this.style.offsetX}set offsetX(t){this.style&&(this.style.offsetX=t)}get offsetY(){return this.style.offsetY}set offsetY(t){this.style&&(this.style.offsetY=t)}get leftSpace(){return this.style.leftSpace*this.scaleX}set leftSpace(t){this.style&&(this.style.leftSpace=t),super.leftSpace=t}get rightSpace(){return this.style.rightSpace*this.scaleX}set rightSpace(t){this.style&&(this.style.rightSpace=t),super.rightSpace=t}get align(){return this.style.align}set align(t){this.style&&(this.style.align=t)}modifyStyle(t){return this.setDirty(!0),this.style.modify(t),this.updateTextFlag&&this.updateTextSize(),this}modifyPorperties(t){return t?(this.modifyStyle(t),super.modifyPorperties(t),this):this}setText(t){return this.setDirty(this.text!=t),this.text=t,this.updateTextSize(),this}updateTextSize(){var t=this.text;if("\n"===t||"\f"===t||""===t)this.clearTextSize();else{var e,i,s=this.style.getTextMetrics(this.context,this.text);this.textWidth=s.width,"actualBoundingBoxAscent"in s?(e=s.actualBoundingBoxAscent,i=s.actualBoundingBoxDescent):(e=0,i=0),this.textHeight=e+i,this.ascent=e,this.descent=i}return this.updateTextFlag=!1,this}clearTextSize(){return this.textWidth=0,this.textHeight=0,this.ascent=0,this.descent=0,this}copyTextSize(t){return this.textWidth=t.textWidth,this.textHeight=t.textHeight,this.ascent=t.ascent,this.descent=t.descent,this}get width(){return this.textWidth*this.scaleX}set width(t){this.textWidth>0?this.scaleX=t/this.textWidth:this.scaleX=1}get height(){return this.textHeight*this.scaleY}set height(t){this.textHeight>0?this.scaleY=t/this.textHeight:this.scaleY=1}get willRender(){return 0!==this.textWidth&&super.willRender}renderContent(){var t=this.context,e=this.style;if(e.hasBackgroundColor){t.fillStyle=e.backgroundColor;var i=this.drawTLX,s=this.drawTRX-i+1,r=e.backgroundBottomY;null==r&&(r=this.drawBLY);var n=e.backgroundHeight;null==n&&(n=r-this.drawTLY);var a=r-n;t.fillRect(i,a,s,n)}var o=e.hasFill,h=e.hasStroke;(o||h)&&(e.syncFont(t).syncStyle(t),h&&(e.syncShadow(t),t.strokeText(this.text,0,0)),o&&(e.syncShadow(t),t.fillText(this.text,0,0)))}get drawTLX(){return-this.leftSpace}get drawTLY(){return-this.ascent}get drawBLX(){return-this.leftSpace}get drawBLY(){return this.descent}get drawTRX(){return this.textWidth+this.rightSpace}get drawTRY(){return-this.ascent}get drawBRX(){return this.textWidth+this.rightSpace}get drawBRY(){return this.descent}}var pr=function(t,e){var i=this.createCharChildren(t,e);return this.addChild(i),this};Phaser.Display.Canvas.CanvasPool;class gr extends Ns{constructor(t,e,i){super(t,rr),this.setTexture(e,i),this.color=void 0}get frameWidth(){return this.frameObj?this.frameObj.cutWidth:0}get frameHeight(){return this.frameObj?this.frameObj.cutHeight:0}get offsetY(){return-this.height}set offsetY(t){}get key(){return this._key}set key(t){this.setDirty(this._key!=t),this._key=t}get frame(){return this._frame}set frame(t){this.setDirty(this._frame!=t),this._frame=t}setTexture(t,e){return this.key=t,this.frame=e,this.frameObj=this.scene.sys.textures.getFrame(t,e),this}get width(){return this.frameWidth*this.scaleX}set width(t){this.setDirty(this.width!==t),this.scaleX=t/this.frameWidth}get height(){return this.frameHeight*this.scaleY}set height(t){this.setDirty(this.height!==t),this.scaleY=t/this.frameHeight}setHeight(t,e){return void 0===e&&(e=!1),this.height=t,e&&(this.scaleX=this.scaleY),this}setColor(t){return this.color=t,this}modifyPorperties(t){return t.hasOwnProperty("color")&&this.setColor(t.color),super.modifyPorperties(t),this}renderContent(){Pi(this.frameObj,this.canvas,0,0,this.frameWidth,this.frameHeight,this.color,!1)}get drawTLX(){return-this.leftSpace}get drawTLY(){return 0}get drawBLX(){return-this.leftSpace}get drawBLY(){return this.frameHeight}get drawTRX(){return this.frameWidth+this.rightSpace}get drawTRY(){return 0}get drawBRX(){return this.frameWidth+this.rightSpace}get drawBRY(){return this.frameHeight}}var vr=function(t,e,i){var s=this.createImageChild(t,e,i);return this.addChild(s),this};class fr extends Ns{constructor(t,e,i,s){super(t,nr),this.setRenderCallback(e),this.setDrawerSize(i,s)}setRenderCallback(t){return t?this.renderContent=t.bind(this):delete this.renderContent,this}setDrawerSize(t,e){return!0===t?(this.toLocalPosition=!1,t=void 0,e=void 0):this.toLocalPosition=!0,void 0===t&&(t=0),void 0===e&&(e=t),this.drawerWidth=t,this.drawerHeight=e,this}onFree(){super.onFree(),this.setRenderCallback()}get width(){return this.drawerWidth*this.scaleX}set width(t){this.setDirty(this.width!==t),this.scaleX=this.drawerWidth>0?t/this.drawerWidth:1}get height(){return this.drawerHeight*this.scaleY}set height(t){this.setDirty(this.height!==t),this.scaleY=this.drawerHeight>0?t/this.drawerHeight:1}get offsetY(){return-this.height}set offsetY(t){}get drawTLX(){return-this.leftSpace}get drawTLY(){return 0}get drawBLX(){return-this.leftSpace}get drawBLY(){return this.drawerHeight}get drawTRX(){return this.drawerWidth+this.rightSpace}get drawTRY(){return 0}get drawBRX(){return this.drawerWidth+this.rightSpace}get drawBRY(){return this.drawerHeight}}let mr=class extends Ns{constructor(t,e){super(t,ar),this.setSpaceWidth(e)}get width(){return this.spaceWidth*this.scaleX}set width(t){this.spaceWidth>0?this.scaleX=t/this.spaceWidth:this.scaleX=1}setSpaceWidth(t){return this.spaceWidth=t,this}};var yr=function(t){var e=this.createSpaceChild(t);return this.addChild(e),this};class br extends Os{constructor(t,e,i,s,r){super(t,or),this.setName(e).setParameter(s).setCallback(i,r)}setName(t){return this.name=t,this}setParameter(t){return this.param=t,this}setCallback(t,e){return this.callback=t,this.scope=e,this}exec(){return this.scope?this.callback.call(this.scope,this.param,this.name):this.callback(this.param,this.name)}onFree(){super.onFree(),this.setName().setCallback().setParameter()}}var xr=function(t,e,i,s){var r=this.createCommandChild(t,e,i,s);return this.addChild(r),this},Cr=function(t){var e={callback:void 0,start:0,isLastPage:!1,maxLines:void 0,padding:void 0,letterSpacing:void 0,hAlign:void 0,vAlign:void 0,children:[],lines:[],maxLineWidth:0,linesHeight:0,lineHeight:void 0,maxLineHeight:0,linesWidth:0,lineWidth:void 0};return Object.assign(e,t)};const kr={none:0,word:1,char:2,character:2,mix:3};var wr=function(t,e,i,s){void 0===s&&(s={word:[],width:0}),s.word.length=0;for(var r=2===i,n=3===i,a=!r&&!n,o=t.length,h=e,l=s.word,d=0,c=!1;h0&&!o){var h=this.fixedHeight-s;i>0?n=h/i:(n=(l=Or.call(this)).height,a=l.ascent,i=Math.floor((h-a)/n))}else{var l;n=(l=Or.call(this)).height,a=l.ascent}}else this.fixedHeight>0?void 0===(i=Er(t,"maxLines"))&&(h=this.fixedHeight-s,i=Math.floor(h/n)):i=Er(t,"maxLines",0);void 0===a&&(a=n);var d=0===i,c=Er(t,"wrapMode");void 0===c&&(c=Er(t,"charWrap",!1)?"char":"word"),"string"==typeof c&&(c=kr[c]);var u=Er(t,"wrapWidth",void 0);void 0===u&&(this.fixedWidth>0?u=this.fixedWidth-r:(u=1/0,c=0));for(var p=Er(t,"letterSpacing",0),g=Er(t,"hAlign",0),v=Er(t,"vAlign",0),f=Er(t,"justifyPercentage",.25),m=Cr({callback:"runWordWrap",start:e,padding:this.wrapPadding,letterSpacing:p,maxLines:i,hAlign:g,vAlign:v,justifyPercentage:f,ascent:a,lineHeight:n,wrapWidth:u,wrapMode:c}),y=this.children,b=0,x=y.length;b0&&(E.push({children:_,width:R}),L=Math.max(L,R)),m.start+=M.length,m.isLastPage=!B&&m.start===O,m.maxLineWidth=L,m.linesHeight=E.length*n;var Y=this.fixedWidth>0?this.fixedWidth:m.maxLineWidth+r,X=this.fixedHeight>0?this.fixedHeight:m.linesHeight+s;for(function(t,e,i){for(var s,r,n=t.hAlign,a=t.vAlign,o=t.justifyPercentage,h=t.lines,l=0,d=h.length;l0?(a=this.fixedWidth-r)/i:0;else if(this.fixedWidth>0){if(void 0===(i=Lr(t,"maxLines",void 0))){var a=this.fixedWidth-r;i=Math.floor(a/n)+1}}else i=Lr(t,"maxLines",0);var o=0===i,h=Lr(t,"fixedCharacterHeight",void 0);if(void 0===h){var l=Lr(t,"charPerLine",void 0);if(void 0!==l){var d=this.fixedHeight-s;h=Math.floor(d/l)}}var c=Lr(t,"wrapHeight",void 0);void 0===c&&(c=this.fixedHeight>0?this.fixedHeight-s:1/0);for(var u=Lr(t,"letterSpacing",0),p=Lr(t,"rtl",!0),g=Lr(t,"hAlign",p?2:0),v=Lr(t,"vAlign",0),f=Cr({callback:"runVerticalWrap",start:e,padding:this.wrapPadding,letterSpacing:u,maxLines:i,hAlign:g,vAlign:v,lineWidth:n,fixedCharacterHeight:h,wrapHeight:c,rtl:p}),m=this.children,y=0,b=m.length;y0&&(M.push({children:E,height:_}),R=Math.max(R,_)),f.start+=O.length,f.isLastPage=f.start===T,f.maxLineHeight=R,f.linesWidth=M.length*n;var A=this.fixedWidth>0?this.fixedWidth:f.linesWidth+r,z=this.fixedHeight>0?this.fixedHeight:f.maxLineHeight+s;for(function(t,e,i){var s,r,n=t.hAlign,a=t.vAlign,o=t.rtl,h=t.lines,l=t.lineWidth,d=t.linesWidth;switch(n){case 1:case"center":s=(e-d)/2;break;case 2:case"right":s=e-d;break;default:s=0}o&&(s+=l);for(var c=0,u=h.length;c0?t:this.width,e>0?e:this.height)),this},setPadding:function(t,e){var i=this.padding,s=i.left,r=i.right,n=i.top,a=i.bottom;return Ts(i,t,e),this.dirty=this.dirty||s!=i.left||r!=i.right||n!=i.top||a!=i.bottom,this},getPadding:function(t){return Ps(this.padding,t)},modifyTextStyle:function(t){return this.textStyle.modify(t),this},modifyDefaultTextStyle:function(t){return this.defaultTextStyle.modify(t),this},resetTextStyle:function(){return this.textStyle.copyFrom(this.defaultTextStyle),this},setTestString:function(t){return this.testString=t,this},removeChild:function(t){return this.poolManager.free(t),er(this.children,t),this.lastAppendedChildren.length=0,this.lastOverChild=null,this.dirty=!0,this},removeChildren:function(){return this.poolManager.freeMultiple(this.children),this.children.length=0,this.lastAppendedChildren.length=0,this.lastOverChild=null,this.dirty=!0,this},popChild:function(t){return ir(this.children,t),this.lastAppendedChildren.length=0,this.lastOverChild=null,this.dirty=!0,this},clearContent:function(){return this.setText(),this},addChild:function(t,e){var i=Array.isArray(t);return void 0===e||e===this.children.length?i?this.children.push(...t):this.children.push(t):i?this.children.splice(e,0,...t):this.children.splice(e,0,t),this.lastAppendedChildren.length=0,i?this.lastAppendedChildren.push(...t):this.lastAppendedChildren.push(t),this},createCharChild:function(t,e){e&&this.textStyle.modify(e);var i=this.poolManager.allocate(sr);return null===i?i=new ur(this,t,this.textStyle):i.setParent(this).setActive().modifyStyle(this.textStyle).setText(t),i},createCharChildren:function(t,e){e&&this.textStyle.modify(e);for(var i=[],s=0,r=t.length;se&&(s=e,r=t)})),r},getCharWorldPosition:function(t,e,i,s){return"number"==typeof t&&(t=this.getCharChild(t,!0)),Ws(this,t,e,i,s)},setToMinSize:function(){for(var t=this.children,e=0,i=0,s=0,r=t.length;s=i.length&&(t=i.length);for(var s=0,r=0;r>16&255},yn=function(t){return t>>8&255},bn=function(t){return 255&t};const xn=Phaser.Events.EventEmitter;var Cn=function(t,e,i,s,r,n){return void 0===n?n={}:!0===n&&(n=kn),"number"!=typeof i&&(i=0,s=0),n.x=r.x+r.width*t+i,n.y=r.y+r.height*e+s,n},kn={},wn=function(t,e,i,s,r,n,a){if(t.hasOwnProperty("vp"))return t;"function"==typeof i&&(a=i,i=void 0),"function"==typeof r&&(a=r,r=void 0),void 0===i&&(i=.5),void 0===s&&(s=.5),void 0===r&&(r=0),void 0===n&&(n=0),void 0===a&&(a=Cn),function(t){if(t.events)return t;var e=new xn,i=t.x;Object.defineProperty(t,"x",{get:function(){return i},set:function(s){i!==s&&(i=s,e.emit("update",t))}});var s=t.y;Object.defineProperty(t,"y",{get:function(){return s},set:function(i){s!==i&&(s=i,e.emit("update",t))}});var r=t.width;Object.defineProperty(t,"width",{get:function(){return r},set:function(i){r!==i&&(r=i,e.emit("update",t))}});var n=t.height;Object.defineProperty(t,"height",{get:function(){return n},set:function(i){n!==i&&(n=i,e.emit("update",t))}}),t.events=e}(e);var o=e.events;t.vp=e;var h=function(){a(i,s,r,n,e,t)};o.on("update",h),t.once("destroy",(function(){o.off("update",h),t.vp=void 0})),Object.defineProperty(t,"vpx",{get:function(){return i},set:function(t){i!==t&&(i=t,h())}}),Object.defineProperty(t,"vpy",{get:function(){return s},set:function(t){s!==t&&(s=t,h())}}),Object.defineProperty(t,"vpxOffset",{get:function(){return r},set:function(t){r!==t&&(r=t,h())}}),Object.defineProperty(t,"vpyOffset",{get:function(){return n},set:function(t){n!==t&&(n=t,h())}}),h()},Sn=function(t){return t.preFX?t.preFX:t.postFX?t.postFX:null},Pn=function(t,e){t._effectSwitchNames||(t._effectSwitchNames=[],t.clearAllEffects=function(){for(var e=t._effectSwitchNames,i=0,s=e.length;i0&&void 0!==t.setTint},useAlphaFadeEffect(t){return(void 0===this.fadeMode||1===this.fadeMode)&&this.fadeTime>0&&void 0!==t.setAlpha},useRevealEffect(t){return this.fadeMode>=2&&this.fadeMode<=5&&this.fadeTime>0&&(t.preFX||t.postFX)},fadeBob(t,e,i,s){var r=t.gameObject;if(this.useTintFadeEffect(r))void 0!==e&&t.setProperty("tintGray",255*e),t.easeProperty({property:"tintGray",value:Math.floor(255*i),duration:this.fadeTime,delay:0,ease:"Linear",repeat:0,yoyo:!1,from:!1,complete:s});else if(this.useAlphaFadeEffect(r))void 0!==e&&t.setProperty("alpha",e),t.easeProperty({property:"alpha",value:i,duration:this.fadeTime,delay:0,ease:"Linear",repeat:0,yoyo:!1,from:!1,complete:s});else if(this.useRevealEffect(r)){var n;switch(Mn(r,"reveal"),this.fadeMode){case 2:n="revealUp";break;case 3:n="revealDown";break;case 4:n="revealLeft";break;case 5:n="revealRight"}void 0===e&&(e=0),r[n]=e,t.easeProperty({property:n,value:i,duration:this.fadeTime,delay:0,ease:"Linear",repeat:0,yoyo:!1,from:!1,complete:s}),t.getTweenTask(n).once("complete",(function(){r[n]=null}))}else s&&s(r);return this}},An=function(t){return void 0!==t.displayWidth?t.displayWidth:t.width},zn=function(t){return void 0!==t.displayHeight?t.displayHeight:t.height};const Fn=Phaser.Geom.Rectangle,Yn=Phaser.Math.Vector2,Xn=Phaser.Math.RotateAround;var Wn=function(t,e){if(void 0===e?e=new Fn:!0===e&&(void 0===Vn&&(Vn=new Fn),e=Vn),t.getBounds)return t.getBounds(e);var i,s,r,n,a,o,h,l;if(t.parentContainer){var d=t.parentContainer.getBoundsTransformMatrix();Gn(t,e),d.transformPoint(e.x,e.y,e),i=e.x,s=e.y,Hn(t,e),d.transformPoint(e.x,e.y,e),r=e.x,n=e.y,Un(t,e),d.transformPoint(e.x,e.y,e),a=e.x,o=e.y,Nn(t,e),d.transformPoint(e.x,e.y,e),h=e.x,l=e.y}else Gn(t,e),i=e.x,s=e.y,Hn(t,e),r=e.x,n=e.y,Un(t,e),a=e.x,o=e.y,Nn(t,e),h=e.x,l=e.y;return e.x=Math.min(i,r,a,h),e.y=Math.min(s,n,o,l),e.width=Math.max(i,r,a,h)-e.x,e.height=Math.max(s,n,o,l)-e.y,e},Vn=void 0,Gn=function(t,e,i){return void 0===e?e=new Yn:!0===e&&(void 0===Kn&&(Kn=new Yn),e=Kn),t.getTopLeft?t.getTopLeft(e):(e.x=t.x-An(t)*t.originX,e.y=t.y-zn(t)*t.originY,Jn(t,e,i))},Hn=function(t,e,i){return void 0===e?e=new Yn:!0===e&&(void 0===Kn&&(Kn=new Yn),e=Kn),t.getTopRight?t.getTopRight(e):(e.x=t.x-An(t)*t.originX+An(t),e.y=t.y-zn(t)*t.originY,Jn(t,e,i))},Un=function(t,e,i){return void 0===e?e=new Yn:!0===e&&(void 0===Kn&&(Kn=new Yn),e=Kn),t.getBottomLeft?t.getBottomLeft(e):(e.x=t.x-An(t)*t.originX,e.y=t.y-zn(t)*t.originY+zn(t),Jn(t,e,i))},Nn=function(t,e,i){return void 0===e?e=new Yn:!0===e&&(void 0===Kn&&(Kn=new Yn),e=Kn),t.getBottomRight?t.getBottomRight(e):(e.x=t.x-An(t)*t.originX+An(t),e.y=t.y-zn(t)*t.originY+zn(t),Jn(t,e,i))},$n=function(t,e,i){void 0===e?e=new Yn:!0===e&&(void 0===Kn&&(Kn=new Yn),e=Kn);var s=An(t),r=zn(t);return e.x=t.x+s*(.5-t.originX),e.y=t.y+r*(.5-t.originY),Jn(t,e,i)},Kn=void 0,Jn=function(t,e,i){return void 0===i&&(i=!1),0!==t.rotation&&Xn(e,t.x,t.y,t.rotation),i&&t.parentContainer&&t.parentContainer.getBoundsTransformMatrix().transformPoint(e.x,e.y,e),e};const qn=Phaser.Utils.Objects.GetValue;var Zn=function(t,e,i){var s,r,n,a,o;if("number"==typeof i?s=i:(s=qn(i,"color"),r=qn(i,"lineWidth"),n=qn(i,"fillColor"),a=qn(i,"fillAlpha",1),o=qn(i,"padding",0)),Array.isArray(t))for(var h=0,l=t.length;h0?-this.delay:0,this.state=this.nowTime>=0?Va:Wa,this.repeatCounter=0,this}stop(){return this.state=Xa,this}update(t,e){this.state!==Xa&&this.state!==Ha&&0!==e&&0!==this.timeScale&&(this.nowTime+=e*this.timeScale,this.justRestart=!1,this.nowTime>=this.duration?-1===this.repeat||this.repeatCounter0&&(this.nowTime-=this.repeatDelay,this.state=Ga)):(this.nowTime=this.duration,this.state=Ha):this.nowTime>=0&&(this.state=Va))}get t(){var t;switch(this.state){case Xa:case Wa:case Ga:t=0;break;case Va:t=this.nowTime/this.duration;break;case Ha:t=1}return Fa(t,0,1)}set t(t){(t=Fa(t,-1,1))<0?(this.state=Wa,this.nowTime=-this.delay*t):(this.state=Va,this.nowTime=this.duration*t,1===t&&0!==this.repeat&&this.repeatCounter++)}setT(t){return this.t=t,this}get isIdle(){return this.state===Xa}get isDelay(){return this.state===Wa}get isCountDown(){return this.state===Va}get isRunning(){return this.state===Wa||this.state===Va}get isDone(){return this.state===Ha}get isOddIteration(){return!(1&~this.repeatCounter)}get isEvenIteration(){return!(1&this.repeatCounter)}};const Xa=0,Wa=1,Va=2,Ga=3,Ha=-1;class Ua extends ja{constructor(t,e){super(t,e),this.timer=new Ya}shutdown(t){this.isShutdown||(super.shutdown(t),this.timer.destroy(),this.timer=void 0)}start(){return this.timer.start(),super.start(),this}stop(){return this.timer.stop(),super.stop(),this}complete(){return this.timer.stop(),super.complete(),this}}const Na=Phaser.Utils.Objects.GetValue,$a=Phaser.Utils.Objects.GetAdvancedValue,Ka=Phaser.Tweens.Builders.GetEaseFunction;class Ja extends Ua{resetFromJSON(t){return this.timer.resetFromJSON(Na(t,"timer")),this.setEnable(Na(t,"enable",!0)),this.setTarget(Na(t,"target",this.parent)),this.setDelay($a(t,"delay",0)),this.setDuration($a(t,"duration",1e3)),this.setEase(Na(t,"ease","Linear")),this.setRepeat(Na(t,"repeat",0)),this}setEnable(t){return null==t&&(t=!0),this.enable=t,this}setTarget(t){return void 0===t&&(t=this.parent),this.target=t,this}setDelay(t){return this.delay=t,this}setDuration(t){return this.duration=t,this}setRepeat(t){return this.repeat=t,this}setRepeatDelay(t){return this.repeatDelay=t,this}setEase(t){return void 0===t&&(t="Linear"),this.ease=t,this.easeFn=Ka(t),this}start(){return this.timer.isRunning||super.start(),this}restart(){return this.timer.stop(),this.start.apply(this,arguments),this}stop(t){return void 0===t&&(t=!1),super.stop(),t&&(this.timer.setT(1),this.updateTarget(this.target,this.timer),this.complete()),this}update(t,e){if(!this.isRunning||!this.enable||this.parent.hasOwnProperty("active")&&!this.parent.active)return this;var i=this.target,s=this.timer;return s.update(t,e),s.isDelay||this.updateTarget(i,s),this.emit("update",i,this),s.isDone&&this.complete(),this}updateTarget(t,e){}}const qa=Phaser.Sound.BaseSound;var Za=function(t){return t instanceof qa};const Qa=Phaser.Utils.Objects.GetValue,to=Phaser.Utils.Objects.GetAdvancedValue,eo=Phaser.Math.Linear;let io=class extends Ja{constructor(t,e,i){Za(t)&&(i=e,e=t,t=void 0),e.active=!0,e.scene=t,e.game=e.manager.game,super(e,i),this.volume={},this.resetFromJSON(i)}resetFromJSON(t){return super.resetFromJSON(t),this.setMode(Qa(t,"mode",0)),this.setEnable(Qa(t,"enable",!0)),this.setVolumeRange(to(t,"volume.start",this.parent.volume),to(t,"volume.end",0)),this}setMode(t){return"string"==typeof t&&(t=so[t]),this.mode=t,this}setVolumeRange(t,e){return this.volume.start=t,this.volume.end=e,this}start(){return this.timer.isRunning||(this.parent.setVolume(this.volume.start),this.timer.setDelay(this.delay).setDuration(this.duration),super.start()),this}updateTarget(t,e){t.volume=eo(this.volume.start,this.volume.end,e.t)}complete(){switch(super.complete(),this.mode){case 1:this.parent.stop();break;case 2:this.parent.stop(),this.parent.destroy()}return this}};const so={stop:1,destroy:2};var ro=function(t,e,i,s,r){Za(t)&&(r=s,s=i,i=e,e=t,t=void 0),void 0===s&&(s=1),void 0===r&&(r=0);var n,a={mode:0,volume:{start:r,end:s},duration:i};return"string"==typeof e&&(e=t.sys.sound.add(e)),e.hasOwnProperty("_fade")?(n=e._fade).stop().resetFromJSON(a):(n=new io(t,e,a),e._fade=n),n.start(),e.isPlaying||e.setVolume(r).play(),e},no=function(t,e,i,s){Za(t)&&(s=i,i=e,e=t,t=void 0),void 0===s&&(s=!0);var r,n={mode:s?2:1,volume:{start:e.volume,end:0},duration:i};return e.hasOwnProperty("_fade")?(r=e._fade).stop().resetFromJSON(n):(r=new io(t,e,n),e._fade=r),r.start(),e.isPlaying||e.play(),e};const ao=Phaser.Utils.Objects.GetValue;var oo={setBackgroundMusicLoop(t){return void 0===t&&(t=!0),this.backgroundMusicLoop=t,this},setBackgroundMusicFadeTime(t){return this.backgroundMusicFadeTime=t,this},getBackgroundMusic(){return this.backgroundMusic},setCurrentBackgroundMusic(t){return this.backgroundMusic=t,t&&(t.once("complete",(function(){this.backgroundMusic===t&&(this.backgroundMusic.destroy(),this.backgroundMusic=void 0)}),this).once("destroy",(function(){this.backgroundMusic===t&&(this.backgroundMusic=void 0)}),this),t.isPlaying||t.play()),this},playBackgroundMusic(t,e){if(!this.hasAudio(t))return console.error(`[Sound manager] Audio key'${t}' is not existed`),this;if(this.backgroundMusic&&this.backgroundMusic.key===t)return this;this.stopBackgroundMusic();var i=this.sound.add(t,{loop:ao(e,"loop",this.backgroundMusicLoop),mute:ao(e,"mute",this.backgroundMusicMute),volume:ao(e,"volume",this.backgroundMusicVolume),detune:ao(e,"detune",0),rate:ao(e,"rate",1)});return this.setCurrentBackgroundMusic(i),this.backgroundMusicFadeTime>0&&this.fadeInBackgroundMusic(this.backgroundMusicFadeTime),this},pauseBackgroundMusic(){return this.backgroundMusic&&this.backgroundMusic.pause(),this},resumeBackgroundMusic(){return this.backgroundMusic&&this.backgroundMusic.resume(),this},stopBackgroundMusic(){return this.backgroundMusic&&(this.backgroundMusicFadeTime>0?this.fadeOutBackgroundMusic(this.backgroundMusicFadeTime,!0):(this.backgroundMusic.stop(),this.backgroundMusic.destroy(),this.backgroundMusic=void 0)),this},fadeInBackgroundMusic(t){return this.backgroundMusic&&ro(this.backgroundMusic,t,this.backgroundMusicVolume,0),this},fadeOutBackgroundMusic(t,e){return this.backgroundMusic&&no(this.backgroundMusic,t,e),this},crossFadeBackgroundMusic(t,e){if(!this.hasAudio(t))return console.error(`[Sound manager] Audio key'${t}' is not existed`),this;var i=this.backgroundMusicFadeTime;return this.backgroundMusicFadeTime=0,this.fadeOutBackgroundMusic(e,!0).playBackgroundMusic(t).fadeInBackgroundMusic(e),this.backgroundMusicFadeTime=i,this},setBackgroundMusicMute(t){return void 0===t&&(t=!0),this.backgroundMusicMute=t,this},setBackgroundMusicVolume(t){return this.backgroundMusicVolume=t,this},setBackgroundMusicRate(t){return this.backgroundMusic&&this.backgroundMusic.setRate(t),this},setBackgroundMusicDetune(t){return this.backgroundMusic&&this.backgroundMusic.setDetune(t),this}};const ho=Phaser.Utils.Objects.GetValue;var lo={setBackgroundMusic2Loop(t){return void 0===t&&(t=!0),this.backgroundMusic2Loop=t,this},setBackgroundMusic2FadeTime(t){return this.backgroundMusic2FadeTime=t,this},getBackgroundMusic2(){return this.backgroundMusic2},setCurrentBackgroundMusic2(t){return this.backgroundMusic2=t,t&&(t.once("complete",(function(){this.backgroundMusic2===t&&(this.backgroundMusic2.destroy(),this.backgroundMusic2=void 0)}),this).once("destroy",(function(){this.backgroundMusic2===t&&(this.backgroundMusic2=void 0)}),this),t.isPlaying||t.play()),this},playBackgroundMusic2(t,e){if(!this.hasAudio(t))return console.error(`[Sound manager] Audio key'${t}' is not existed`),this;if(this.backgroundMusic2&&this.backgroundMusic2.key===t)return this;this.stopBackgroundMusic2();var i=this.sound.add(t,{loop:ho(e,"loop",this.backgroundMusicLoop),mute:ho(e,"mute",this.backgroundMusic2Mute),volume:ho(e,"volume",this.backgroundMusic2Volume),detune:ho(e,"detune",0),rate:ho(e,"rate",1)});return this.setCurrentBackgroundMusic2(i),this.backgroundMusic2FadeTime>0&&this.fadeInBackgroundMusic2(this.backgroundMusic2FadeTime),this},pauseBackgroundMusic2(){return this.backgroundMusic2&&this.backgroundMusic2.pause(),this},resumeBackgroundMusic2(){return this.backgroundMusic2&&this.backgroundMusic2.resume(),this},stopBackgroundMusic2(){return this.backgroundMusic2&&(this.backgroundMusic2FadeTime>0?this.fadeOutBackgroundMusic2(this.backgroundMusic2FadeTime,!0):(this.backgroundMusic2.stop(),this.backgroundMusic2.destroy(),this.backgroundMusic2=void 0)),this},fadeInBackgroundMusic2(t){return this.backgroundMusic2&&ro(this.backgroundMusic2,t,this.backgroundMusic2Volume,0),this},fadeOutBackgroundMusic2(t,e){return this.backgroundMusic2&&no(this.backgroundMusic2,t,e),this},crossFadeBackgroundMusic2(t,e){if(!this.hasAudio(t))return console.error(`[Sound manager] Audio key'${t}' is not existed`),this;var i=this.backgroundMusic2FadeTime;return this.backgroundMusic2FadeTime=0,this.fadeOutBackgroundMusic2(e,!0).playBackgroundMusic2(t).fadeInBackgroundMusic2(e),this.backgroundMusic2FadeTime=i,this},setBackgroundMusic2Mute(t){return void 0===t&&(t=!0),this.backgroundMusic2Mute=t,this},setBackgroundMusic2Volume(t){return this.backgroundMusic2Volume=t,this},setBackgroundMusic2Rate(t){return this.backgroundMusic2&&this.backgroundMusic2.setRate(t),this},setBackgroundMusic2Detune(t){return this.backgroundMusic2&&this.backgroundMusic2.setDetune(t),this}};const co=Phaser.Utils.Array.Remove,uo=Phaser.Utils.Objects.GetValue;var po={getSoundEffects(){return this.soundEffects},getLastSoundEffect(){return this.soundEffects[this.soundEffects.length-1]},playSoundEffect(t,e){if(!this.hasAudio(t))return console.error(`[Sound manager] Audio key'${t}' is not existed`),this;var i=this.sound.add(t,{mute:uo(e,"mute",this.soundEffectsMute),volume:uo(e,"volume",this.soundEffectsVolume),detune:uo(e,"detune",0),rate:uo(e,"rate",1)});return this.soundEffects.push(i),i.once("complete",(function(){i.destroy(),this.sound&&co(this.soundEffects,i)}),this).once("destroy",(function(){this.sound&&co(this.soundEffects,i)}),this).play(),this},stopAllSoundEffects(){for(var t=this.soundEffects.length-1;t>=0;t--){var e=this.soundEffects[t];e.stop(),e.destroy()}return this},fadeInSoundEffect(t){var e=this.getLastSoundEffect();return e&&ro(e,t,this.soundEffectsVolume,0),this},fadeOutSoundEffect(t,e){var i=this.getLastSoundEffect();return i&&no(i,t,e),this},fadeOutAllSoundEffects(t,e){for(var i=this.soundEffects.length-1;i>=0;i--)no(this.soundEffects[i],t,e);return this},setSoundEffectMute(t,e){if(void 0===t&&(t=!0),void 0===e&&(e=!1),e){var i=this.getLastSoundEffect();i&&i.setMute(t)}else this.soundEffectsMute=t;return this},setSoundEffectVolume(t,e){if(void 0===e&&(e=!1),e){var i=this.getLastSoundEffect();i&&i.setVolume(t)}else this.soundEffectsVolume=t;return this},setSoundEffectDetune(t,e){var i;void 0===e&&(e=!1);for(var s=0,r=(i=e?[this.getLastSoundEffect()]:this.soundEffects).length;s=0;t--){var e=this.soundEffects[t];e.stop(),e.destroy()}return this},fadeInSoundEffect2(t){var e=this.getLastSoundEffect2();return e&&ro(e,t,this.soundEffects2Volume,0),this},fadeOutSoundEffect2(t,e){var i=this.getLastSoundEffect2();return i&&no(i,t,e),this},fadeOutAllSoundEffects2(t,e){for(var i=this.soundEffects2.length-1;i>=0;i--)no(this.soundEffects2[i],t,e);return this},setSoundEffect2Mute(t,e){if(void 0===t&&(t=!0),void 0===e&&(e=!1),e){var i=this.getLastSoundEffect2();i&&i.setMute(t)}else this.soundEffects2Mute=t;return this},setSoundEffect2Volume(t,e){if(void 0===e&&(e=!1),e){var i=this.getLastSoundEffect2();i&&i.setVolume(t)}else this.soundEffects2Volume=t;return this},setSoundEffect2Detune(t,e){var i;void 0===e&&(e=!1);for(var s=0,r=(i=e?[this.getLastSoundEffect2()]:this.soundEffects2).length;s=0;t--)this.soundEffects[t].destroy();if(this.soundEffects.length=0,this.soundEffects2.length)for(t=this.soundEffects2.length-1;t>=0;t--)this.soundEffects2[t].destroy();return this.soundEffects2.length=0,this.sound=void 0,this}get backgroundMusicMute(){return this._backgroundMusicMute}set backgroundMusicMute(t){this._backgroundMusicMute=t,this.backgroundMusic&&this.backgroundMusic.setMute(mute)}get backgroundMusicVolume(){return this._backgroundMusicVolume}set backgroundMusicVolume(t){this._backgroundMusicVolume=t,this.backgroundMusic&&this.backgroundMusic.setVolume(t)}get backgroundMusic2Mute(){return this._backgroundMusic2Mute}set backgroundMusic2Mute(t){this._backgroundMusic2Mute=t,this.backgroundMusic2&&this.backgroundMusic2.setMute(mute)}get backgroundMusic2Volume(){return this._backgroundMusic2Volume}set backgroundMusic2Volume(t){this._backgroundMusic2Volume=t,this.backgroundMusic2&&this.backgroundMusic2.setVolume(t)}get soundEffectsMute(){return this._soundEffectsMute}set soundEffectsMute(t){this._soundEffectsMute=t;for(var e=this.soundEffects,i=0,s=e.length;i");this.setDelimiters(e[0],e[1]),this.setTranslateTagNameCallback(J(t,"translateTagNameCallback")),this.isRunning=!1,this.isPaused=!1,this.skipEventFlag=!1,this.justCompleted=!1,this.lastTagStart=null,this.lastTagEnd=null,this.lastContent=null}shutdown(){this.destroyEventEmitter()}destroy(){this.shutdown()}setMultipleLinesTagEnable(t){return void 0===t&&(t=!0),this.multipleLinesTagEnable=t,this}setDelimiters(t,e){void 0===e&&(e=t[1],t=t[0]),this.delimiterLeft=t,this.delimiterRight=e,t=qi(this.delimiterLeft),e=qi(this.delimiterRight);var i=this.multipleLinesTagEnable?"gs":"gi";return this.reSplit=RegExp(`${t}(.+?)${e}`,i),this}setTranslateTagNameCallback(t){return this.translateTagNameCallback=t,this}setValueConverter(t){return!0===t?t=qo:t||(t=Qo),this.valueConverter=t,this}setLoopEnable(t){return void 0===t&&(t=!0),this.loopEnable=t,this}setSource(t){return this.source=t,this}resetIndex(t){return void 0===t&&(t=0),this.progressIndex=t,this.reSplit.lastIndex=t,this.lastTagStart=null,this.lastTagEnd=null,this.lastContent=null,this.justCompleted=!1,this.isRunning=!1,this}start(t){return this.setSource(t).restart(),this}restart(){this.resetIndex().next()}next(){if(this.isPaused&&this.onResume(),this.isRunning)return this;if(this.isRunning=!0,this.justCompleted)return this.isRunning=!1,this;0===this.reSplit.lastIndex&&this.onStart();var t=this.source,e=t.length;for(this.reSplit.lastIndex=this.progressIndex;;){var i=this.reSplit.exec(t);if(!i){if(this.progressIndex");this.setDelimiters(e[0],e[1])}setTagExpression(t){return t||(t=eh),this.tagExpression=t,this}setValueExpression(t){return t||(t=eh),this.valueExpression=t,this}setDelimiters(t,e){super.setDelimiters(t,e);var i=`(${this.tagExpression})(=(${this.valueExpression}))?`;if(this.reTag=RegExp(i,"i"),this.tagExpression!==eh||this.valueExpression!==eh){var s=`${this.tagExpression}(=${this.valueExpression})?`,r=`/${this.tagExpression}`;t=qi(this.delimiterLeft),e=qi(this.delimiterRight);var n=this.multipleLinesTagEnable?"gs":"gi";this.reSplit=RegExp(`${t}((${s})|(${r}))${e}`,n)}return this}onTag(t){var e=t.match(this.reTag),i=e[1],s="/"===i.charAt(0);if(s&&(i=i.substring(1,i.length)),this.translateTagNameCallback&&(i=this.translateTagNameCallback(i)),this.skipEventFlag=!1,s)this.emit(`-${i}`),this.skipEventFlag||this.emit("-",i),this.lastTagEnd=i;else{var r=function(t,e,i){if(null==t)return[];void 0===e&&(e=qo),void 0===i&&(i=",");for(var s=t.split(i),r=0,n=s.length;r0){var n=this.timeline.addTimer({name:al,target:s,duration:r.duration,yoyo:r.yoyo,onStart:r.onStart,onProgress:r.onProgress,onComplete:r.onComplete});this.skipTypingAnimation&&n.seek(1)}else r.onStart&&r.onStart(s,0);this.minSizeEnable&&this.textPlayer.setToMinSize(),this.textPlayer.emit("typing",s);var a=this.nextChild;if(a)if(this.skipSpaceEnable&&(e=a).type===sr&&" "===e.text);else if(i+=this.speed+t,t=0,i>0){this.typingTimer=this.timeline.addTimer({name:"delay",target:this,duration:i,onComplete:function(t,e,i){t.typingTimer=void 0,ol.call(t,i.remainder)}});break}}else cr(s)&&s.exec()}this.minSizeEnable&&this.textPlayer.setToMinSize(),this.inTypingProcessLoop=!1},hl=function(t){switch(t){case"camera.fadein":case"camera.fadeout":case"camera.flash":case"camera.shake":case"camera.zoom":case"camera.rotate":case"camera.scroll":return!0;default:return!1}},ll=function(t,e){var i=e.split(".");return t.gameObjectManagers.hasOwnProperty(i[0])},dl=function(t,e,i,s){var r=t.waitEventManager,n=e.split("."),a=n[0],o=t.getGameObjectManager(a),h=`wait.${a}`;switch(n.length){case 1:return r.waitGameObjectManagerEmpty(a),void t.emit(h);case 2:var l=n[1];return r.waitGameObjectDestroy(a,l),void t.emit(h,l);case 3:l=n[1];var d=n[2];if("number"==typeof o.getProperty(l,d))return r.waitGameObjectTweenComplete(a,l,d),void t.emit(h,l,d);var c=d,u=c.startsWith("!");return u&&(c=c.substring(1)),o.hasData(l,c)?(r.waitGameObjectDataFlag(a,l,c,!u),void t.emit(h,l,c)):void r.waitTime(0)}};const cl=Phaser.Input.Keyboard.KeyCodes;var ul=function(t,e,i,s){var r=t.waitEventManager;r.clearWaitCompleteCallbacks().addWaitCompleteCallback(i,s);for(var n=0,a=(e="string"==typeof e&&e.length>1&&-1!==e.indexOf("|")?e.split("|"):[e]).length;n0&&n.chainAnimation(i,s)},Ol=function(t){var e,i;[e,...i]=t,this.getGameObjectManager(e).stopAnimation(...i)},Ml=function(t){var e,i;[e,...i]=t,this.getGameObjectManager(e).pauseAnimation(...i)},El=function(t){var e,i;[e,...i]=t,this.getGameObjectManager(e).chainAnimation(...i)};const _l=[function(t,e,i){var s=i.name;e.on("+",(function(i,...r){if(!e.skipEventFlag){var n,a=i.split(".");Pl(a,s)&&(n=a[1],xr.call(t,`${s}.play`,Tl,[s,n,r],t),e.skipEvent())}})).on("+",(function(i){if(!e.skipEventFlag){var r,n=i.split(".");(function(t,e){return 3===t.length&&t[0]===e&&"stop"===t[2]})(n,s)&&(r=n[1],xr.call(t,`${s}.stop`,Ol,[s,r],t),e.skipEvent())}})).on("-",(function(i){if(!e.skipEventFlag){var r,n=i.split(".");Pl(n,s)&&(r=n[1],xr.call(t,`${s}.stop`,Ol,[s,r],t),e.skipEvent())}}))},function(t,e,i){var s=i.name;e.on("+",(function(i){if(!e.skipEventFlag){var r,n=i.split(".");(function(t,e){return 3===t.length&&t[0]===e&&"pause"===t[2]})(n,s)&&(r=n[1],xr.call(t,`${s}.pause`,Ml,[s,r],t),e.skipEvent())}}))},function(t,e,i){var s=i.name;e.on("+",(function(i){if(!e.skipEventFlag){var r,n=i.split(".");if(function(t,e){return 3===t.length&&t[0]===e&&"chain"===t[2]}(n,s)){r=n[1];var a=Array.prototype.slice.call(arguments,1);xr.call(t,`${s}.chain`,El,[s,r,a],t),e.skipEvent()}}}))}];var Rl=function(t){void 0===t&&(t={}),t.name="sprite",t.parseCallbacks=_l,t.createGameObject=Cl(t.createGameObject),this.addGameObjectManager(t,Sl)},Ll=function(t,e){return 2===t.length&&t[0]===e},Bl=function(t){var e,i;[e,...i]=t,this.getGameObjectManager(e).add(...i)},Il=function(t){var e,i;[e,...i]=t,this.getGameObjectManager(e).remove(...i)},Dl=function(t){this.getGameObjectManager(t).removeAll()},jl=function(t){var e,i,s,r;[e,i,s,...r]=t;var n=`${e}.${s}`;if(this.emit(n,i,...r),!(this.listenerCount(n)>0)){var a=this.getGameObjectManager(e);a.hasMethod(i,s)?a.call(i,s,...r):a.setProperty(i,s,r[0])}},Al={to:!0,yoyo:!0,from:!0,toLeft:!0,toRight:!0,toUp:!0,toDown:!0,yoyoLeft:!0,yoyoRight:!0,yoyoUp:!0,yoyoDown:!0,fromLeft:!0,fromRight:!0,fromUp:!0,fromDown:!0},zl=function(t){var e,i,s,r,n,a,o,h;[e,i,s,r,n,a,o,h]=t;var l=this.getGameObjectManager(e),d=l.getProperty(i,s);if("number"==typeof d){h.endsWith("Left")||h.endsWith("Up")?h.startsWith("to")||h.startsWith("yoyo")?r=d-r:h.startsWith("from")&&(l.setProperty(i,s,d-r),r=d):h.endsWith("Right")||h.endsWith("Down")?h.startsWith("to")||h.startsWith("yoyo")?r=d+r:h.startsWith("from")&&(l.setProperty(i,s,d+r),r=d):"from"===h&&(l.setProperty(i,s,r),r=d);var c=h.startsWith("yoyo");l.easeProperty(i,{property:s,value:r,duration:n,ease:a,repeat:o,yoyo:c})}};const Fl=[function(t,e,i){var s=i.name;e.on("+",(function(i,...r){if(!e.skipEventFlag){var n,a=i.split(".");Ll(a,s)&&(n=a[1],xr.call(t,`${s}.add`,Bl,[s,n,...r],t),e.skipEvent())}})).on("-",(function(i){if(!e.skipEventFlag){var r,n=i.split(".");Ll(n,s)&&(r=n[1],xr.call(t,`${s}.remove`,Il,[s,r],t),e.skipEvent())}}))},function(t,e,i){var s=i.name;e.on("-",(function(i){e.skipEventFlag||i===s&&(xr.call(t,`${s}.removeall`,Dl,s,t),e.skipEvent())}))},function(t,e,i){var s=i.name;e.on("+",(function(i,...r){if(!e.skipEventFlag){var n,a,o=i.split(".");(function(t,e){return 3===t.length&&t[0]===e})(o,s)&&(n=o[1],a=o[2],xr.call(t,`${s}.call`,jl,[s,n,a,...r],t),e.skipEvent())}}))},function(t,e,i){var s=i.name;t.getGameObjectManager(s),e.on("+",(function(i,r,n,a,o){if(!e.skipEventFlag){var h,l,d,c=i.split(".");(function(t,e){return 4===t.length&&t[0]===e&&Al[t[3]]})(c,s)&&(h=c[1],l=c[2],d=c[3],"number"==typeof a&&(o=a,a=void 0),xr.call(t,`${s}.ease`,zl,[s,h,l,r,n,a,o,d],t),e.skipEvent())}}))}],Yl=Wo.addGameObjectManager;var Xl={addGameObjectManager(t,e){(t=t?Ve(t):{}).name||console.warn("[TextPlayer] Parameter 'name' is required in addGameObjectManager(config) method");var i=t.defaultLayer,s=t.createGameObject,r=this.layerManager;t.createGameObject=function(t,...e){var n=s.call(this,t,...e);return i&&r&&r.addToLayer(i,n),n},Yl.call(this,t,e);for(var n=t.parseCallbacks,a=0,o=(n=n?[...n,...Fl]:Fl).length;a0)return nd.length=0,!0;return nd.length=0,!1},nd=[],ad=void 0;const od=Phaser.Utils.Objects.GetValue;var hd=function(t,e,i){var s,r;for(var n in void 0===i&&(i={}),t)s=t[n],void 0!==(r=od(e,n,s[1]))&&(i[s[0]]=r);return i},ld=function(t){t.addEventListener("touchstart",dd,!1),t.addEventListener("touchmove",dd,!1),t.addEventListener("touchend",dd,!1),t.addEventListener("mousedown",dd,!1),t.addEventListener("mouseup",dd,!1),t.addEventListener("mousemove",dd,!1)},dd=function(t){t.stopPropagation()},cd=function(){return this.close(),this.emit("keydown-ENTER",this.parent,this),this},ud=function(){this.isOpened=!0,this.initText(),this.enterCloseEnable&&this.scene.input.keyboard.once("keydown-ENTER",cd,this),this.scene.sys.events.on("postupdate",this.updateText,this),this.clickOutSideTarget?(xa.call(this.clickOutSideTarget,this.parent),ba.call(this.clickOutSideTarget,this.parent),this.clickOutSideTarget.setInteractive().on("pointerdown",this.onClickOutside,this)):this.scene.input.on("pointerdown",this.onClickOutside,this),this.onOpenCallback&&this.onOpenCallback(this.parent,this),this.emit("open",this)},pd=function(){this.isOpened=!1,this.updateText(),this.enterCloseEnable&&this.scene.input.keyboard.off("keydown-ENTER",cd,this),this.scene.sys.events.off("postupdate",this.updateText,this),this.clickOutSideTarget?this.clickOutSideTarget.disableInteractive().off("pointerdown",this.onClickOutside,this):this.scene.input.off("pointerdown",this.onClickOutside,this),this.onCloseCallback&&this.onCloseCallback(this.parent,this),function(t){if(t){var e=t.parentElement;e&&e.removeChild(t)}}(this.node),this.node=void 0,this.emit("close",this)};const gd=Phaser.Utils.Objects.GetValue;var vd=function(t,e){var i,s=gd(e,"inputType",void 0);void 0===s&&(s=gd(e,"type","text")),"textarea"===s?(i=document.createElement("textarea")).style.resize="none":(i=document.createElement("input")).type=s;var r=gd(e,"style",void 0),n=i.style;hd(ed,r,n),n.position="absolute",n.opacity=0,n.pointerEvents="none",n.zIndex=0,n.transform="scale(0)",hd(td,e,i),ld(i);var a=t.scene.sys.scale;return(a.isFullscreen?a.fullscreenTarget:document.body).appendChild(i),i.addEventListener("focus",(function(e){ud.call(t)})),i.addEventListener("blur",(function(e){pd.call(t)})),i},fd={open:function(){return this.isOpened||this.readOnly||((t=this)!==ad&&(void 0!==ad&&ad.close(),ad=t),this.node||(this.node=vd(this,this.nodeConfig)),this.setFocus()),this;var t},close:function(){return this.isOpened?(this===ad&&(ad=void 0),this.setBlur(),this):this}};const md=Phaser.Utils.Objects.GetValue;class yd extends Ra{constructor(t,e){super(t);var i=md(e,"inputType",void 0);void 0===i&&(i=md(e,"type","text")),this.setEnterCloseEnable(md(e,"enterClose","textarea"!==i));var s=md(e,"onOpen",void 0);s||(s=md(e,"onFocus",void 0)),this.onOpenCallback=s,this.clickOutSideTarget=md(e,"clickOutSideTarget",void 0);var r=md(e,"onClose",void 0);r||(r=md(e,"onBlur",void 0)),this.onCloseCallback=r,this.onUpdateCallback=md(e,"onUpdate",void 0),this.isOpened=!1,t.on("pointerdown",(function(){this.open()}),this).setInteractive(),this.nodeConfig=function(t){void 0===t&&(t={});var e={};return id(t,e,"inputType"),id(t,e,"type"),id(t,e,"style"),id(t,e,ed),id(t,e,td),e}(e),this.node=void 0}destroy(){this.close(),this.clickOutSideTarget&&this.clickOutSideTarget.destroy(),super.destroy()}onClickOutside(t){sd(this.parent,t)||this.close()}setEnterCloseEnable(t){return void 0===t&&(t=!0),this.enterCloseEnable=t,this}initText(){}updateText(){}get text(){return this.node?this.node.value:""}set text(t){this.node&&(this.node.value=t)}setText(t){return this.text=t,this}get maxLength(){return this.nodeConfig.maxLength}set maxLength(t){this.nodeConfig.maxLength=t,this.node&&(this.node.maxLength=t)}setMaxLength(t){return this.maxLength=t,this}get minLength(){return this.nodeConfig.minLength}set minLength(t){this.nodeConfig.minLength=t,this.node&&(this.node.minLength=t)}setMinLength(t){return this.minLength=t,this}get placeholder(){return this.node.placeholder}set placeholder(t){this.node&&(this.node.placeholder=t)}setPlaceholder(t){return this.placeholder=t,this}selectText(t,e){return this.node?(void 0===t?this.node.select():this.node.setSelectionRange(t,e),this):this}selectAll(){return this.selectText(),this}get selectionStart(){return this.node?this.node.selectionStart:0}get selectionEnd(){return this.node?this.node.selectionEnd:0}get selectedText(){if(!this.node)return"";var t=this.node;return t.value.substring(t.selectionStart,t.selectionEnd)}get cursorPosition(){return this.node?this.node.selectionStart:0}set cursorPosition(t){this.node&&this.node.setSelectionRange(t,t)}setCursorPosition(t){return void 0===t?t=this.text.length:t<0&&(t=this.text.length+t),this.cursorPosition=t,this}get tooltip(){return this.node?this.node.title:""}set tooltip(t){if(!this.node)return this;this.node.title=t}setTooltip(t){return this.tooltip=t,this}setTextChangedCallback(t){return this.onTextChanged=t,this}get readOnly(){return this.nodeConfig.readOnly}set readOnly(t){this.nodeConfig.readOnly=t,this.node&&(this.node.readOnly=t)}setReadOnly(t){return void 0===t&&(t=!0),this.readOnly=t,this}get spellCheck(){return this.node?this.node.spellcheck:""}set spellCheck(t){this.node&&(this.node.spellcheck=t)}setSpellCheck(t){return this.spellCheck=t,this}get fontColor(){if(this.node)return this.node.style.color}set fontColor(t){this.node&&(this.node.style.color=t)}setFontColor(t){return this.fontColor=t,this}setStyle(t,e){return this.node?(this.node.style[t]=e,this):this}getStyle(t){if(this.node)return this.node.style[t]}scrollToBottom(){return this.node?(this.node.scrollTop=this.node.scrollHeight,this):this}setEnabled(t){return this.node?(void 0===t&&(t=!0),this.node.disabled=!t,this):this}setBlur(){return this.node?(this.node.blur(),this):this}setFocus(){return this.node?(this.node.focus(),this):this}get isFocused(){return this.isOpened}}Object.assign(yd.prototype,fd);var bd=function(t,e,i){t=t.replace(" ","");var s=i.previousText;if(t===s)return t;if(isNaN(t)){i.emit("nan",t,i),t=s;var r=i.cursorPosition-1;i.setText(t),i.setCursorPosition(r)}else i.previousText=t;return t},xd=function(t){var e=t.prevSelectionStart;if(null!==e){for(var i=t.prevSelectionEnd,s=t.parent,r=e;r=r&&h=i&&hi.length&&(t.prevCursorPosition=null),null!==t.prevCursorPosition&&(s=e.getCharChild(t.prevCursorPosition))&&("\n"===s.text&&s.clearTextSize(),e.emit("cursorout",s,t.prevCursorPosition,e)),null!=r&&(s=e.getCharChild(r))&&("\n"===s.text&&s.copyTextSize(e.lastInsertCursor),function(t){var e,i,s=t.parent,r=s.width,n=s.height,a=t.drawX,o=t.drawY,h=a+t.drawTLX,l=a+t.drawTRX,d=o+t.drawTLY,c=o+t.drawBLY;e=h<0?0-h:l>r?r-l:0,i=d<0?0-d:c>n?n-c:0,s._textOX+=e,s._textOY+=i}(s),e.emit("cursorin",s,r,e)),e.emit("movecursor",r,t.prevCursorPosition,e),t.prevCursorPosition=r)}(this)):(xd(this),Cd(this)),this}setNumberInput(){return this.onUpdateCallback=bd,this}setSelectAllWhenFocusEnable(t){return void 0===t&&(t=!0),this.selectAllWhenFocus=t,this}setRequestCursorPosition(t){return this.isOpened?(this.requestCursorPosition=t,this):this}};const Sd=Phaser.Utils.Objects.GetValue,Pd=["inputType","onOpen","clickOutSideTarget","onFocus","onClose","onBlur","onUpdate","enterClose","readOnly","maxLength","minLength","selectAll"];var Td=function(t,e){if(t&&"number"!=typeof t){if(t.hasOwnProperty(e))return!0;if(-1!==e.indexOf(".")){for(var i=e.split("."),s=t,r=0;r0))return e;return null}(e);if(i){e.setScrollFactor(0).setOrigin(.5);var s=t.sys.scale.gameSize,r=s.width,n=s.height,a=1/i.zoom,o=r/2,h=n/2,l=r*a,d=n*a;e.x===o&&e.y===h||e.setPosition(o,h),e.width===l&&e.height===d||e.setSize(l,d)}}}const Ed=Phaser.GameObjects.Zone;let _d=class extends Ed{constructor(t){super(t,0,0,2,2),this.fullWindow=new Md(this)}};var Rd=function(t,e,i,s){if(void 0===i&&(i="."),void 0===s&&(s={}),!t)return s;if(e in t)return Object.assign(s,t[e]);for(var r in e+=i,t)r.startsWith(e)&&(s[r.replace(e,"")]=t[r]);return s},Ld=function(){var t=this.scene.input.keyboard;this.textEdit.on("open",(function(){t.on("keydown-UP",this.cursorMoveUp,this).on("keydown-DOWN",this.cursorMoveDown,this)}),this).on("close",(function(){t.off("keydown-UP",this.cursorMoveUp,this).off("keydown-DOWN",this.cursorMoveDown,this)}),this)},Bd=function(t,e,i){if(void 0===i&&(i={}),Array.isArray(e))for(var s=0,r=e.length;st.length?i:t})),a.value=t.join(e)}else a.value=t.join(i.slice(o,o+a.count));o+=a.count,a.added||(h+=a.count)}}let l=e[a-1];return a>1&&"string"==typeof l.value&&(l.added||l.removed)&&t.equals("",l.value)&&(e[a-2].value+=l.value,e.pop()),e}Ad.prototype={diff(t,e,i={}){let s=i.callback;"function"==typeof i&&(s=i,i={}),this.options=i;let r=this;function n(t){return s?(setTimeout((function(){s(void 0,t)}),0),!0):t}t=this.castInput(t),e=this.castInput(e),t=this.removeEmpty(this.tokenize(t));let a=(e=this.removeEmpty(this.tokenize(e))).length,o=t.length,h=1,l=a+o;i.maxEditLength&&(l=Math.min(l,i.maxEditLength));let d=[{newPos:-1,components:[]}],c=this.extractCommon(d[0],e,t,0);if(d[0].newPos+1>=a&&c+1>=o)return n([{value:this.join(e),count:e.length}]);function u(){for(let s=-1*h;s<=h;s+=2){let h,l=d[s-1],c=d[s+1],u=(c?c.newPos:0)-s;l&&(d[s-1]=void 0);let p=l&&l.newPos+1=a&&u+1>=o)return n(zd(r,h.components,e,t,r.useLongestToken));d[s]=h}else d[s]=void 0}var i;h++}if(s)!function t(){setTimeout((function(){if(h>l)return s();u()||t()}),0)}();else for(;h<=l;){let t=u();if(t)return t}},pushComponent(t,e,i){let s=t[t.length-1];s&&s.added===e&&s.removed===i?t[t.length-1]={count:s.count+1,added:e,removed:i}:t.push({count:1,added:e,removed:i})},extractCommon(t,e,i,s){let r=e.length,n=i.length,a=t.newPos,o=a-s,h=0;for(;a+1t,tokenize:t=>t.split(""),join:t=>t.join("")};const Fd=new Ad,Yd=/^[a-zA-Z\u{C0}-\u{FF}\u{D8}-\u{F6}\u{F8}-\u{2C6}\u{2C8}-\u{2D7}\u{2DE}-\u{2FF}\u{1E00}-\u{1EFF}]+$/u,Xd=/\S/,Wd=new Ad;Wd.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!Xd.test(t)&&!Xd.test(e)},Wd.tokenize=function(t){let e=t.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/);for(let t=0;tvoid 0===i?e:i}=this.options;return"string"==typeof t?t:JSON.stringify(Ud(t,null,null,i),i," ")},Hd.equals=function(t,e){return Ad.prototype.equals.call(Hd,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};const Nd=new Ad;Nd.tokenize=function(t){return t.slice()},Nd.join=Nd.removeEmpty=function(t){return t};const $d=Phaser.Utils.Array.Remove;var Kd=function(t,e){var i=t.text;if(e!==i){if(null==i&&(i=""),$d(t.children,t.lastInsertCursor),""===e)t.removeChildren();else for(var s=(h=i,l=e,Fd.diff(h,l,d)),r=0,n=0,a=s.length;nr)i+=a;else{if(s!==r)break;i+=Math.min(e.position,a)}}return i},tc={cursorMoveLeft(){if(!this.isOpened)return this;var t=qd(this.cursorPosition-1,0,this.inputText.length);return this.setCursorPosition(t),this},cursorMoveRight(){if(!this.isOpened)return this;var t=qd(this.cursorPosition+1,0,this.inputText.length);return this.setCursorPosition(t),this},cursorMoveUp(){if(!this.isOpened)return this;var t=Zd(this.characterCountOfLines,this.cursorPosition);t.lineIndex-=1;var e=qd(Qd(this.characterCountOfLines,t),0,this.inputText.length);return this.setCursorPosition(e),this},cursorMoveDown(){if(!this.isOpened)return this;var t=Zd(this.characterCountOfLines,this.cursorPosition);t.lineIndex+=1;var e=qd(Qd(this.characterCountOfLines,t),0,this.inputText.length);return this.setCursorPosition(e),this}};const ec=Phaser.Utils.Objects.IsPlainObject;class ic extends hn{constructor(t,e,i,s,r,n){ec(e)?n=e:ec(s)&&(n=s),void 0===n&&(n={}),function(t,e){var i=!e.textArea;if(Td(e,"wrap.vAlign")||P(e,"wrap.vAlign",s=i?"center":"top"),Td(e,"wrap.wrapMode")||P(e,"wrap.wrapMode","char"),Td(e,"wrap.maxLines")||P(e,"wrap.maxLines",s=i?1:void 0),i&&P(e,"wrap.wrapWidth",1/0),Td(e,"wrap.useDefaultTextHeight")||P(e,"wrap.useDefaultTextHeight",!0),e.edit||(e.edit={}),!Td(e.edit,"inputType")){var s=i?"text":"textarea";P(e.edit,"inputType",s)}if(!0===e.clickOutSideTarget){var r=new _d(t);t.add.existing(r),e.clickOutSideTarget=r}}(t,n);var a=n.text;a&&delete n.text;var o=Rd(n.background,"focus"),h=Rd(n.style,"cursor");super(t,e,i,s,r,n),this.type="rexCanvasInput",this.contentWidth=void 0,this.contentHeight=void 0,this.lineHeight=void 0,this.linesCount=void 0,this.characterCountOfLines=[],this._text,this.textEdit=function(t,e){var i=Sd(e,"edit");return void 0===i&&(i={}),id(e,i,Pd),new wd(t,i)}(this,n),Ld.call(this),n.focusStyle&&Object.assign(o,n.focusStyle),jd.call(this,o),n.cursorStyle&&Object.assign(h,n.cursorStyle),Dd.call(this,h);var l=n.onAddChar;l&&this.on("addchar",l);var d=n.onCursorOut;d&&this.on("cursorout",d);var c=n.onCursorIn;c&&this.on("cursorin",c);var u,p=n.onMoveCursor;p&&this.on("movecursor",p),this.setParseTextCallback(n.parseTextCallback),this.lastInsertCursor=((u=this.createCharChild("|")).text="",u),a||(a=""),this.setText(a)}addChild(t,e){if(super.addChild(t,e),Array.isArray(t))for(var i=t,s=0,r=i.length;s0,a=0,o=e.length;a0;this.dirty=this.dirty||this._radiusTL!==t||this._convexTL!==e,this._convexTL=e,this._radiusTL=Math.abs(t)}get radiusTR(){return this._radiusTR}set radiusTR(t){var e=t>0;this.dirty=this.dirty||this._radiusTR!==t||this._convexTR!==e,this._convexTR=e,this._radiusTR=Math.abs(t)}get radiusBL(){return this._radiusBL}set radiusBL(t){var e=t>0;this.dirty=this.dirty||this._radiusBL!==t||this._convexBL!==e,this._convexBL=e,this._radiusBL=Math.abs(t)}get radiusBR(){return this._radiusBR}set radiusBR(t){var e=t>0;this.dirty=this.dirty||this._radiusBR!==t||this._convexBR!==e,this._convexBR=e,this._radiusBR=Math.abs(t)}get radius(){return Math.max(this.radiusTL,this.radiusTR,this.radiusBL,this.radiusBR)}set radius(t){"number"==typeof t?(this.radiusTL=t,this.radiusTR=t,this.radiusBL=t,this.radiusBR=t):(this.radiusTL=$c(t,"tl",0),this.radiusTR=$c(t,"tr",0),this.radiusBL=$c(t,"bl",0),this.radiusBR=$c(t,"br",0))}setRadius(t){return void 0===t&&(t=0),this.radius=t,this}get iterations(){return this._iterations}set iterations(t){this.dirty=this.dirty||this._iterations!==t,this._iterations=t}setIterations(t){return this.iterations=t,this}updateData(){var t=this.pathData;t.length=0;var e,i=this.width,s=this.height,r=this.iterations+1;return(e=this.radiusTL)>0?this._convexTL?Rt(e,e,e,e,180,270,!1,r,t):Rt(0,0,e,e,90,0,!0,r,t):Et(0,0,t),(e=this.radiusTR)>0?this._convexTR?Rt(i-e,e,e,e,270,360,!1,r,t):Rt(i,0,e,e,180,90,!0,r,t):Et(i,0,t),(e=this.radiusBR)>0?this._convexBR?Rt(i-e,s-e,e,e,0,90,!1,r,t):Rt(i,s,e,e,270,180,!0,r,t):Et(i,s,t),(e=this.radiusBL)>0?this._convexBL?Rt(e,s-e,e,e,90,180,!1,r,t):Rt(0,s,e,e,360,270,!0,r,t):Et(0,s,t),t.push(t[0],t[1]),Ec(this.x,this.y,t),super.updateData(),this}}const Jc=Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlpha;var qc={buildShapes(){this.addShape((new Kc).setName("box")).addShape((new Uc).setName("checker"))},updateShapes(){var t=this.width/2,e=this.height/2,i=Math.min(t,e),s=2*i,r=t-i,n=e-i,a=this.boxLineWidth,o=Math.max(s/10,2),h=this.getShape("box"),l=this.getShape("checker");if(this.isSizeChanged){var d=s*(1-this.boxSize)/2,c=a/2,u=s*this.boxSize-a;h.setTopLeftPosition(r+c+d,n+c+d).setSize(u,u),this.isCircleShape?h.setRadius(u/2):h.setRadius(0),d=s*(1-this.checkerSize)/2;var p=s*this.checkerSize/4,g=1*p,v=2*p,f=3*p;l.startAt(g,v).lineTo(v,f).lineTo(f,g).offset(r+d,n+d).end()}this.checked?(h.fillStyle(this.boxFillColor,this.boxFillAlpha).lineStyle(a,this.boxStrokeColor,this.boxStrokeAlpha),l.lineStyle(o,this.checkerColor)):(h.fillStyle(this.uncheckedBoxFillColor,this.uncheckedBoxFillAlpha).lineStyle(a,this.uncheckedBoxStrokeColor,this.uncheckedBoxStrokeAlpha),l.lineStyle()),this.checked&&l.setDisplayPathSegment(this.checkerAnimProgress)}};const Zc=Phaser.Utils.Objects.GetValue,Qc=Phaser.Math.Linear;class tu extends Ja{constructor(t,e){super(t,e),this.resetFromJSON(),this.boot()}start(t){if(this.timer.isRunning)return this;var e=this.target;this.propertyKey=Zc(t,"key","value");var i=e[this.propertyKey];return this.fromValue=Zc(t,"from",i),this.toValue=Zc(t,"to",i),this.setEase(Zc(t,"ease",this.ease)),this.setDuration(Zc(t,"duration",this.duration)),this.setRepeat(Zc(t,"repeat",0)),this.setDelay(Zc(t,"delay",0)),this.setRepeatDelay(Zc(t,"repeatDelay",0)),this.timer.setDuration(this.duration).setRepeat(this.repeat).setDelay(this.delay).setRepeatDelay(this.repeatDelay),e[this.propertyKey]=this.fromValue,super.start(),this}updateTarget(t,e){var i=e.t;i=this.easeFn(i),t[this.propertyKey]=Qc(this.fromValue,this.toValue,i)}}var eu={setCheckerAnimationDuration(t){return void 0===t&&(t=0),this.checkerAnimDuration=t,this},playCheckerAnimation(){return void 0===this.checkerAnimProgressTask&&(this.checkerAnimProgressTask=new tu(this,{eventEmitter:null})),this.checkerAnimProgressTask.restart({key:"checkerAnimProgress",from:0,to:1,duration:this.checkerAnimDuration}),this},stopCheckerAnimation(){return void 0===this.checkerAnimProgressTask||this.checkerAnimProgressTask.stop(),this}},iu={};Object.assign(iu,gc,vc,qc,eu);const su=23730,ru=Phaser.Utils.Objects.GetValue,nu=Phaser.Utils.Objects.IsPlainObject;class au extends pc{constructor(t,e,i,s,r,n,a){nu(e)?(e=ru(a=e,"x",0),i=ru(a,"y",0),s=ru(a,"width",2),r=ru(a,"height",2),n=ru(a,"color",su)):nu(n)&&(n=ru(a=n,"color",su)),super(t,e,i,s,r),this.type="rexCheckbox",void 0===n&&(n=su),this.setBoxShape(ru(a,"circleBox",!1)),this.setBoxFillStyle(n,ru(a,"boxFillAlpha",1)),this.setUncheckedBoxFillStyle(ru(a,"uncheckedColor",null),ru(a,"uncheckedBoxFillAlpha",1)),this.setBoxStrokeStyle(ru(a,"boxLineWidth",4),ru(a,"boxStrokeColor",n),ru(a,"boxStrokeAlpha",1)),this.setUncheckedBoxStrokeStyle(this.boxLineWidth,ru(a,"uncheckedBoxStrokeColor",this.boxStrokeColor),ru(a,"uncheckedBoxStrokeAlpha",this.boxStrokeAlpha)),this.setCheckerStyle(ru(a,"checkerColor",16777215),ru(a,"checkerAlpha",1)),this.setBoxSize(ru(a,"boxSize",1)),this.setCheckerSize(ru(a,"checkerSize",1)),this.setCheckerAnimationDuration(ru(a,"animationDuration",150)),this.buildShapes();var o=ru(a,"checked");void 0===o&&(o=ru(a,"value",!1)),this.setValue(o)}get value(){return this._value}set value(t){t=!!t,this._value!==t&&(this.dirty=!0,this._value=t,t?this.playCheckerAnimation():this.stopCheckerAnimation(),this.emit("valuechange",t))}setValue(t){return this.value=t,this}toggleValue(){return this.setValue(!this.value),this}get checked(){return this.value}set checked(t){this.value=t}setChecked(t){return void 0===t&&(t=!0),this.setValue(t),this}toggleChecked(){return this.toggleValue(),this}get checkerAnimProgress(){return this._checkerAnimProgress}set checkerAnimProgress(t){this._checkerAnimProgress!==t&&(this._checkerAnimProgress=t,this.dirty=!0)}}Object.assign(au.prototype,iu);const ou=Phaser.Utils.Objects.GetValue;class hu extends Ra{constructor(t,e){super(t,e),this._enable=void 0,t.setInteractive(ou(e,"inputConfig",void 0)),this.resetFromJSON(e),this.boot()}resetFromJSON(t){return this.pointer=void 0,this.lastClickTime=void 0,this.isDown=!1,this.isOver=!1,this.setEnable(ou(t,"enable",!0)),this.setMode(ou(t,"mode",1)),this.setClickInterval(ou(t,"clickInterval",100)),this.setDragThreshold(ou(t,"threshold",void 0)),this}boot(){var t=this.parent;t.on("pointerdown",this.onPress,this),t.on("pointerup",this.onRelease,this),t.on("pointerout",this.onPointOut,this),t.on("pointermove",this.onMove,this),t.on("pointerover",this.onOver,this),t.on("pointerout",this.onOut,this)}shutdown(t){this.isShutdown||(this.pointer=null,super.shutdown(t))}get enable(){return this._enable}set enable(t){if(this._enable!==t){t||this.cancel(),this._enable=t;var e=t?"enable":"disable";this.emit(e,this,this.parent)}}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}toggleEnable(){return this.setEnable(!this.enable),this}setMode(t){return"string"==typeof t&&(t=lu[t]),this.mode=t,this}setClickInterval(t){return this.clickInterval=t,this}setDragThreshold(t){return this.dragThreshold=t,this}onPress(t,e,i,s){void 0===this.pointer&&(this.pointer=t,this.isDown=!0,this.emit("down",this,this.parent,t,s),0===this.mode&&this.click(t.downTime,t,s))}onRelease(t,e,i,s){this.pointer===t&&(this.isDown=!1,this.emit("up",this,this.parent,t,s),1===this.mode&&this.click(t.upTime,t,s),this.pointer=void 0)}onPointOut(t,e){this.pointer===t&&this.cancel()}onMove(t,e,i,s){this.pointer===t&&void 0!==this.dragThreshold&&1===this.mode&&t.getDistance()>=this.dragThreshold&&this.cancel()}onOver(t,e,i,s){return this.enable?(this.isOver=!0,this.emit("over",this,this.parent,t,s),this):this}onOut(t,e){return this.enable?(this.isOver=!1,this.emit("out",this,this.parent,t,e),this):this}click(t,e,i){if(!this.enable)return this;if(void 0===t)return this.emit("click",this,this.parent,e,i),this;this.pointer=void 0;var s=this.lastClickTime;return void 0!==s&&t-s<=this.clickInterval||(this.lastClickTime=t,this.emit("click",this,this.parent,e,i)),this}cancel(){return this.pointer=void 0,this}}const lu={press:0,pointerdown:0,release:1,pointerup:1},du=Phaser.Utils.Objects.GetValue,cu=Phaser.Utils.Objects.IsPlainObject;class uu extends au{constructor(t,e,i,s,r,n,a){cu(e)?(e=du(a=e,"x",0),i=du(a,"y",0),s=du(a,"width",2),r=du(a,"height",2),n=du(a,"color",su)):cu(n)&&(n=du(a=n,"color",su)),super(t,e,i,s,r,n,a),this._click=new hu(this,du(a,"click")),this._click.on("click",(function(){this.toggleValue()}),this),this.setReadOnly(du(a,"readOnly",!1))}get readOnly(){return!this._click.enable}set readOnly(t){this._click.enable=!t}setReadOnly(t){return void 0===t&&(t=!0),this.readOnly=t,this}}t.register("checkbox",(function(t,e,i,s,r,n){var a=new uu(this.scene,t,e,i,s,r,n);return this.scene.add.existing(a),a})),P(window,"RexPlugins.UI.Checkbox",uu);var pu={setTrackFillStyle(t,e){return void 0===e&&(e=1),this.dirty=this.dirty||this.trackFillColor!==t||this.trackFillAlpha!==e,this.trackFillColor=t,this.trackFillAlpha=e,this},setFalseValueTrackFillStyle(t,e){return void 0===e&&(e=1),this.dirty=this.dirty||this.falseValueTrackColor!==t||this.uncheckedTrackFillAlpha!==e,this.falseValueTrackColor=t,this.falseValueTrackFillAlpha=e,this},setThumbStyle(t,e){return void 0===e&&(e=1),this.dirty=this.dirty||this.thumbColor!==t||this.checkAlpha!==e,this.thumbColor=t,this.thumbAlpha=e,this}},gu={setTrackSize(t,e){return this.dirty=this.dirty||this.trackWidth!==t||this.trackHeight!==e,this.trackWidth=t,this.trackHeight=e,this},setTrackRadius(t){return this.dirty=this.dirty||this.trackRadius!==t,this.trackRadius=t,this},setThumbSize(t,e){return void 0===e&&(e=t),this.dirty=this.dirty||this.thumbWidth!==t||this.thumbHeight!==e,this.thumbWidth=t,this.thumbHeight=e,this},setThumbRadius(t){return this.dirty=this.dirty||this.thumbRadius!==t,this.thumbRadius=t,this}},vu={setThumbPosition(t,e){return void 0===e&&(e=1-t),this.thumbLeftX=t,this.thumbRightX=e,this},setRTL(t){return void 0===t&&(t=!0),this.rtl=t,this}},fu=function(t,e,i){return(e-t)*i+t};const mu=Phaser.Math.Linear;var yu={buildShapes(){this.addShape((new Kc).setName("track")).addShape((new Kc).setName("thumb"))},updateShapes(){var t=this.width,e=this.height,i=this.value?this.toggleAnimProgress:1-this.toggleAnimProgress,s=this.getShape("track");if(this.isSizeChanged){var r=t*this.trackWidth,n=e*this.trackHeight,a=(t-r)/2,o=(e-n)/2,h=e*this.trackRadius;s.setTopLeftPosition(a,o).setSize(r,n).setRadius(h)}var l,d,c,u=(l=this.falseValueTrackColor,d=this.trackFillColor,c=i,(255&fu(mn(l),mn(d),c))<<16|(255&fu(yn(l),yn(d),c))<<8|255&fu(bn(l),bn(d),c)),p=mu(this.falseValueTrackFillAlpha,this.trackFillAlpha,i);s.fillStyle(u,p);var g=this.getShape("thumb");if(this.isSizeChanged){var v=t*this.thumbWidth,f=e*this.thumbHeight,m=e*this.thumbRadius;g.setSize(v,f).setRadius(m)}var y=mu(this.thumbLeftX,this.thumbRightX,i)*t;this.rtl&&(y=t-y);var b=e/2;g.setCenterPosition(y,b),g.fillStyle(this.thumbColor,this.thumbAlpha)}},bu={setToggleAnimationDuration(t){return void 0===t&&(t=0),this.toggleAnimDuration=t,this},playToggleAnimation(){return void 0===this.toggleAnimProgressTask&&(this.toggleAnimProgressTask=new tu(this,{eventEmitter:null})),this.toggleAnimProgressTask.restart({key:"toggleAnimProgress",from:0,to:1,duration:this.toggleAnimDuration}),this},stopToggleAnimation(){return void 0===this.toggleAnimProgressTask||this.toggleAnimProgressTask.stop(),this}},xu={};Object.assign(xu,pu,gu,vu,yu,bu);const Cu=Phaser.Utils.Objects.GetValue,ku=Phaser.Utils.Objects.IsPlainObject,wu=23730;class Su extends pc{constructor(t,e,i,s,r,n,a){ku(e)?(e=Cu(a=e,"x",0),i=Cu(a,"y",0),s=Cu(a,"width",2),r=Cu(a,"height",2),n=Cu(a,"color",wu)):ku(n)&&(n=Cu(a=n,"color",wu)),super(t,e,i,s,r),this.type="rexToggleSwitch",void 0===n&&(n=wu),this.setTrackFillStyle(n,Cu(a,"trackFillAlpha",1)),this.setFalseValueTrackFillStyle(Cu(a,"falseValueTrackColor",function(t){var e=.3*mn(t)+.59*yn(t)+.11*bn(t);return(255&e)<<16|(255&e)<<8|255&e}(n)),Cu(a,"falseValueTrackFillAlpha",1)),this.setThumbStyle(Cu(a,"thumbColor",16777215),Cu(a,"thumbAlpha",1)),this.setTrackSize(Cu(a,"trackWidth",.9),Cu(a,"trackHeight",.5)),this.setTrackRadius(Cu(a,"trackRadius",.5*this.trackHeight));var o=Cu(a,"thumbHeight",void 0),h=Cu(a,"thumbWidth",o);void 0===h&&(h=.9*this.trackHeight),this.setThumbSize(h,o),this.setThumbRadius(Cu(a,"thumbRadius",.5*this.thumbHeight)),this.setThumbPosition(Cu(a,"thumbLeft",.3),Cu(a,"thumbRight",void 0)),this.setRTL(Cu(a,"rtl",!1)),this.setToggleAnimationDuration(Cu(a,"animationDuration",150)),this.buildShapes(),this.setValue(Cu(a,"value",!1),0)}get value(){return this._value}set value(t){t=!!t,this._value!==t&&(this.dirty=!0,this._value=t,this.playToggleAnimation(),this.emit("valuechange",t))}setValue(t,e){void 0===e&&(e=this.toggleAnimDuration);var i=this.toggleAnimDuration;return this.toggleAnimDuration=e,this.value=t,this.toggleAnimDuration=i,this}toggleValue(t){return this.setValue(!this.value,t),this}get toggleAnimProgress(){return this._toggleAnimProgress}set toggleAnimProgress(t){this._toggleAnimProgress!==t&&(this._toggleAnimProgress=t,this.dirty=!0)}}Object.assign(Su.prototype,xu);const Pu=Phaser.Utils.Objects.GetValue;class Tu extends Su{constructor(t,e,i,s,r,n,a){super(t,e,i,s,r,n,a),this._click=new hu(this,Pu(a,"click")),this._click.on("click",(function(){this.toggleValue()}),this),this.setReadOnly(Pu(a,"readOnly",!1))}get readOnly(){return!this._click.enable}set readOnly(t){this._click.enable=!t}setReadOnly(t){return void 0===t&&(t=!0),this.readOnly=t,this}}t.register("toggleSwitch",(function(t,e,i,s,r,n){var a=new Tu(this.scene,t,e,i,s,r,n);return this.scene.add.existing(a),a})),P(window,"RexPlugins.UI.ToggleSwitch",Tu);var Ou={loadFromURL(t,e){var i=this,s=new Image;return s.onload=function(){i.width!==s.width||i.height!==s.height?i.resize(s.width,s.height):i.clear(),i.context.drawImage(s,0,0),i.updateTexture(),e&&e(),s.onload=null,s.src="",s.remove()},s.src=t,this},loadFromURLPromise(t){var e=this;return new Promise((function(i,s){e.loadFromURL(t,i)}))},loadFromFile(t,e){var i=URL.createObjectURL(t);return this.loadFromURL(i,(function(){URL.revokeObjectURL(i),e&&e()})),this},loadFromFilePromise(t){var e=this;return new Promise((function(i,s){e.loadFromFile(t,i)}))}};class Mu extends Nt{}Object.assign(Mu.prototype,Ou),t.register("canvas",(function(t,e,i,s){var r=new Mu(this.scene,t,e,i,s);return this.scene.add.existing(r),r})),P(window,"RexPlugins.UI.Canvas",Mu);const Eu=Phaser.Utils.Objects.GetValue;class _u extends Nt{constructor(t,e,i,s,r,n){super(t,e,i),this.type="rexCircleMaskImage",this.setTexture(s,r,n)}setTexture(t,e,i){"object"==typeof e&&(i=e,e=void 0),"string"==typeof i&&(i={maskType:i});var s=Eu(i,"maskType",0),r=Eu(i,"backgroundColor",void 0),n=Eu(i,"strokeColor",void 0),a=Eu(i,"strokeWidth",null!=n?10:0);if(void 0===s?s=0:"string"==typeof s&&(s=Ru[s]),this._textureKey=t,this._frameName=e,null===s)return this.loadTexture(t,e),this.dirty=!0,this;var o=this.scene.sys.textures.getFrame(t,e);if(!o)return this;o.cutWidth!==this.width||o.cutHeight!==this.height?this.setCanvasSize(o.cutWidth,o.cutHeight):this.clear();var h=this.canvas,l=this.context,d=h.width,c=h.height;null!=r&&(l.fillStyle=r,l.fillRect(0,0,d,c)),l.save(),l.beginPath();var u=a/2;switch(s){case 1:var p=(m=Math.floor(d/2))-u,g=(y=Math.floor(c/2))-u;l.ellipse(m,y,p,g,0,0,2*Math.PI);break;case 2:var v=Eu(i,"radius",0),f=Eu(i,"iteration",void 0);Zt(l,u,u,d-a,c-a,v,f);break;default:var m=Math.floor(d/2),y=Math.floor(c/2),b=Math.min(m,y)-u;l.arc(m,y,b,0,2*Math.PI)}return null!=n&&(l.strokeStyle=n,l.lineWidth=a,l.stroke()),l.clip(),this.loadTexture(t,e),l.restore(),this.dirty=!0,this}resize(t,e){return this.setDisplaySize(t,e),this}}const Ru={circle:0,ellipse:1,roundRectangle:2};t.register("circleMaskImage",(function(t,e,i,s,r){var n=new _u(this.scene,t,e,i,s,r);return this.scene.add.existing(n),n})),P(window,"RexPlugins.UI.CircleMaskImage",_u);const Lu=Phaser.Utils.Objects.GetValue;class Bu extends Nt{constructor(t,e,i,s,r,n){super(t,e,i),this.type="rexAlphaMaskImage",this.maskFrame=null,this.setTexture(s,r,n)}setTexture(t,e,i){"object"==typeof e&&(i=e,e=void 0),"string"==typeof i&&(i={mask:{key:i}});var s=Lu(i,"mask.key"),r=Lu(i,"mask.frame"),n=Lu(i,"mask.invertAlpha",!1),a=Lu(i,"mask.scale"),o=Lu(i,"backgroundColor");if(s){this._maskKey=s,this._maskFrame=r,this._maskScale=a;var h=s?this.scene.sys.textures.get(s):null;this.maskFrame=h?h.get(r):null}this._textureKey=t,this._frameName=e;var l=this.maskFrame;if(null===l)return this.loadTexture(t,e),this.dirty=!0,this;var d=null!=o;this.loadTexture(t,e);var c,u,p=this.canvas,g=this.context,v=p.width,f=p.height;g.save(),g.globalCompositeOperation=n?"destination-out":"destination-in",null!=this._maskScale?(c=l.cutWidth*this._maskScale,u=l.cutHeight*this._maskScale):(c=v,u=f);var m=(v-c)/2,y=(f-u)/2;return this.drawFrame(this._maskKey,this._maskFrame,m,y,c,u),g.restore(),d&&(g.save(),g.globalCompositeOperation="destination-over",g.fillStyle=o,g.fillRect(0,0,v,f),g.restore()),this.dirty=!0,this}resize(t,e){return this.setDisplaySize(t,e),this}}t.register("alphaMaskImage",(function(t,e,i,s,r){var n=new Bu(this.scene,t,e,i,s,r);return this.scene.add.existing(n),n})),P(window,"RexPlugins.UI.AlphaMaskImage",Bu);const Iu=Phaser.Math.Linear,Du=Phaser.Math.Percent;var ju={setValue(t,e,i){return null==t||(void 0!==e&&(t=Du(t,e,i)),this.value=t),this},addValue(t,e,i){return void 0!==e&&(t=Du(t,e,i)),this.value+=t,this},getValue(t,e){var i=this.value;return void 0!==t&&(i=Iu(t,e,i)),i}};const Au=Phaser.Math.Percent;var zu={setEaseValuePropName:function(t){return this.easeValuePropName=t,this},setEaseValueDuration:function(t){return this.easeValueDuration=t,this},setEaseValueFunction:function(t){return this.easeFunction=t,this},stopEaseValue:function(){return this.easeValueTask&&this.easeValueTask.stop(),this},easeValueTo:function(t,e,i){return null==t||(void 0!==e&&(t=Au(t,e,i)),void 0===this.easeValueTask&&(this.easeValueTask=new tu(this,{eventEmitter:null})),this.easeValueTask.restart({key:this.easeValuePropName,to:t,duration:this.easeValueDuration,ease:this.easeFunction})),this},easeValueRepeat:function(t,e,i,s){return void 0===i&&(i=-1),void 0===s&&(s=0),void 0===this.easeValueTask&&(this.easeValueTask=new tu(this,{eventEmitter:null})),this.easeValueTask.restart({key:this.easeValuePropName,from:t,to:e,duration:this.easeValueDuration,ease:this.easeFunction,repeat:i,repeatDelay:s}),this}};const Fu=Phaser.Utils.Objects.GetValue,Yu=Phaser.Math.Clamp;function Xu(t){class e extends t{bootProgressBase(t){this.eventEmitter=Fu(t,"eventEmitter",this);var e=Fu(t,"valuechangeCallback",null);if(null!==e){var i=Fu(t,"valuechangeCallbackScope",void 0);this.eventEmitter.on("valuechange",e,i)}return this.setEaseValuePropName("value").setEaseValueDuration(Fu(t,"easeValue.duration",0)).setEaseValueFunction(Fu(t,"easeValue.ease","Linear")),this}get value(){return this._value}set value(t){t=Yu(t,0,1);var e=this._value,i=e!=t;this.dirty=this.dirty||i,this._value=t,i&&this.eventEmitter.emit("valuechange",this._value,e,this.eventEmitter)}}return Object.assign(e.prototype,ju,zu),e}const Wu=Phaser.Math.RadToDeg,Vu=Phaser.Math.DegToRad;var Gu=function(t,e,i,s,r,n,a,o){var h=360===Math.abs(a-n),l=Vu(n),d=Vu(a),c=Math.cos(l),u=Math.sin(l),p=Math.cos(d),g=Math.sin(d);return t.startAt(e+c*s,i+u*s),t.arc(e,i,s,n,a,o),h&&0===r||(t.lineTo(e+p*r,i+g*r),r>0&&t.arc(e,i,r,a,n,!o)),t.close(),t},Hu={buildShapes(){var t=this.iterations;this.addShape((new Uc).setIterations(t).setName("track")).addShape((new Uc).setIterations(t).setName("bar")).addShape((new kc).setIterations(t).setName("center"))},updateShapes(){var t=this.radius,e=this.thickness*this.radius,i=this.radius,s=i-e,r=this.getShape("track");null!=this.trackColor&&this.thickness>0?(r.fillStyle(this.trackColor),Gu(r,t,t,i,s,0,360,!1)):r.reset();var n,a,o,h=this.getShape("bar");null!=this.barColor&&this.thickness>0?(1===this.value?(n=!1,a=0,o=360):(n=this.anticlockwise,a=Wu(this.startAngle),o=360*(n?1-this.value:this.value)+a),h.fillStyle(this.barColor),Gu(h,t,t,i+1,s-1,a,o,!1)):h.reset();var l=this.getShape("center");this.centerColor&&s>0?l.setCenterPosition(t,t).setRadius(s).fillStyle(this.centerColor):l.reset()}};const Uu=Phaser.Utils.Objects.GetValue,Nu=Phaser.Utils.Objects.IsPlainObject,$u=Phaser.Math.Clamp,Ku=Phaser.Math.DegToRad(270);let Ju=class extends(Xu(pc)){constructor(t,e,i,s,r,n,a){Nu(e)&&(e=Uu(a=e,"x",0),i=Uu(a,"y",0),s=Uu(a,"radius",1),r=Uu(a,"barColor",void 0),n=Uu(a,"value",0)),void 0===s&&(s=1);var o=2*s;super(t,e,i,o,o),this.type="rexCircularProgress",this.bootProgressBase(a),this.setRadius(s),this.setTrackColor(Uu(a,"trackColor",void 0)),this.setBarColor(r),this.setCenterColor(Uu(a,"centerColor",void 0)),this.setThickness(Uu(a,"thickness",.2)),this.setStartAngle(Uu(a,"startAngle",Ku)),this.setAnticlockwise(Uu(a,"anticlockwise",!1)),this.iterations=Uu(a,"iterations",128),this.buildShapes(),this.setValue(n)}resize(t,e){return(t=Math.floor(Math.min(t,e)))===this.width||(super.resize(t,t),this.setRadius(t/2)),this}get radius(){return this._radius}set radius(t){this.dirty=this.dirty||this._radius!=t,this._radius=t;var e=2*t;this.resize(e,e)}setRadius(t){return this.radius=t,this}get trackColor(){return this._trackColor}set trackColor(t){this.dirty=this.dirty||this._trackColor!=t,this._trackColor=t}setTrackColor(t){return this.trackColor=t,this}get barColor(){return this._barColor}set barColor(t){this.dirty=this.dirty||this._barColor!=t,this._barColor=t}setBarColor(t){return this.barColor=t,this}get startAngle(){return this._startAngle}set startAngle(t){this.dirty=this.dirty||this._startAngle!=t,this._startAngle=t}setStartAngle(t){return this.startAngle=t,this}get anticlockwise(){return this._anticlockwise}set anticlockwise(t){this.dirty=this.dirty||this._anticlockwise!=t,this._anticlockwise=t}setAnticlockwise(t){return void 0===t&&(t=!0),this.anticlockwise=t,this}get thickness(){return this._thickness}set thickness(t){t=$u(t,0,1),this.dirty=this.dirty||this._thickness!=t,this._thickness=t}setThickness(t){return this.thickness=t,this}get centerColor(){return this._centerColor}set centerColor(t){this.dirty=this.dirty||this._centerColor!=t,this._centerColor=t}setCenterColor(t){return this.centerColor=t,this}};Object.assign(Ju.prototype,Hu),t.register("circularProgress",(function(t,e,i,s,r,n){var a=new Ju(this.scene,t,e,i,s,r,n);return this.scene.add.existing(a),a})),P(window,"RexPlugins.UI.CircularProgress",Ju);var qu=function(t,e,i,s,r,n,a,o,h,l,d,c){void 0===l&&(l=0),void 0===d&&(d=2*Math.PI),void 0===c&&(c=!1),e.beginPath(),e.ellipse(i,s,r,n,0,l,d,c),null!=a&&(e.fillStyle=a,e.fill()),null!=o&&(e.strokeStyle=o,e.lineWidth=h,e.stroke())};const Zu=Phaser.Math.PI2;var Qu=function(){var t,e=this.radius,i=this.thickness*this.radius,s=this.radius-i/2,r=this.radius-i,n=(this.canvas,this.context),a=this.anticlockwise,o=this.startAngle,h=this.endAngle,l=this._deltaAngle;if(this.trackColor&&i>0&&(n.save(),qu(0,n,e,e,s,s,void 0,this.trackColor,i,o,h,a),n.restore()),this.barColor&&s>0){var d,c;if(d=this.value>=1?h:a?(o-l*this.value+Zu)%Zu:(o+l*this.value)%Zu,n.save(),this.barColor2){var u=e+s*Math.cos(o),p=e+s*Math.sin(o),g=e+s*Math.cos(d),v=e+s*Math.sin(d),f=n.createLinearGradient(u,p,g,v);f.addColorStop(0,this.barColor2),f.addColorStop(1,this.barColor),c=f}else c=this.barColor;qu(0,n,e,e,s,s,void 0,c,i,o,d,a),n.restore()}this.centerColor&&r>0&&(this.centerColor2?((t=this.context.createRadialGradient(e,e,0,e,e,r)).addColorStop(0,this.centerColor),t.addColorStop(1,this.centerColor2)):t=this.centerColor,n.save(),qu(0,n,e,e,r,r,t),n.restore()),this.textFormatCallback&&(this.textColor||this.textStrokeColor)&&(n.save(),function(t,e,i,s,r,n,a,o,h,l,d){void 0===h&&null!=o&&(h=2),void 0===l&&(l="start"),void 0===d&&(d="alphabetic"),e.font=n,e.textAlign=l,e.textBaseline=d,e.fillStyle=a,e.strokeStyle=o,e.lineWidth=h,e.lineCap="round",e.lineJoin="round",null!=o&&"none"!==o&&h>0&&e.strokeText(r,i,s),null!=a&&"none"!==a&&e.fillText(r,i,s)}(0,n,e,e,this.getFormatText(),this.textFont,this.textColor,this.textStrokeColor,this.textStrokeThickness,"center","middle"),n.restore())};const tp=Phaser.Utils.Objects.GetValue,ep=Phaser.Utils.Objects.IsPlainObject,ip=Phaser.Math.Clamp,sp=Phaser.Math.DegToRad(270),rp=Phaser.Math.PI2;class np extends(Xu(Nt)){constructor(t,e,i,s,r,n,a){ep(e)&&(e=tp(a=e,"x",0),i=tp(a,"y",0),s=tp(a,"radius",1),r=tp(a,"barColor",void 0),n=tp(a,"value",0));var o=2*s;super(t,e,i,o,o,tp(a,"resolution",1)),this.type="rexCircularProgressCanvas",this.bootProgressBase(a),this.setRadius(s),this.setTrackColor(tp(a,"trackColor",void 0)),this.setBarColor(r),this.setBarColor2(tp(a,"barColor2",void 0)),this.setCenterColor(tp(a,"centerColor",void 0)),this.setThickness(tp(a,"thickness",.2)),this.setStartAngle(tp(a,"startAngle",sp)),this.setEndAngle(tp(a,"endAngle",this.startAngle+rp)),this.setAnticlockwise(tp(a,"anticlockwise",!1)),this.setTextColor(tp(a,"textColor",void 0)),this.setTextStrokeColor(tp(a,"textStrokeColor",void 0),tp(a,"textStrokeThickness",void 0));var h=tp(a,"textFont",void 0);h?this.setTextFont(h):this.setTextFont(tp(a,"textSize","16px"),tp(a,"textFamily","Courier"),tp(a,"textStyle","")),this.setTextFormatCallback(tp(a,"textFormatCallback",void 0),tp(a,"textFormatCallbackScope",void 0)),this.setValue(n)}resize(t,e){return(t=Math.floor(Math.min(t,e)))===this.width||(super.resize(t,t),this.setRadius(t/2)),this}get radius(){return this._radius}set radius(t){this.dirty=this.dirty||this._radius!=t,this._radius=t;var e=2*t;this.resize(e,e)}setRadius(t){return this.radius=t,this}get trackColor(){return this._trackColor}set trackColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._trackColor!=t,this._trackColor=t}setTrackColor(t){return this.trackColor=t,this}get barColor(){return this._barColor}set barColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._barColor!=t,this._barColor=t}setBarColor(t){return this.barColor=t,this}get barColor2(){return this._barColor2}set barColor2(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._barColor2!=t,this._barColor2=t}setBarColor2(t){return this.barColor2=t,this}get startAngle(){return this._startAngle}set startAngle(t){this.dirty=this.dirty||this._startAngle!=t,this._startAngle=t,this._deltaAngle=ap(this._startAngle,this._endAngle,this._anticlockwise)}setStartAngle(t){return this.startAngle=t,this}get endAngle(){return this._endAngle}set endAngle(t){this.dirty=this.dirty||this._endAngle!=t,this._endAngle=t,this._deltaAngle=ap(this._startAngle,this._endAngle,this._anticlockwise)}setEndAngle(t){return this.endAngle=t,this}get anticlockwise(){return this._anticlockwise}set anticlockwise(t){this.dirty=this.dirty||this._anticlockwise!=t,this._anticlockwise=t,this._deltaAngle=ap(this._startAngle,this._endAngle,this._anticlockwise)}setAnticlockwise(t){return void 0===t&&(t=!0),this.anticlockwise=t,this}get thickness(){return this._thickness}set thickness(t){t=ip(t,0,1),this.dirty=this.dirty||this._thickness!=t,this._thickness=t}setThickness(t){return this.thickness=t,this}get centerColor(){return this._centerColor}set centerColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._centerColor!=t,this._centerColor=t}get centerColor2(){return this._centerColor2}set centerColor2(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._centerColor2!=t,this._centerColor2=t}setCenterColor(t,e){return this.centerColor=t,this.centerColor2=e,this}get textColor(){return this._textColor}set textColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._textColor!=t,this._textColor=t}setTextColor(t){return this.textColor=t,this}get textStrokeColor(){return this._textStrokeColor}set textStrokeColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._textStrokeColor!=t,this._textStrokeColor=t}get textStrokeThickness(){return this._textStrokeThickness}set textStrokeThickness(t){this.dirty=this.dirty||this._textStrokeThickness!=t,this._textStrokeThickness=t}setTextStrokeColor(t,e){return void 0===e&&(e=2),this.textStrokeColor=t,this.textStrokeThickness=e,this}get textFont(){return this._textFont}set textFont(t){this.dirty=this.dirty||this._textFont!=t,this._textFont=t}setTextFont(t,e,i){var s;return s=void 0===e?t:i+" "+t+" "+e,this.textFont=s,this}setTextFormatCallback(t,e){return this.textFormatCallback=t,this.textFormatCallbackScope=e,this}updateTexture(){return super.updateTexture((function(){this.clear(),Qu.call(this)}),this),this}getFormatText(t){return void 0===t&&(t=this.value),this.textFormatCallbackScope?this.textFormatCallback(t):this.textFormatCallback.call(this.textFormatCallbackScope,t)}}var ap=function(t,e,i){return i?t<=e?rp+t-e:t-e:t>=e?rp+e-t:e-t};t.register("circularProgressCanvas",(function(t,e,i,s,r,n){var a=new np(this.scene,t,e,i,s,r,n);return this.scene.add.existing(a),a})),P(window,"RexPlugins.UI.CircularProgressCanvas",np);var op=function(t,e,i,s,r,n){var a=(e+s)/2;return n>=0?t.startAt(a+n,i).lineTo(s+n,i).lineTo(s,r).lineTo(e,r).lineTo(e+n,i).lineTo(a+n,i):t.startAt(a,i).lineTo(s,i).lineTo(s-n,r).lineTo(e-n,r).lineTo(e,i).lineTo(a,i),t};const hp=Phaser.Utils.Objects.GetValue,lp=Phaser.Utils.Objects.IsPlainObject;let dp=class extends(Xu(pc)){constructor(t,e,i,s,r,n,a,o){lp(e)?(e=hp(o=e,"x",0),i=hp(o,"y",0),s=hp(o,"width",2),r=hp(o,"height",2),n=hp(o,"barColor",void 0),a=hp(o,"value",0)):lp(s)?(s=hp(o=s,"width",2),r=hp(o,"height",2),n=hp(o,"barColor",void 0),a=hp(o,"value",0)):lp(n)&&(n=hp(o=n,"barColor",void 0),a=hp(o,"value",0)),super(t,e,i,s,r,o),this.type="rexLineProgress",this.bootProgressBase(o),this.addShape((new Uc).setName("trackFill")).addShape((new Uc).setName("bar")).addShape((new Uc).setName("trackStroke")),this.setTrackColor(hp(o,"trackColor",void 0)),this.setBarColor(n),this.setTrackStroke(hp(o,"trackStrokeThickness",2),hp(o,"trackStrokeColor",void 0)),this.setSkewX(hp(o,"skewX",0)),this.setRTL(hp(o,"rtl",!1)),this.setValue(a)}get trackColor(){return this._trackColor}set trackColor(t){this.dirty=this.dirty||this._trackColor!=t,this._trackColor=t}setTrackColor(t){return this.trackColor=t,this}get trackStrokeColor(){return this._trackStrokeColor}set trackStrokeColor(t){this.dirty=this.dirty||this._trackStrokeColor!=t,this._trackStrokeColor=t}get trackStrokeThickness(){return this._trackStrokeThickness}set trackStrokeThickness(t){this.dirty=this.dirty||this._trackStrokeThickness!=t,this._trackStrokeThickness=t}setTrackStroke(t,e){return this.trackStrokeThickness=t,this.trackStrokeColor=e,this}get barColor(){return this._barColor}set barColor(t){this.dirty=this.dirty||this._barColor!=t,this._barColor=t}setBarColor(t){return this.barColor=t,this}get skewX(){return this._skewX}set skewX(t){this.dirty=this.dirty||this._skewX!=t,this._skewX=t}setSkewX(t){return this.skewX=t,this}get rtl(){return this._rtl}set rtl(t){t=!!t,this.dirty=this.dirty||this._rtl!=t,this._rtl=t}setRTL(t){return void 0===t&&(t=!0),this.rtl=t,this}};var cp={updateShapes:function(){var t=this.skewX,e=this.width-Math.abs(t),i=this.height,s=this.getShape("trackFill");s.fillStyle(this.trackColor),s.isFilled&&op(s,0,0,e,i,t).close();var r,n,a=this.getShape("bar");a.fillStyle(this.barColor),a.isFilled&&(this.rtl?(r=e*(1-this.value),n=e):(r=0,n=e*this.value),op(a,r,0,n,i,t).close());var o=this.getShape("trackStroke");o.lineStyle(this.trackStrokeThickness,this.trackStrokeColor),o.isStroked&&op(o,0,0,e,i,t).end()}};Object.assign(dp.prototype,cp),t.register("lineProgress",(function(t,e,i,s,r,n,a){var o=new dp(this.scene,t,e,i,s,r,n,a);return this.scene.add.existing(o),o})),P(window,"RexPlugins.UI.LineProgress",dp);var up=function(t,e,i,s,r,n,a){void 0===a&&(a="round"),function(t,e){t.save(),t.beginPath();var i=e[0];t.moveTo(i.x,i.y);for(var s=1,r=e.length;s0&&(n.save(),up(0,n,this.trackPoints,void 0,this.trackStrokeColor,this.trackStrokeThickness),n.restore())},gp=function(t,e,i,s,r,n){void 0===n&&(n=[]),n.length=4;for(var a=0;a<4;a++)n[a]||(n[a]={});var o;return r>=0?((o=n[0]).x=t+r,o.y=e,(o=n[1]).x=i+r,o.y=e,(o=n[2]).x=i,o.y=s,(o=n[3]).x=t,o.y=s):((o=n[0]).x=t,o.y=e,(o=n[1]).x=i,o.y=e,(o=n[2]).x=i-r,o.y=s,(o=n[3]).x=t-r,o.y=s),n};const vp=Phaser.Utils.Objects.GetValue,fp=Phaser.Utils.Objects.IsPlainObject;class mp extends(Xu(Nt)){constructor(t,e,i,s,r,n,a,o){fp(e)?(e=vp(o=e,"x",0),i=vp(o,"y",0),s=vp(o,"width",2),r=vp(o,"height",2),n=vp(o,"barColor",void 0),a=vp(o,"value",0)):fp(s)?(s=vp(o=s,"width",2),r=vp(o,"height",2),n=vp(o,"barColor",void 0),a=vp(o,"value",0)):fp(n)&&(n=vp(o=n,"barColor",void 0),a=vp(o,"value",0)),super(t,e,i,s,r,vp(o,"resolution",1)),this.type="rexLineProgressCanvas",this.trackPoints=[],this.barPoints=[],this.bootProgressBase(o),this.setTrackColor(vp(o,"trackColor",void 0)),this.setBarColor(n,vp(o,"barColor2",void 0),vp(o,"isHorizontalGradient",void 0)),this.setTrackStroke(vp(o,"trackStrokeThickness",2),vp(o,"trackStrokeColor",void 0)),this.setSkewX(vp(o,"skewX",0)),this.setRTL(vp(o,"rtl",!1)),this.setValue(a)}get trackColor(){return this._trackColor}set trackColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._trackColor!=t,this._trackColor=t}setTrackColor(t){return this.trackColor=t,this}get trackStrokeColor(){return this._trackStrokeColor}set trackStrokeColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._trackStrokeColor!=t,this._trackStrokeColor=t}get trackStrokeThickness(){return this._trackStrokeThickness}set trackStrokeThickness(t){this.dirty=this.dirty||this._trackStrokeThickness!=t,this._trackStrokeThickness=t}setTrackStroke(t,e){return this.trackStrokeThickness=t,this.trackStrokeColor=e,this}get barColor(){return this._barColor}set barColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._barColor!=t,this._barColor=t}get barColor2(){return this._barColor2}set barColor2(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._barColor2!=t,this._barColor2=t}get isHorizontalGradient(){return this._isHorizontalGradient}set isHorizontalGradient(t){this.dirty|=this._isHorizontalGradient!=t,this._isHorizontalGradient=t}setBarColor(t,e,i){return void 0===i&&(i=!0),this.barColor=t,this.barColor2=e,this.isHorizontalGradient=i,this}get skewX(){return this._skewX}set skewX(t){this.dirty=this.dirty||this._skewX!=t,this._skewX=t}setSkewX(t){return this.skewX=t,this}get rtl(){return this._rtl}set rtl(t){t=!!t,this.dirty=this.dirty||this._rtl!=t,this._rtl=t}setRTL(t){return void 0===t&&(t=!0),this.rtl=t,this}updateTexture(){return super.updateTexture((function(){this.clear(),pp.call(this)}),this),this}}t.register("circularProgressCanvas",(function(t,e,i,s,r,n,a){var o=new mp(this.scene,t,e,i,s,r,n,a);return this.scene.add.existing(o),o})),P(window,"RexPlugins.UI.LineProgressCanvas",mp),Phaser.Math.Wrap;const yp=Phaser.Math.Linear;var bp=function(){var t,e,i,s,r,n,a=this.getShape("triangle"),o=this.padding,h=this.width-o.right,l=0+o.left,d=this.height-o.bottom,c=0+o.top,u=(l+h)/2,p=(c+d)/2,g={0:{a:{x:l,y:c},b:{x:h,y:p},c:{x:l,y:d}},1:{a:{x:l,y:c},b:{x:u,y:d},c:{x:h,y:c}},2:{a:{x:h,y:c},b:{x:l,y:p},c:{x:h,y:d}},3:{a:{x:l,y:d},b:{x:u,y:c},c:{x:h,y:d}}};if(void 0===this.previousDirection){var v=g[this.direction],f=v.a,m=v.b,y=v.c;t=f.x,e=f.y,i=m.x,s=m.y,r=y.x,n=y.y}else{var b=g[this.previousDirection],x=g[this.direction],C=this.easeDirectionProgress;t=yp(b.a.x,x.a.x,C),e=yp(b.a.y,x.a.y,C),i=yp(b.b.x,x.b.x,C),s=yp(b.b.y,x.b.y,C),r=yp(b.c.x,x.c.x,C),n=yp(b.c.y,x.c.y,C)}a.startAt(t,e).lineTo(i,s).lineTo(r,n),this.arrowOnly?a.end():a.close()};const xp=(0,Phaser.Math.DegToRad)(120);var Cp=function(t){t=this.getShape("triangle");var e=this.width/2,i=this.height/2,s=Math.min(e,i)*this.radius,r=this.verticeRotation;t.startAt(e+s*Math.cos(r+xp),i+s*Math.sin(r+xp)).lineTo(e+s*Math.cos(r),i+s*Math.sin(r)).lineTo(e+s*Math.cos(r-xp),i+s*Math.sin(r-xp)),this.arrowOnly?t.end():t.close()},kp={buildShapes(){this.addShape((new Uc).setName("triangle"))},updateShapes(){var t=this.getShape("triangle");this.arrowOnly?t.fillStyle().lineStyle(this.lineWidth,this.strokeColor,this.strokeAlpha):t.fillStyle(this.fillColor,this.fillAlpha).lineStyle(this.lineWidth,this.strokeColor,this.strokeAlpha),0===this.shapeMode?bp.call(this):Cp.call(this)}},wp={setEaseDuration(t){return void 0===t&&(t=0),this.easeDuration=t,this},playEaseDirectionation(){return void 0===this.easeDirectionProgressTask&&(this.easeDirectionProgressTask=new tu(this,{eventEmitter:null})),this.easeDirectionProgressTask.restart({key:"easeDirectionProgress",from:0,to:1,duration:this.easeDuration}),this},stopEaseDirection(){return void 0===this.easeDirectionProgressTask||this.easeDirectionProgressTask.stop(),this}};const Sp=Phaser.Utils.Objects.GetValue,Pp=Phaser.Utils.Objects.IsPlainObject,Tp=Phaser.Math.DegToRad,Op=Phaser.Math.RadToDeg;class Mp extends pc{constructor(t,e,i,s,r,n,a){var o,h,l,d,c,u,p,g;if(Pp(e)){var v=e;e=v.x,i=v.y,s=v.width,r=v.height,n=v.color,a=v.alpha,o=v.strokeColor,h=v.strokeAlpha,l=v.strokeWidth,d=v.arrowOnly,c=v.direction,u=v.easeDuration,p=v.padding,g=v.radius}void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=1),void 0===r&&(r=s),void 0===d&&(d=!1),void 0===c&&(c=0),void 0===u&&(u=0),void 0===p&&(p=0),void 0===g&&(g=void 0),super(t,e,i,s,r),this.type="rexTriangle",this.setFillStyle(n,a),void 0!==o&&void 0===l&&(l=2),this.setStrokeStyle(l,o,h),this.setArrowOnly(d),this.setDirection(c,u),this.setPadding(p),this.setRadius(g),this.buildShapes()}get arrowOnly(){return this._arrowOnly}set arrowOnly(t){this.dirty=this.dirty||this._arrowOnly!=t,this._arrowOnly=t}setArrowOnly(t){return void 0===t&&(t=!0),this.arrowOnly=t,this}get direction(){return this._direction}set direction(t){t=_p(t),this._direction!==t&&(this.easeDuration>0&&void 0!==this._direction?this.previousDirection=this._direction:this.previousDirection=void 0,this._direction=t,this.verticeAngle=90*t,this.dirty=!0,void 0!==this.previousDirection?this.playEaseDirectionation():this.stopEaseDirection())}setDirection(t,e){return void 0!==e&&this.setEaseDuration(e),this.direction=t,this}toggleDirection(t){return this.setDirection(this.direction+2,t),this}get easeDirectionProgress(){return this._easeDirectionProgress}set easeDirectionProgress(t){this._easeDirectionProgress!==t&&(this._easeDirectionProgress=t,this.dirty=!0)}setPadding(t,e,i,s){if("object"==typeof t){var r=t,n=Sp(r,"x",null);null!==n?(t=n,i=n):(t=Sp(r,"left",0),i=Sp(r,"right",t));var a=Sp(r,"y",null);null!==a?(e=a,s=a):(e=Sp(r,"top",0),s=Sp(r,"bottom",e))}else void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=t),void 0===s&&(s=e);return void 0===this.padding&&(this.padding={}),this.dirty=this.dirty||this.padding.left!=t||this.padding.top!=e||this.padding.right!=i||this.padding.bottom!=s,this.padding.left=t,this.padding.top=e,this.padding.right=i,this.padding.bottom=s,this.setRadius(),this}get radius(){return this._radius}set radius(t){this.dirty=this.dirty||this._radius!=t,this._radius=t}setRadius(t){return this.radius=t,this.shapeMode=null==t?0:1,this}get verticeRotation(){return this._verticeRotation}set verticeRotation(t){this.dirty=this.dirty||this._verticeRotation!=t,this._verticeRotation=t}setVerticeRotation(t){return this.verticeRotation=t,this}get verticeAngle(){return Op(this.verticeRotation)}set verticeAngle(t){this.verticeRotation=Tp(t)}setVerticeAngle(t){return this.verticeAngle=t,this}}const Ep={right:0,down:1,left:2,up:3};var _p=function(t){return"string"==typeof t&&(t=Ep[t]),t%=4};Object.assign(Mp.prototype,kp,wp),t.register("triangle",(function(t,e,i,s,r,n){var a=new Mp(this.scene,t,e,i,s,r,n);return this.scene.add.existing(a),a})),P(window,"RexPlugins.UI.Triangle",Mp),F();const Rp=Phaser.GameObjects.Zone,Lp=Phaser.Utils.Array.Add,Bp=Phaser.Utils.Array.Remove;let Ip=class extends Rp{constructor(t,e,i,s,r){void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=1),void 0===r&&(r=1),super(t,e,i,s,r),this.children=[]}destroy(t){if(this.scene&&!this.ignoreDestroy){if(t)for(var e,i=this.children.length-1;i>=0;i--)(e=this.children[i]).parentContainer||e.displayList||e.destroy(t);this.clear(!t),super.destroy(t)}}contains(t){return-1!==this.children.indexOf(t)}add(t){var e=this;return Lp(this.children,t,0,(function(t){t.once("destroy",e.onChildDestroy,e)}),this),this}remove(t,e){var i=this;return Bp(this.children,t,(function(t){t.off("destroy",i.onChildDestroy,i),e&&t.destroy()})),this}onChildDestroy(t,e){this.remove(t,!1)}clear(t){for(var e,i=0,s=this.children.length;iYp(t),resetChildState(t){return this.resetChildPositionState(t).resetChildVisibleState(t).resetChildAlphaState(t).resetChildActiveState(t),this},resetChildrenState(t){for(var e=0,i=t.length;eYp(t).x,getChildLocalY:t=>Yp(t).y};const ig=Phaser.Math.DegToRad;var sg={updateChildRotation(t){var e=Yp(t),i=e.parent;return e.syncRotation&&(t.rotation=i.rotation+e.rotation),this},syncRotation(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildRotation,this),this},resetChildRotationState(t){var e=Yp(t),i=e.parent;return e.rotation=t.rotation-i.rotation,this},setChildRotation(t,e){return t.rotation=e,this.resetChildRotationState(t),this},setChildAngle(t,e){return t.angle=e,this.resetChildRotationState(t),this},setChildLocalRotation(t,e){return Yp(t).rotation=e,this.updateChildRotation(t),this},setChildLocalAngle(t,e){return Yp(t).rotation=ig(e),this.updateChildRotation(t),this},resetLocalRotationState(){var t=Yp(this).parent;return t&&t.resetChildRotationState(this),this},getChildLocalRotation:t=>Yp(t).rotation},rg={updateChildScale(t){var e=Yp(t),i=e.parent;return e.syncScale&&(t.scaleX=i.scaleX*e.scaleX,t.scaleY=i.scaleY*e.scaleY),this},syncScale(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildScale,this),this},resetChildScaleState(t){var e=Yp(t),i=e.parent;return e.scaleX=tg(t.scaleX,i.scaleX),e.scaleY=tg(t.scaleY,i.scaleY),this},setChildScale(t,e,i){return void 0===i&&(i=e),t.scaleX=e,t.scaleY=i,this.resetChildScaleState(t),this},setChildLocalScale(t,e,i){void 0===i&&(i=e);var s=Yp(t);return s.scaleX=e,s.scaleY=i,this.updateChildScale(t),this},setChildDisplaySize(t,e,i){return t.setDisplaySize(e,i),this.resetChildScaleState(t),this},resetLocalScaleState(){var t=Yp(this).parent;return t&&t.resetChildScaleState(this),this},getChildLocalScaleX:t=>Yp(t).scaleX,getChildLocalScaleY:t=>Yp(t).scaleY},ng={updateChildVisible(t){var e=Yp(t),i=e.parent,s=!e.hasOwnProperty("maskVisible")||e.maskVisible,r=!i||i.visible;return t.visible=r&&e.visible&&s,this},syncVisible(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildVisible,this),this},resetChildVisibleState(t){var e=Yp(t);return e.hasOwnProperty("maskVisible")&&delete e.maskVisible,e.visible=t.visible,this},setChildVisible(t,e){return this.setChildLocalVisible(t,e),this},setChildLocalVisible(t,e){return void 0===e&&(e=!0),Yp(t).visible=e,this.updateChildVisible(t),this},setChildMaskVisible(t,e){return void 0===e&&(e=!0),Yp(t).maskVisible=e,this.updateChildVisible(t),this},resetLocalVisibleState(){var t=Yp(this).parent;return t&&t.resetChildVisibleState(this),this},getChildLocalVisible:t=>Yp(t).visible},ag={updateChildAlpha(t){var e=Yp(t),i=e.parent;return e.syncAlpha&&(t.alpha=i.alpha*e.alpha),this},syncAlpha(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildAlpha,this),this},resetChildAlphaState(t){var e=Yp(t),i=e.parent;return e.alpha=tg(t.alpha,i.alpha),this},setChildAlpha(t,e){return t.alpha=e,this.resetChildAlphaState(t),this},setChildLocalAlpha(t,e){return Yp(t).alpha=e,this.updateChildAlpha(t),this},resetLocalAlphaState(){var t=Yp(this).parent;return t&&t.resetChildAlphaState(this),this},getChildLocalAlpha:t=>Yp(t).alpha},og={updateChildActive(t){var e=Yp(t),i=e.parent;return t.active=i.active&&e.active,this},syncActive(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildActive,this),this},resetChildActiveState(t){return Yp(t).active=t.active,this},setChildActive(t,e){return t.active=e,this.resetChildActiveState(t),this},setChildLocalActive(t,e){return void 0===e&&(e=!0),Yp(t).active=e,this.updateChildActive(t),this},resetLocalActiveState(){var t=Yp(this).parent;return t&&t.resetChildActiveState(this),this},getChildLocalActive:t=>Yp(t).active},hg={updateChildScrollFactor(t){var e=Yp(t),i=e.parent;return e.syncScrollFactor&&(t.scrollFactorX=i.scrollFactorX,t.scrollFactorY=i.scrollFactorY),this},syncScrollFactor(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildScrollFactor,this),this}},lg={updateCameraFilter(t){var e=Yp(t),i=e.parent;return e.syncCameraFilter&&(t.cameraFilter=i.cameraFilter),this},syncCameraFilter(){return this.syncChildrenEnable&&this.children.forEach(this.updateCameraFilter,this),this}},dg={updateChildMask(t){return null==this.mask||(this.mask.hasOwnProperty("geometryMask")?this.mask.geometryMask:this.mask.bitmapMask)!==t&&(t.mask=this.mask),this},syncMask(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildMask,this),this},setMask(t){return this.mask=t,this},clearMask(t){void 0===t&&(t=!1);var e=this;return this._mask=null,this.setChildMaskVisible(this),this.children.forEach((function(t){t.clearMask&&t.clearMask(!1),t.hasOwnProperty("isRexContainerLite")||e.setChildMaskVisible(t)})),t&&this.mask&&this.mask.destroy(),this}},cg=function(t){return t.filter((function(t){return!!t.displayList||!!t.parentContainer||void 0}))},ug={setDepth(t,e){if(this.depth=t,!e&&this.children)for(var i=this.getAllChildren(),s=0,r=i.length;s=0;r--){var n=e[r];s!==n&&(n!==this&&s.displayList!==n.displayList||(s.displayList.moveBelow(n,s),s=n))}return this}},pg=function(t,e){if(!e(t)&&t.isRexContainerLite)for(var i=t.children,s=0,r=i.length;s0;){var s=i.shift();!e(s)&&s.isRexContainerLite&&i.push(...s.children)}};const vg=Phaser.Utils.Array;var fg={getChildren(t){if(t)for(var e=0,i=this.children.length;e=0;e--)this.remove(this.backgroundChildren[e],t);return this}},Ov=function(t,e){if("string"==typeof t)this.childrenMap[t]=e;else{var i=t;for(t in i)this.childrenMap[t]=i[t]}return this};const Mv=/(\S+)\[(\d+)\]/i;var Ev={getInnerPadding(t){return Ps(this.space,t)},setInnerPadding(t,e){return Ts(this.space,t,e),this},getOuterPadding(t){return Ps(this.getSizerConfig(this).padding,t)},setOuterPadding(t,e){return Ts(this.getSizerConfig(this).padding,t,e),this},getChildOuterPadding(t,e){return"string"==typeof t&&(t=this.getElement(t)),Ps(this.getSizerConfig(t).padding,e)},setChildOuterPadding(t,e,i){return"string"==typeof t&&(t=this.getElement(t)),Ts(this.getSizerConfig(t).padding,e,i),this}},_v=function(t){var e=this.childrenWidth;if(void 0!==e){var i=void 0!==this.minWidth?this.minWidth*this.scaleX:0;return void 0===t?(t=Math.max(i,e),this.layoutWarnEnable&&i>0&&e>i&&console.warn(`Layout width warn: ${this.constructor.name}'s minWidth (${i}) < childrenWidth (${e})`)):this.layoutWarnEnable&&(i>t||e>t)&&console.warn(`Layout width warn: ${this.constructor.name}'s minWidth (${i}) or childrenWidth (${e} > targetWidth ${t})`),t}},Rv=function(){var t;for(var e in this.sizerChildren)if(!(!(t=this.sizerChildren[e])||t.isRexSizer&&t.ignoreLayout)&&t.runWidthWrap&&(!t.hasWidthWrap||t.hasWidthWrap()))return!0;return!1},Lv=function(t){var e,i,s;for(var r in this.sizerChildren)!(e=this.sizerChildren[r])||e.isRexSizer&&e.ignoreLayout||!e.runWidthWrap||(i=this.getExpandedChildWidth(e,t),e.isRexSizer?void 0===(s=e.resolveWidth(i))&&(s=i):s=i,e.runWidthWrap(s));return this},Bv=function(t){var e=this.childrenHeight;if(void 0!==e){var i=void 0!==this.minHeight?this.minHeight*this.scaleY:0;return void 0===t?(t=Math.max(i,e),this.layoutWarnEnable&&i>0&&e>i&&console.warn(`Layout height warn: ${this.constructor.name}'s minHeight (${i}) < childrenHeight (${e})`)):this.layoutWarnEnable&&(i>t||e>t)&&console.warn(`Layout height warn: ${this.constructor.name}'s minHeight (${i}) or childrenHeight (${e}) > targetHeight (${t})`),t}},Iv=function(){var t;for(var e in this.sizerChildren)if(!(!(t=this.sizerChildren[e])||t.isRexSizer&&t.ignoreLayout)&&t.runHeightWrap&&(!t.hasHeightWrap||t.hasHeightWrap()))return!0;return!1},Dv=function(t){var e,i,s;for(var r in this.sizerChildren)!(e=this.sizerChildren[r])||e.isRexSizer&&e.ignoreLayout||!e.runHeightWrap||(i=this.getExpandedChildHeight(e,t),e.isRexSizer?void 0===(s=e.resolveHeight(i))&&(s=i):s=i,e.runHeightWrap(s));return this},jv={getShownChildren(t){void 0===t&&(t=[]);for(var e,i=this.children,s=0,r=i.length;s0;){var i=e.shift();i.rexSizer&&i.rexSizer.hidden||(i!==this&&t.push(i),i.isRexContainerLite&&e.push(...i.children))}return t}},Av=function(){this._childrenWidth=void 0,this._childrenHeight=void 0;for(var t,e=this.getChildrenSizers(),i=0,s=e.length;i0){var e=t.runTransitionInCallback();t.delayCall(e,this.next,this)}else this.next()}exit_TRANS_OPNE(){this.parent.removeDelayCall()}next_OPEN(){return"TRANS_CLOSE"}enter_OPEN(){this.parent.onOpen()}exit_OPEN(){this.parent.removeDelayCall()}next_TRANS_CLOSE(){return"CLOSE"}enter_TRANS_CLOSE(){var t=this.parent;if(t.transitOutTime>0){var e=t.runTransitionOutCallback();t.delayCall(e,this.next,this)}else this.next()}exit_TRANS_CLOSE(){this.parent.removeDelayCall()}next_CLOSE(){return"TRANS_OPNE"}enter_CLOSE(){this.parent.onClose()}exit_CLOSE(){}canOpen(){return"IDLE"===this.state||"CLOSE"===this.state}canClose(){return"IDLE"===this.state||"OPEN"===this.state}};var Jf={delayCall(t,e,i){return this.delayCallTimer=function(t,e,i,s,r){var n=Ea(t);return n.time.delayedCall(e,(function(){n.game.events.once("poststep",(function(){i.call(s,r)}))}))}(this,t,e,i),this},removeDelayCall(){return this.delayCallTimer&&(this.delayCallTimer.remove(!1),this.delayCallTimer=void 0),this}},qf={setTransitInTime(t){return this.transitInTime=t,this},setTransitOutTime(t){return this.transitOutTime=t,this},setTransitInCallback(t){return t||(t=h),this.transitInCallback=t,this},setTransitOutCallback(t){return t||(t=h),this.transitOutCallback=t,this}},Zf={runTransitionInCallback(){return this.transitInCallback(this.parent,this.transitInTime),this.transitInTime},onOpen(){},requestOpen(t,e){if(!this._state.canOpen())return this;this.openEventData=arguments.length>0?t:this.parent;var i=this.transitInTime;return void 0!==e&&(this.transitInTime=e),this._state.goto("TRANS_OPNE"),this.transitInTime=i,this}},Qf={runTransitionOutCallback(){return this.transitOutCallback(this.parent,this.transitOutTime),this.transitOutTime},onClose(){this.oneShotMode&&this.parent.destroy()},requestClose(t,e){if(!this._state.canClose)return this;this.closeEventData=arguments.length>0?t:this.parent;var i=this.transitOutTime;return void 0!==e&&(this.transitOutTime=e),this._state.goto("TRANS_CLOSE"),this.transitOutTime=i,this}},tm={};Object.assign(tm,Jf,qf,Zf,Qf);const em=Phaser.Utils.Objects.GetValue;class im extends Ra{constructor(t,e){super(t,e),this.setTransitInTime(em(e,"duration.in",200)),this.setTransitOutTime(em(e,"duration.out",200)),this.setTransitInCallback(em(e,"transitIn")),this.setTransitOutCallback(em(e,"transitOut")),this.oneShotMode=em(e,"destroy",!1),this.delayCallTimer=void 0,this._state=new Kf(this,{eventEmitter:!1,initState:em(e,"initState","IDLE")}),this.openEventData=void 0,this.closeEventData=void 0}get state(){return this._state.state}shutdown(t){this.isShutdown||(this.transitInCallback=void 0,this.transitOutCallback=void 0,this.openEventData=void 0,this.closeEventData=void 0,this.removeDelayCall(),super.shutdown(t))}}Object.assign(im.prototype,tm);const sm=Phaser.GameObjects.Rectangle;class rm extends sm{constructor(t,e,i){super(t,0,0,2,2,e,1),this.fullWindow=new Md(this),this.setAlpha(i)}get tint(){return this.fillColor}set tint(t){this.setFillStyle(t,this.fillAlpha)}}const nm=Phaser.Utils.Objects.GetValue;class am extends Ra{constructor(t,e){super(t,{eventEmitter:!1}),this.resetFromJSON(e),this.boot()}resetFromJSON(t){return this.setHitAreaMode(nm(t,"hitAreaMode",0)),this.setEnable(nm(t,"enable",!0)),this.setStopMode(nm(t,"stopAllLevels",!0)),this}boot(){this.parent.on("pointerdown",(function(t,e,i,s){this.stopAllLevels&&s.stopPropagation()}),this).on("pointerup",(function(t,e,i,s){this.stopAllLevels&&s.stopPropagation()}),this).on("pointermove",(function(t,e,i,s){this.stopAllLevels&&s.stopPropagation()}),this).on("pointerover",(function(t,e,i,s){this.stopAllLevels&&s.stopPropagation()}),this).on("pointerout",(function(t,e){this.stopAllLevels&&e.stopPropagation()}),this)}setHitAreaMode(t){"string"==typeof t&&(t=om[t]);var e=this.parent;return e.input&&e.removeInteractive(),0===t?e.setInteractive():e.setInteractive({hitArea:{},hitAreaCallback:function(){return!0}}),this}setEnable(t){return void 0===t&&(t=!0),t?this.parent.setInteractive():this.parent.disableInteractive(),this.enable=t,this}setStopMode(t){return void 0===t&&(t=!0),this.stopAllLevels=t,this}toggleEnable(){return this.setEnable(!this.enable),this}}var om={default:0,fullWindow:1};const hm=Phaser.Utils.Objects.GetValue;class lm extends rm{constructor(t,e){super(t,hm(e,"color",0),hm(e,"alpha",.8)),this.touchEventStop=new am(this,{hitAreaMode:1})}}var dm={popUp(t,e){void 0!==t._modalScaleSave?(t.scaleX=t._modalScaleSave,t.scaleY=t._modalScaleSave):t._modalScaleSave=t.scaleX,Zv(t,e)},scaleDown(t,e){Qv(t,e,void 0,void 0,!1)},fadeIn(t,e){void 0!==t._modalAlphaSave?t.alpha=t._modalAlphaSave:t._modalAlphaSave=t.alpha,df(t,e)},fadeOut(t,e){cf(t,e,!1)}},cm=function(t,e){void 0!==t._modalAlphaSave?t.alpha=t._modalAlphaSave:t._modalAlphaSave=t.alpha,df(t,e,t.alpha)},um=function(t,e){cf(t,e,!1)},pm=function(t,e,i,s,r){return!(!t||s&&!s(t,e,i)||!Wn(t,!0).contains(e,i)||r&&!r(t,e,i))};const gm=Phaser.Utils.Objects.GetValue;let vm=class extends im{constructor(t,e){void 0===e&&(e={}),null==e.transitIn&&(e.transitIn=fm.popUp),null==e.transitOut&&(e.transitOut=fm.scaleDown),e.destroy=gm(e,"destroy",!0),super(t,e);var i=gm(e,"cover");this.cover=!1!==i?function(t,e){var i=t.scene,s=new lm(i,e);return i.add.existing(s),t.isRexContainerLite?(t.pin(s,{syncPosition:!1,syncRotation:!1,syncScale:!1,syncAlpha:!1,syncScrollFactor:!1}),t.moveDepthBelow(s)):i.children.moveBelow(s,t),s}(t,i):void 0,this.cover&&(this.setCoverTransitInCallback(gm(i,"transitIn",cm)),this.setCoverTransitOutCallback(gm(i,"transitOut",um)));var s=gm(e,"touchOutsideClose",!1),r=gm(e,"duration.hold",-1),n=gm(e,"timeOutClose",r>=0),a=gm(e,"anyTouchClose",!1);gm(e,"manualClose",!1)&&(s=!1,a=!1,n=!1),a&&(s=!1),n?this.setDisplayTime(r):this.setDisplayTime(-1),a?this.once("open",this.anyTouchClose,this):s&&this.once("open",this.touchOutsideClose,this),gm(e,"openOnStart",!0)&&this.delayCall(0,this.requestOpen,this)}shutdown(t){this.isShutdown||(this.cover||this.scene.input.off("pointerup",this.touchCloseCallback,this),this.cover&&!t&&(this.cover.destroy(),this.cover=void 0),super.shutdown(t))}touchOutsideClose(){return this.cover?this.cover.on("pointerup",this.touchCloseCallback,this):this.scene.input.on("pointerup",this.touchCloseCallback,this),this.clickOutsideTest=!0,this}anyTouchClose(){return this.cover?this.cover.once("pointerup",this.touchCloseCallback,this):this.scene.input.once("pointerup",this.touchCloseCallback,this),this}touchCloseCallback(t){this.clickOutsideTest&&pm(this.parent,t.worldX,t.worldY)||this.requestClose()}runTransitionInCallback(){var t=super.runTransitionInCallback(),e=this.cover;return e&&this.coverTransitInCallback&&this.coverTransitInCallback(e,t),t}runTransitionOutCallback(){var t=super.runTransitionOutCallback(),e=this.cover;return e&&this.coverTransitOutCallback&&this.coverTransitOutCallback(e,t),t}onOpen(){var t=this.displayTime;t>=0&&this.delayCall(t,this.requestClose,this),this.emit("open",this.parent,this),super.onOpen()}onClose(){this.emit("close",this.closeEventData),super.onClose()}setDisplayTime(t){return this.displayTime=t,this}setTransitInCallback(t){switch("string"==typeof t&&(t=fm[t]),t){case fm.popUp:t=dm.popUp;break;case fm.fadeIn:t=dm.fadeIn}return super.setTransitInCallback(t),this}setTransitOutCallback(t){switch("string"==typeof t&&(t=fm[t]),t){case fm.scaleDown:t=dm.scaleDown;break;case fm.fadeOut:t=dm.fadeOut}return super.setTransitOutCallback(t),this}setCoverTransitInCallback(t){return this.coverTransitInCallback=t,this}setCoverTransitOutCallback(t){return this.coverTransitOutCallback=t,this}};const fm={popUp:0,fadeIn:1,scaleDown:0,fadeOut:1};var mm=function(t,e){var i=new vm(t,e);return i.on("open",(function(){t.emit("modal.open",i)})),i.on("close",(function(e){t.emit("modal.close",e,i)})),t.on("modal.requestClose",i.requestClose,i),i},ym=function(t,e){t.emit("modal.requestClose",e)},bm=function(t){return t&&"function"==typeof t},xm={modal(t,e){return bm(t)&&(e=t,t=void 0),void 0===this._modalBehavior&&(this.onCreateModalBehavior&&this.onCreateModalBehavior(this,t),this._modalBehavior=mm(this,t)),e&&this._modalBehavior.once("close",e),this._modalBehavior.requestOpen(),this},modalPromise(t){var e=this;return new Promise((function(i,s){e.modal(t,i)}))},modalClose(t){return ym(this,t),this}},Cm=function(t,e,i,s,r){bm(e)&&(r=s,s=i,i=e,e=this);var n=this.scene.events;return this.bindEvent(e,n,t,i,s,r),this},km={bindEvent(t,e,i,s,r,n){return"string"==typeof e&&(n=r,r=s,s=i,i=e,e=t,t=this),function(t,e,i,s,r,n){void 0===n&&(n=!1),e[n?"once":"on"](i,s,r),t.once("destroy",(function(){e.off(i,s,r)}))}(t,e,i,s,r,n),this},bindScenePreupdateEvent(t,e,i,s){return Cm.call(this,"preupdate",t,e,i,s),this},bindSceneUpdateEvent(t,e,i,s){return Cm.call(this,"update",t,e,i,s),this},bindScenePostupdateEvent(t,e,i,s){return Cm.call(this,"postupdate",t,e,i,s),this},bindSceneRenderEvent(t,e,i,s){return Cm.call(this,"render",t,e,i,s),this},bindScenePauseEvent(t,e,i,s){return Cm.call(this,"pause",t,e,i,s),this},bindSceneResumeEvent(t,e,i,s){return Cm.call(this,"resume",t,e,i,s),this},bindSceneSleepEvent(t,e,i,s){return Cm.call(this,"sleep",t,e,i,s),this},bindSceneWakeEvent(t,e,i,s){return Cm.call(this,"wake",t,e,i,s),this},bindSceneShutdownEvent(t,e,i,s){return Cm.call(this,"shutdown",t,e,i,s),this}},wm=function(t,e,i){var s=t.camera;return s?(void 0===i?i={}:!0===i&&(i=Sm),s===e?(i.x=t.worldX,i.y=t.worldY):s.getWorldPoint(t.x,t.y,i),i):null},Sm={},Pm=function(t,e,i,s){var r,n=t.scene.sys.cameras.main,a=0===t.scrollFactorX&&0===t.scrollFactorY;if(e)return a?pm(t,e.x,e.y,i,s):!!(r=wm(e,n,!0))&&pm(t,r.x,r.y,i,s);for(var o=t.scene.input.manager,h=o.pointersTotal,l=o.pointers,d=0;d=this.dragThreshold||this.isPointerInside(t))&&this.cancel()}click(t,e){if(!this.enable)return this;if(void 0===t)return this.emit("clickoutside",this,this.parent,e),this;this.pointer=void 0;var i=this.lastClickTime;return void 0!==i&&t-i<=this.clickInterval||(this.lastClickTime=t,this.emit("clickoutside",this,this.parent,e)),this}cancel(){return this.pointer=void 0,this}}const zm={press:0,pointerdown:0,release:1,pointerup:1};var Fm={onClickOutside(t,e,i,s){return t?("function"==typeof t&&(s=i,i=e,e=t,t=this),void 0===t._clickOutside&&(t._clickOutside=new Am(t,s)),t._clickOutside.on("clickoutside",e,i),this):this},offClickOutside(t,e,i){return"function"==typeof t&&(i=e,e=t,t=this),void 0===t._clickOutside||t._clickOutside.off("clickoutside",e,i),this},enableClickOutside(t,e){return"boolean"==typeof t&&(e=t,t=void 0),void 0===t&&(t=this),void 0===t._clickOutside||t._clickOutside.setEnable(e),this},disableClickOutside(t){return void 0===t&&(t=this),void 0===t._clickOutside||t._clickOutside.setEnable(!1),this}};class Ym extends $f{constructor(){super({eventEmitter:!1}),this.goto("IDLE")}setCooldownTime(t){return this.cooldownTime=t,this.cooldownMode=void 0!==t,this}request(){return this.runMethod("request")}update_IDLE(){this.compensationTime=0}request_IDLE(){return this.next(),!0}next_IDLE(){if(this.cooldownMode)return"COOLDOWN"}enter_COOLDOWN(){this.remainderTime=this.cooldownTime+this.compensationTime}update_COOLDOWN(t,e){this.remainderTime-=e,this.remainderTime<0&&(this.compensationTime=this.cooldownTime>e?-this.remainderTime:0,this.goto("IDLE"))}request_COOLDOWN(){return!1}}const Xm=Phaser.Utils.Objects.GetValue;class Wm extends Ra{constructor(t,e){super(t,e),this._enable=void 0,this.cooldown=new Ym,this.parent.setInteractive(Xm(e,"inputConfig",void 0)),this.resetFromJSON(e),this.boot()}resetFromJSON(t){return this.pointer=void 0,this.prevIsInTouch=!1,this.isInTouching=!1,this.setEnable(Xm(t,"enable",!0)),this.setCooldown(Xm(t,"cooldown",void 0)),this}boot(){var t=this.parent;t.on("pointerdown",this.onPointIn,this),t.on("pointerover",this.onPointIn,this),t.on("pointerup",this.onPointOut,this),t.on("pointerout",this.onPointOut,this),this.scene.sys.events.on("preupdate",this.preupdate,this)}shutdown(t){this.isShutdown||(this.scene.sys.events.off("preupdate",this.preupdate,this),this.pointer=void 0,super.shutdown(t))}get enable(){return this._enable}set enable(t){if(this._enable!==t)return t||(this.prevIsInTouch=!1,this.isInTouching=!1,this.pointer=void 0),this._enable=t,this}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}get cooldownTime(){return this.cooldown.cooldownTime}set cooldownTime(t){this.cooldown.setCooldownTime(t)}setCooldown(t){return this.cooldownTime=t,this}toggleEnable(){return this.setEnable(!this.enable),this}onPointIn(t,e,i){this.enable&&t.isDown&&void 0===this.pointer&&(this.pointer=t,this.isInTouching=!0)}onPointOut(t){this.enable&&this.pointer===t&&(this.pointer=void 0,this.isInTouching=!1)}preupdate(t,e){this.cooldown.update(t,e),!this.prevIsInTouch&&this.isInTouching&&this.emit("touchstart",this,this.parent),this.isInTouching&&this.cooldown.request()&&this.emit("intouch",this,this.parent,this.pointer),this.prevIsInTouch&&!this.isInTouching&&this.emit("touchend",this,this.parent),this.prevIsInTouch=this.isInTouching}}var Vm={isPointerInBounds(t){return void 0===t?t=this:"string"==typeof t&&(t=this.getElement(t)),!!t&&Pm(t)},onTouching(t,e,i,s){return t?("function"==typeof t&&(s=i,i=e,e=t,t=this),void 0===t._inTouching&&(t._inTouching=new Wm(t,s)),t._inTouching.on("intouch",e,i),this):this},offTouching(t,e,i){return"function"==typeof t&&(i=e,e=t,t=this),void 0===t._inTouching||t._inTouching.off("intouch",e,i),this},onTouchingEnd(t,e,i,s){return t?("function"==typeof t&&(s=i,i=e,e=t,t=this),void 0===t._inTouching&&(t._inTouching=new Wm(t,s)),t._inTouching.on("touchend",e,i),this):this},offTouchingEnd(t,e,i){return"function"==typeof t&&(i=e,e=t,t=this),void 0===t._inTouching||t._inTouching.off("touchend",e,i),this},enableTouching(t,e){return"boolean"==typeof t&&(e=t,t=void 0),void 0===t&&(t=this),void 0===t._inTouching||t._inTouching.setEnable(e),this},disableTouching(t){return void 0===t&&(t=this),void 0===t._inTouching||t._inTouching.setEnable(!1),this}},Gm={onOver(t,e,i){return t?("function"==typeof t&&(i=e,e=t,t=this),t.setInteractive().on("pointerover",e,i),this):this},onOut(t,e,i){return t?("function"==typeof t&&(i=e,e=t,t=this),t.setInteractive().on("pointerout",e,i),this):this}},Hm=function(t,e,i){for(var s,r=0,n=t.length;r0),this.onDragStart())}onPointerUp(t){this.enable&&(!this.bounds||this.bounds.contains(t.x,t.y))&&this.pointer===t&&(this.pointer=void 0,this.pointerCamera=void 0,this.movedState=!1,this.tracerState=oy,this.onDragEnd())}onPointerMove(t){if(this.enable&&t.isDown){var e=!this.bounds||this.bounds.contains(t.x,t.y),i=this.pointer===t;!i&&e||(i&&!e?this.onPointerUp(t):(this.movedState||(this.movedState=t.x!==t.downX||t.y!==t.downY),this.movedState&&this.onDrag()))}}dragCancel(){return this.tracerState===hy&&this.onDragEnd(),this.pointer=void 0,this.tracerState=oy,this}onDragStart(){this.emit("dragstart",this)}onDragEnd(){this.emit("dragend",this)}onDrag(){this.emit("drag",this)}preUpdate(t,e){}postUpdate(t,e){}startTicking(){super.startTicking(),this.scene.sys.events.on("preupdate",this.preUpdate,this),this.scene.sys.events.on("postupdate",this.postUpdate,this)}stopTicking(){super.stopTicking(),this.scene&&(this.scene.sys.events.off("preupdate",this.preUpdate,this),this.scene.sys.events.off("postupdate",this.postUpdate,this))}setRecongizedStateObject(t){return this.recongizedState=t,this}get state(){return this.recongizedState.state}set state(t){this.recongizedState.state=t}cancel(){return this.state=ly,this}isPointerInGameObject(t,e,i){var s=this.lastPointer;return!!s&&Pm(t,s,e,i)}}const oy=0,hy=1,ly="IDLE",dy=Phaser.Utils.Objects.GetValue,cy=Phaser.Math.Distance.Between;class uy extends ay{constructor(t,e){super(t,e);var i=this,s={states:{IDLE:{enter:function(){i.stop(),i.tapsCount=0,i.x=0,i.y=0,i.worldX=0,i.worldY=0,i.lastPointer=void 0},exit:function(){var t=i.lastPointer;i.x=t.x,i.y=t.y,i.worldX=t.worldX,i.worldY=t.worldY}},BEGIN:{enter:function(){i.start(),i.tapsCount=0,i.emit("tappingstart",i,i.gameObject,i.lastPointer)}},RECOGNIZED:{enter:function(){i.start(),i.emit("tap",i,i.gameObject,i.lastPointer),i.emit(`${i.tapsCount}tap`,i,i.gameObject,i.lastPointer)}}},init:function(){this.state=py},eventEmitter:!1};this.setRecongizedStateObject(new $f(s))}resetFromJSON(t){super.resetFromJSON(t),this.setHoldTime(dy(t,"time",250)),this.setTapInterval(dy(t,"tapInterval",200)),this.setDragThreshold(dy(t,"threshold",9)),this.setTapOffset(dy(t,"tapOffset",10));var e=dy(t,"taps",void 0);return void 0!==e?this.setTaps(e):(this.setMaxTaps(dy(t,"maxTaps",void 0)),this.setMinTaps(dy(t,"minTaps",void 0))),this}onDragStart(){switch(this.state){case py:this.state=gy;break;case gy:var t=this.lastPointer;cy(t.upX,t.upY,t.x,t.y)>this.tapOffset&&(this.state=vy,this.state=gy);break;case vy:this.state=gy}}onDragEnd(){this.state===gy&&(this.tapsCount++,this.emit("tapping",this,this.gameObject,this.lastPointer),void 0!==this.maxTaps&&this.tapsCount===this.maxTaps&&(this.state=vy))}onDrag(){this.state!==py&&this.pointer.getDistance()>this.dragThreshold&&(this.state=py)}preUpdate(t,e){if(this.isRunning&&this.enable&&this.state===gy){var i=this.lastPointer;i.isDown?t-i.downTime>this.holdTime&&(this.state=py):t-i.upTime>this.tapInterval&&(void 0===this.minTaps||this.tapsCount>=this.minTaps?this.state=vy:this.state=py)}}postUpdate(t,e){this.isRunning&&this.enable&&this.state===vy&&(this.state=py)}get isTapped(){return this.state===vy}setHoldTime(t){return this.holdTime=t,this}setTapInterval(t){return this.tapInterval=t,this}setDragThreshold(t){return this.dragThreshold=t,this}setTapOffset(t){return this.tapOffset=t,this}setMaxTaps(t){return this.maxTaps=t,this}setMinTaps(t){return this.minTaps=t,this}setTaps(t,e){return void 0===e&&(e=t),this.setMinTaps(t).setMaxTaps(e),this}}const py="IDLE",gy="BEGIN",vy="RECOGNIZED",fy=Phaser.Utils.Objects.GetValue;class my extends ay{constructor(t,e){super(t,e);var i=this,s={states:{IDLE:{enter:function(){i.x=0,i.y=0,i.worldX=0,i.worldY=0,i.lastPointer=void 0},exit:function(){var t=i.lastPointer;i.x=t.x,i.y=t.y,i.worldX=t.worldX,i.worldY=t.worldY}},BEGIN:{enter:function(){i.start()},exit:function(){i.stop()}},RECOGNIZED:{enter:function(){i.emit("pressstart",i,i.gameObject,i.lastPointer)},exit:function(){i.emit("pressend",i,i.gameObject,i.lastPointer)}}},init:function(){this.state=yy},eventEmitter:!1};this.setRecongizedStateObject(new $f(s))}resetFromJSON(t){return super.resetFromJSON(t),this.setDragThreshold(fy(t,"threshold",9)),this.setHoldTime(fy(t,"time",251)),this}onDragStart(){this.state=by,0===this.holdTime&&(this.state=xy)}onDragEnd(){this.state=yy}onDrag(){this.state!==yy&&this.pointer.getDistance()>this.dragThreshold&&(this.state=yy)}preUpdate(t,e){this.isRunning&&this.enable&&this.state===by&&t-this.pointer.downTime>=this.holdTime&&(this.state=xy)}get isPressed(){return this.state===xy}setHoldTime(t){return this.holdTime=t,this}setDragThreshold(t){return this.dragThreshold=t,this}}const yy="IDLE",by="BEGIN",xy="RECOGNIZED",Cy=Phaser.Utils.Objects.GetValue;class ky extends ay{constructor(t,e){super(t,e);var i=this,s={states:{IDLE:{},BEGIN:{enter:function(){var t=i.pointer;i.startX=t.x,i.startY=t.y,i.startWorldX=t.worldX,i.startWorldY=t.worldY}},RECOGNIZED:{enter:function(){i.emit("panstart",i,i.gameObject,i.lastPointer)},exit:function(){var t=i.lastPointer;i.endX=t.x,i.endY=t.y;var e=wm(t,i.pointerCamera,!0);i.endWorldX=e.x,i.endWorldY=e.y,i.emit("panend",i,i.gameObject,i.lastPointer)}}},init:function(){this.state=wy},eventEmitter:!1};this.setRecongizedStateObject(new $f(s))}resetFromJSON(t){return super.resetFromJSON(t),this.setDragThreshold(Cy(t,"threshold",10)),this}onDragStart(){this.state=Sy,0===this.dragThreshold&&(this.state=Py)}onDragEnd(){this.state=wy}onDrag(){switch(this.state){case Sy:if(this.pointer.getDistance()>=this.dragThreshold){this.state=Py,this.dx=0,this.dy=0,this.dWorldX=0,this.dWorldY=0;var t=this.pointer;this.x=t.x,this.y=t.y,this.worldX=t.worldX,this.worldY=t.worldY}break;case Py:var e=this.pointerCamera,i=this.pointer.position,s=this.pointer.prevPosition;this.dx=i.x-s.x,this.dy=i.y-s.y,this.dWorldX=this.dx/e.zoom,this.dWorldY=this.dy/e.zoom,t=this.pointer,this.x=t.x,this.y=t.y;var r=wm(t,e,!0);this.worldX=r.x,this.worldY=r.y,this.emit("pan",this,this.gameObject,this.lastPointer)}}get isPanned(){return this.state===Py}setDragThreshold(t){return this.dragThreshold=t,this}}const wy="IDLE",Sy="BEGIN",Py="RECOGNIZED",Ty=Phaser.Math.Distance.Between,Oy=Phaser.Math.Angle.Between;var My={getDt:function(){return rc(this.scene)},getVelocity:function(){var t=this.pointer.position,e=this.pointer.prevPosition;return Ty(e.x,e.y,t.x,t.y)/(.001*this.getDt())},getVelocityX:function(){var t=this.pointer.position,e=this.pointer.prevPosition;return Math.abs(t.x-e.x)/(.001*this.getDt())},getVelocityY:function(){var t=this.pointer.position,e=this.pointer.prevPosition;return Math.abs(t.y-e.y)/(.001*this.getDt())},getVelocityAngle:function(){var t=this.pointer.position,e=this.pointer.prevPosition;return Oy(e.x,e.y,t.x,t.y)}},Ey={"up&down":0,"left&right":1,"4dir":2,"8dir":3},_y={};const Ry=Phaser.Utils.Objects.GetValue,Ly=Phaser.Math.RadToDeg;class By extends ay{constructor(t,e){super(t,e);var i=this,s={states:{IDLE:{enter:function(){i.x=0,i.y=0,i.worldX=0,i.worldY=0},exit:function(){var t=i.lastPointer;i.x=t.x,i.y=t.y,i.worldX=t.worldX,i.worldY=t.worldY}},BEGIN:{enter:function(){i.validDrag=!1}},RECOGNIZED:{enter:function(){i.start(),i.updateDirectionStates(),i.emit("swipe",i,i.gameObject,i.lastPointer)},exit:function(){i.stop(),i.clearDirectionStates()}}},init:function(){this.state=Iy},eventEmitter:!1};this.setRecongizedStateObject(new $f(s)),this.clearDirectionStates()}resetFromJSON(t){return super.resetFromJSON(t),this.setDragThreshold(Ry(t,"threshold",10)),this.setVelocityThreshold(Ry(t,"velocityThreshold",1e3)),this.setDirectionMode(Ry(t,"dir","8dir")),this}onDragStart(){this.state=Dy}onDragEnd(){this.state=Iy}onDrag(){this.state===Dy&&(this.validDrag||(this.validDrag=0===this.dragThreshold||this.pointer.getDistance()>=this.dragThreshold),this.validDrag&&this.dragVelocity>this.velocityThreshold&&(this.state=jy))}postUpdate(t,e){this.isRunning&&this.enable&&this.state===jy&&(this.state=Iy)}get isSwiped(){return this.state===jy}get dragVelocity(){var t;switch(this.dirMode){case 0:t=this.getVelocityY();break;case 1:t=this.getVelocityX();break;default:t=this.getVelocity()}return t}setDragThreshold(t){return this.dragThreshold=t,this}setVelocityThreshold(t){return this.velocityThreshold=t,this}setDirectionMode(t){return"string"==typeof t&&(t=Ey[t]),this.dirMode=t,this}updateDirectionStates(){return function(t,e,i){switch(void 0===i?i={}:!0===i&&(i=_y),i.left=!1,i.right=!1,i.up=!1,i.down=!1,t=(t+360)%360,e){case 0:t<180?i.down=!0:i.up=!0;break;case 1:t>90&&t<=270?i.left=!0:i.right=!0;break;case 2:t>45&&t<=135?i.down=!0:t>135&&t<=225?i.left=!0:t>225&&t<=315?i.up=!0:i.right=!0;break;case 3:t>22.5&&t<=67.5?(i.down=!0,i.right=!0):t>67.5&&t<=112.5?i.down=!0:t>112.5&&t<=157.5?(i.down=!0,i.left=!0):t>157.5&&t<=202.5?i.left=!0:t>202.5&&t<=247.5?(i.left=!0,i.up=!0):t>247.5&&t<=292.5?i.up=!0:t>292.5&&t<=337.5?(i.up=!0,i.right=!0):i.right=!0}}(Ly(this.getVelocityAngle()),this.dirMode,this),this}clearDirectionStates(){return this.left=!1,this.right=!1,this.up=!1,this.down=!1,this}}Object.assign(By.prototype,My);const Iy="IDLE",Dy="BEGIN",jy="RECOGNIZED",Ay=Phaser.Utils.Objects.GetValue,zy=Phaser.Utils.Array.SpliceOne,Fy=Phaser.Math.Distance.Between,Yy=Phaser.Math.Angle.Between;class Xy{constructor(t,e){var i=Ea(t);i===t&&(t=void 0);var s=i.input.manager.pointersTotal-1;s<2&&i.input.addPointer(2-s),this.scene=i,this.gameObject=t,t&&t.setInteractive(Ay(e,"inputConfig",void 0)),this.setEventEmitter(Ay(e,"eventEmitter",void 0)),this._enable=void 0,this.pointers=[],this.movedState={},this.resetFromJSON(e),this.boot()}resetFromJSON(t){return this.setEnable(Ay(t,"enable",!0)),this.bounds=Ay(t,"bounds",void 0),this.tracerState=Vy,this.pointers.length=0,q(this.movedState),this}boot(){this.gameObject?this.gameObject.on("pointerdown",this.onPointerDown,this):this.scene.input.on("pointerdown",this.onPointerDown,this),this.scene.input.on("pointerup",this.onPointerUp,this),this.scene.input.on("gameout",this.dragCancel,this),this.scene.input.on("pointermove",this.onPointerMove,this),this.scene.sys.events.once("shutdown",this.destroy,this)}shutdown(){this.scene&&(this.destroyEventEmitter(),this.pointers.length=0,q(this.movedState),this.gameObject||this.scene.input.off("pointerdown",this.onPointerDown,this),this.scene.input.off("pointerup",this.onPointerUp,this),this.scene.input.off("gameout",this.dragCancel,this),this.scene.input.off("pointermove",this.onPointerMove,this),this.scene.sys.events.off("shutdown",this.destroy,this),this.scene=void 0,this.gameObject=void 0)}destroy(){this.shutdown()}get enable(){return this._enable}set enable(t){if(this._enable!==t)return t||this.dragCancel(),this._enable=t,this}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}toggleEnable(){return this.setEnable(!this.enable),this}onPointerDown(t){if(this.enable&&2!==this.pointers.length&&(!this.bounds||this.bounds.contains(t.x,t.y))&&-1===this.pointers.indexOf(t))switch(this.movedState[t.id]=!1,this.pointers.push(t),this.pointerCamera=t.camera,this.tracerState){case Vy:this.tracerState=Gy,this.onDrag1Start();break;case Gy:this.tracerState=Hy,this.onDrag2Start()}}onPointerUp(t){if(this.enable&&(!this.bounds||this.bounds.contains(t.x,t.y))){var e=this.pointers.indexOf(t);if(-1!==e)switch(delete this.movedState[t.id],zy(this.pointers,e),this.tracerState){case Gy:this.tracerState=Vy,this.onDrag1End();break;case Hy:this.tracerState=Gy,this.onDrag2End(),this.onDrag1Start()}}}onPointerMove(t){if(this.enable&&t.isDown){var e=!this.bounds||this.bounds.contains(t.x,t.y),i=-1!==this.pointers.indexOf(t);if(!i&&e);else if(i&&!e)this.onPointerUp(t);else if(this.movedState[t.id]||(this.movedState[t.id]=t.x!==t.downX||t.y!==t.downY),this.movedState[t.id])switch(this.tracerState){case Gy:this.onDrag1();break;case Hy:this.onDrag2()}}}dragCancel(){return this.tracerState===Hy&&this.onDrag2End(),this.pointers.length=0,q(this.movedState),this.tracerState=Vy,this}onDrag1Start(){this.emit("drag1start",this)}onDrag1End(){this.emit("drag1end",this)}onDrag1(){this.emit("drag1",this)}onDrag2Start(){this.emit("drag2start",this)}onDrag2End(){this.emit("drag2end",this)}onDrag2(){this.emit("drag2",this)}get distanceBetween(){if(this.tracerState!==Hy)return 0;var t=this.pointers[0],e=this.pointers[1];return Fy(t.x,t.y,e.x,e.y)}get angleBetween(){if(this.tracerState!==Hy)return 0;var t=this.pointers[0],e=this.pointers[1];return Yy(t.x,t.y,e.x,e.y)}get drag1Vector(){var t=this.pointers[0];if(t&&this.movedState[t.id]){var e=t.position,i=t.prevPosition;Wy.x=e.x-i.x,Wy.y=e.y-i.y}else Wy.x=0,Wy.y=0;return Wy}get centerX(){if(this.tracerState!==Hy)return 0;var t=this.pointers[0].position,e=this.pointers[1].position;return(t.x+e.x)/2}get centerY(){if(this.tracerState!==Hy)return 0;var t=this.pointers[0].position,e=this.pointers[1].position;return(t.y+e.y)/2}get prevCenterX(){if(this.tracerState!==Hy)return 0;var t=this.movedState[this.pointers[0].id]?this.pointers[0].prevPosition:this.pointers[0].position,e=this.movedState[this.pointers[1].id]?this.pointers[1].prevPosition:this.pointers[1].position;return(t.x+e.x)/2}get prevCenterY(){if(this.tracerState!==Hy)return 0;var t=this.movedState[this.pointers[0].id]?this.pointers[0].prevPosition:this.pointers[0].position,e=this.movedState[this.pointers[1].id]?this.pointers[1].prevPosition:this.pointers[1].position;return(t.y+e.y)/2}get movementCenterX(){return this.centerX-this.prevCenterX}get movementCenterY(){return this.centerY-this.prevCenterY}setRecongizedStateObject(t){return this.recongizedState=t,this}get state(){return this.recongizedState.state}set state(t){this.recongizedState.state=t}cancel(){return this.state=Uy,this}isPointer0InGameObject(t,e,i){var s=this.pointers[0];return!!s&&Pm(t,s,e,i)}isPointer1InGameObject(t,e,i){var s=this.pointers[1];return!!s&&Pm(t,s,e,i)}}Object.assign(Xy.prototype,ln);var Wy={};const Vy=0,Gy=1,Hy=2,Uy="IDLE",Ny=Phaser.Utils.Objects.GetValue;class $y extends Xy{constructor(t,e){super(t,e);var i=this,s={states:{IDLE:{enter:function(){i.prevDistance=void 0,i.scaleFactor=1}},BEGIN:{},RECOGNIZED:{enter:function(){i.emit("pinchstart",i)},exit:function(){i.emit("pinchend",i)}}},init:function(){this.state=Ky},eventEmitter:!1};this.setRecongizedStateObject(new $f(s))}resetFromJSON(t){return super.resetFromJSON(t),this.setDragThreshold(Ny(t,"threshold",0)),this}onDrag2Start(){this.scaleFactor=1,this.prevDistance=this.distanceBetween,this.state=Jy,0===this.dragThreshold&&(this.state=qy)}onDrag2End(){this.state=Ky}onDrag2(){switch(this.state){case Jy:if(this.pointers[0].getDistance()>=this.dragThreshold&&this.pointers[1].getDistance()>=this.dragThreshold){var t=this.distanceBetween;this.scaleFactor=t/this.prevDistance,this.prevDistance=t,this.state=qy}break;case qy:t=this.distanceBetween,this.scaleFactor=t/this.prevDistance,this.emit("pinch",this),this.prevDistance=t}}get isPinched(){return this.state===qy}setDragThreshold(t){return this.dragThreshold=t,this}}const Ky="IDLE",Jy="BEGIN",qy="RECOGNIZED",Zy=Phaser.Math.RotateAround;var Qy=function(t,e,i,s){return Zy(t,e,i,s),t.rotation+=s,t},tb={};const eb=Phaser.Utils.Objects.GetValue,ib=Phaser.Math.Angle.WrapDegrees,sb=Phaser.Math.Angle.ShortestBetween,rb=Phaser.Math.RadToDeg,nb=Phaser.Math.DegToRad;class ab extends Xy{constructor(t,e){super(t,e);var i=this,s={states:{IDLE:{enter:function(){i.prevAngle=void 0,i.angle=0}},BEGIN:{},RECOGNIZED:{enter:function(){i.emit("rotatestart",i)},exit:function(){i.emit("rotateend",i)}}},init:function(){this.state=hb},eventEmitter:!1};this.setRecongizedStateObject(new $f(s))}resetFromJSON(t){return super.resetFromJSON(t),this.setDragThreshold(eb(t,"threshold",0)),this}onDrag2Start(){this.prevAngle=ib(rb(this.angleBetween)),this.state=lb,0===this.dragThreshold&&(this.state=db)}onDrag2End(){this.state=hb}onDrag2(){switch(this.state){case lb:if(this.pointers[0].getDistance()>=this.dragThreshold&&this.pointers[1].getDistance()>=this.dragThreshold){var t=ib(rb(this.angleBetween));this.angle=sb(this.prevAngle,t),this.prevAngle=t,this.state=db}break;case db:t=ib(rb(this.angleBetween)),this.angle=sb(this.prevAngle,t),this.prevAngle=t,this.emit("rotate",this)}}get isRotated(){return this.state===db}get rotation(){return nb(this.angle)}setDragThreshold(t){return this.dragThreshold=t,this}}var ob={spinObject:function(t,e){if(!this.isRotation)return this;void 0===e&&(e=this.pointers[0].camera);var i=this.movementCenterX,s=this.movementCenterY,r=function(t,e,i,s){return void 0===s?s={}:!0===s&&(s=tb),i.getWorldPoint(t,e,s),s}(this.centerX,this.centerY,e,!0),n=r.x,a=r.y,o=this.rotation;if(Array.isArray(t))for(var h=t,l=0,d=h.length;l0&&(r=!0,void 0===n&&(n=0),void 0===a&&(a=0)),(d=this.getSizerConfig(t)).align=i,d.padding=gv(s),Mb(r)?(d.expandWidth=Eb(r,"width",!1),d.expandHeight=Eb(r,"height",!1)):(d.expandWidth=r,d.expandHeight=r),t.isRexSizer||(d.expandWidth&&(t.minWidth=void 0===n?An(t):n),d.expandHeight&&(t.minHeight=void 0===a?zn(t):a)),d.alignOffsetX=o,d.alignOffsetY=h,d.aspectRatio=l,this.sizerChildren.hasOwnProperty(e)&&this.sizerChildren[e].destroy(),this.sizerChildren[e]=t,c&&this.addChildrenMap(e,t),this}};const Bb=Dg.prototype.clear;var Ib=function(t){this.backgroundChildren&&(this.backgroundChildren.length=0);var e,i=!t&&this.sizerEventsEnable;if(i&&(e=this.getChildren([])),Bb.call(this,t),i)for(var s,r=0,n=e.length;r0&&(Tb.width=e.aspectRatio,Tb.height=1,Ob.width=o,Ob.height=h,o=(l=kb(Tb,Ob,"FIT",!0)).width,h=l.height),t.isRexSizer?(t.runLayout(this,o,h),Pb(t,this)):Yv(t,o,h),s=d+i.left*this.scaleX,n=u-(i.left+i.right)*this.scaleX,r=c+i.top*this.scaleY,a=p-(i.top+i.bottom)*this.scaleY,Lm.call(this,t,s,r,n,a,e.align,e.alignOffsetX,e.alignOffsetY))}};Object.assign(jb,Lb,Db);var Ab=function(t,e){if(Array.isArray(t))return t.indexOf(e);for(var i in t)if(t[i]===e)return i;return null};const zb=Phaser.Utils.Objects.IsPlainObject,Fb=Phaser.Utils.Objects.GetValue;class Yb extends Cb{constructor(t,e,i,s,r,n){zb(e)?(e=Fb(n=e,"x",0),i=Fb(n,"y",0),s=Fb(n,"width",void 0),r=Fb(n,"height",void 0)):zb(s)&&(s=Fb(n=s,"width",void 0),r=Fb(n,"height",void 0)),super(t,e,i,s,r,n),this.type="rexOverlapSizer",this.sizerChildren={},this.addChildrenMap("items",this.sizerChildren)}childToKey(t){if("string"!=typeof t)return Ab(this.sizerChildren,t);var e=t;return this.sizerChildren.hasOwnPropery(e)?e:null}}Object.assign(Yb.prototype,jb);var Xb=Phaser.Math.Distance.Between,Wb=function(t,e,i){var s=t.width/2;return Xb(s,s,e,i)<=s};const Vb=Phaser.Math.Angle.Between,Gb=Phaser.Math.Angle.Normalize;var Hb=function(t,e,i){if(this.enable&&t.isDown){var s=this.sizerChildren.knob;if(Wb(s,e,i)){var r=s.width/2,n=s.startAngle,a=Vb(r,r,e,i),o=s.anticlockwise?n-a:a-n,h=Gb(o)/(2*Math.PI);this.stopEaseValue(),0===this.easeValueDuration||Math.abs(this.value-h)<.1?this.value=h:this.easeValueTo(h)}}},Ub=function(){this.sizerChildren.knob.on("pointerdown",Hb,this).on("pointermove",Hb,this).setInteractive()};const Nb=Phaser.Math.Angle.Between,$b=Phaser.Math.Angle.Wrap;var Kb=function(t,e,i){if(this.enable&&!this.panPointer){var s=this.sizerChildren.knob;Wb(s,e,i)&&Zb.call(this,t)}},Jb=function(t,e,i){if(this.enable&&t.isDown){var s=this.sizerChildren.knob;switch(this.panState){case ex:Wb(s,e,i)&&Zb.call(this,t);break;case ix:Wb(s,e,i)?tx.call(this):Qb.call(this)}}},qb=function(t,e,i){this.enable&&this.panPointer===t&&Qb.call(this)},Zb=function(t){this.panPointer=t,this.panState=ix},Qb=function(){this.panPointer=void 0,this.panState=ex},tx=function(){var t=this.panPointer.prevPosition,e=this.panPointer.position,i=this.sizerChildren.knob,s=Nb(i.x,i.y,t.x,t.y),r=Nb(i.x,i.y,e.x,e.y),n=i.anticlockwise?s-r:r-s,a=$b(n)/(2*Math.PI);this.stopEaseValue(),this.value+=a};const ex=0,ix=1;var sx=function(){this.sizerChildren.knob.on("pointerdown",Kb,this).on("pointermove",Jb,this).on("pointerup",qb,this).setInteractive(),this.panPointer=void 0,this.panState=ex},rx=function(t){return void 0===t&&(t=this.value),this.textFormatCallbackScope?this.textFormatCallback(t):this.textFormatCallback.call(this.textFormatCallbackScope,t)},nx={setTextFormatCallback:function(t,e){return this.textFormatCallback=t,this.textFormatCallbackScope=e,this},getFormatText:rx,updateText:function(t){var e=this.sizerChildren.text;return e&&this.textFormatCallback&&(e.setText(rx.call(this,t)),e.layout&&e.layout()),this}};const ax=Phaser.Utils.Objects.GetValue,ox=Phaser.Math.Snap.To;class hx extends(Xu(Yb)){constructor(t,e){void 0===e&&(e={}),super(t,e),this.type="rexKnob",this.bootProgressBase(e);var i=ax(e,"background",void 0),s=ax(e,"text",void 0);i&&this.addBackground(i),s&&(e.textColor=void 0,e.textStrokeColor=void 0,this.setTextFormatCallback(ax(e,"textFormatCallback",void 0),ax(e,"textFormatCallbackScope",void 0)),e.textFormatCallback=void 0,e.textFormatCallbackScope=void 0);var r=new np(t,e);r.setDepth(ax(e,"knobDepth",0)),r._value=-1,t.add.existing(r),this.add(r,"knob"),s&&(this.add(s,"text","center",0,!1),t.children.moveBelow(r,s)),this.addChildrenMap("background",i),this.addChildrenMap("knob",r),this.addChildrenMap("text",s),this.setEnable(ax(e,"enable",void 0)),this.setGap(ax(e,"gap",void 0)),this.setValue(ax(e,"value",0),ax(e,"min",void 0),ax(e,"max",void 0));var n=ax(e,"input",0);switch("string"==typeof n&&(n=lx[n]),n){case 0:sx.call(this);break;case 1:Ub.call(this)}}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}setGap(t){return this.gap=t,this}get value(){return this.sizerChildren.knob.value}set value(t){void 0!==this.gap&&(t=ox(t,this.gap));var e=this.value;this.sizerChildren.knob.value=t;var i=this.value;e!==i&&(this.updateText(),this.eventEmitter.emit("valuechange",i,e,this.eventEmitter))}}const lx={pan:0,drag:0,click:1,none:-1};Object.assign(hx.prototype,nx),t.register("knob",(function(t){var e=new hx(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.Knob",hx);const dx={arc:Cc,circle:kc,curve:class extends bc{constructor(t){super(),this.setCurve(t),this.setIterations(32)}get curve(){return this._curve}set curve(t){this.dirty=this.dirty||this._curve!==t,this._curve=t}setCurve(t){return this.curve=t,this}get iterations(){return this._iterations}set iterations(t){this.dirty=this.dirty||this._iterations!==t,this._iterations=t}setIterations(t){return this.iterations=t,this}updateData(){this.pathData.length=0;for(var t=this.curve.getPoints(this.iterations),e=0,i=t.length;ethis.value)for(var d=0;dthis.value&&(t+=1));for(var r=this.getShapes(),n=0,a=r.length;n0?d.pop().setTexture(u,O):r(c,u,O),h&&c.add.existing(T),l){var M=b+k*P+a*k,E=x+w*S+o*w;T.setOrigin(a,o).setPosition(M,E).setScale(v,f).setRotation(m),HC(T,b,x,m)}C.push(T)}return C}(t,e,i,s),a=0,o=n.length;a0&&(a=this.getChildLocalScaleX(s),a/=s.biasScale,this.setChildLocalScale(s,a)),r.biasScale&&(a=this.getChildLocalScaleX(r),a/=r.biasScale,this.setChildLocalScale(r,a))),e?t.call(e,i,s,r,n):t(i,s,r,n),this.scaleMode&&(s.biasScale>0&&(a=this.getChildLocalScaleX(s),a*=s.biasScale,this.setChildLocalScale(s,a)),r.biasScale&&(a=this.getChildLocalScaleX(r),a*=r.biasScale,this.setChildLocalScale(r,a))))};Object.assign(ek.prototype,$C);const sk={fit:1,FIT:1,envelop:2,ENVELOP:2};t.register("transitionImage",(function(t,e,i,s,r){var n=new ek(this.scene,t,e,i,s,r);return this.scene.add.existing(n),n})),P(window,"RexPlugins.UI.TransitionImage",ek);const rk=Phaser.Renderer.WebGL.Pipelines.PostFXPipeline,nk=Phaser.Utils.Objects.GetValue,ak=Phaser.Math.Clamp;class ok extends rk{constructor(t){super({name:"rexDissolvePostFx",game:t,renderTarget:!0,fragShader:"#ifdef GL_FRAGMENT_PRECISION_HIGH\n#define highmedp highp\n#else\n#define highmedp mediump\n#endif\nprecision highmedp float;\n// Scene buffer\nuniform sampler2D uMainSampler;\nuniform sampler2D uMainSampler2;\n\nuniform int resizeMode;\nuniform float progress;\nuniform float fromRatio;\nuniform float toRatio;\nvarying vec2 outFragCoord;\n// Effect parameters\nuniform float noiseX;\nuniform float noiseY;\nuniform float noiseZ;\nuniform float fromEdgeStart;\nuniform float fromEdgeWidth;\nuniform float toEdgeStart;\nuniform float toEdgeWidth;\n\nvec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }\nvec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }\nvec4 permute(vec4 x) { return mod289(((x*34.0)+1.0)*x); }\nvec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }\nvec3 fade(vec3 t) { return t*t*t*(t*(t*6.0-15.0)+10.0); }\nfloat Perlin(vec3 P) {\n vec3 i0 = mod289(floor(P)), i1 = mod289(i0 + vec3(1.0));\n vec3 f0 = fract(P), f1 = f0 - vec3(1.0), f = fade(f0);\n vec4 ix = vec4(i0.x, i1.x, i0.x, i1.x), iy = vec4(i0.yy, i1.yy);\n vec4 iz0 = i0.zzzz, iz1 = i1.zzzz;\n vec4 ixy = permute(permute(ix) + iy), ixy0 = permute(ixy + iz0), ixy1 = permute(ixy + iz1);\n vec4 gx0 = ixy0 * (1.0 / 7.0), gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5;\n vec4 gx1 = ixy1 * (1.0 / 7.0), gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5;\n gx0 = fract(gx0); gx1 = fract(gx1);\n vec4 gz0 = vec4(0.5) - abs(gx0) - abs(gy0), sz0 = step(gz0, vec4(0.0));\n vec4 gz1 = vec4(0.5) - abs(gx1) - abs(gy1), sz1 = step(gz1, vec4(0.0));\n gx0 -= sz0 * (step(0.0, gx0) - 0.5); gy0 -= sz0 * (step(0.0, gy0) - 0.5);\n gx1 -= sz1 * (step(0.0, gx1) - 0.5); gy1 -= sz1 * (step(0.0, gy1) - 0.5);\n vec3 g0 = vec3(gx0.x,gy0.x,gz0.x), g1 = vec3(gx0.y,gy0.y,gz0.y),\n g2 = vec3(gx0.z,gy0.z,gz0.z), g3 = vec3(gx0.w,gy0.w,gz0.w),\n g4 = vec3(gx1.x,gy1.x,gz1.x), g5 = vec3(gx1.y,gy1.y,gz1.y),\n g6 = vec3(gx1.z,gy1.z,gz1.z), g7 = vec3(gx1.w,gy1.w,gz1.w);\n vec4 norm0 = taylorInvSqrt(vec4(dot(g0,g0), dot(g2,g2), dot(g1,g1), dot(g3,g3)));\n vec4 norm1 = taylorInvSqrt(vec4(dot(g4,g4), dot(g6,g6), dot(g5,g5), dot(g7,g7)));\n g0 *= norm0.x; g2 *= norm0.y; g1 *= norm0.z; g3 *= norm0.w;\n g4 *= norm1.x; g6 *= norm1.y; g5 *= norm1.z; g7 *= norm1.w;\n vec4 nz = mix(vec4(dot(g0, vec3(f0.x, f0.y, f0.z)), dot(g1, vec3(f1.x, f0.y, f0.z)),\n dot(g2, vec3(f0.x, f1.y, f0.z)), dot(g3, vec3(f1.x, f1.y, f0.z))),\n vec4(dot(g4, vec3(f0.x, f0.y, f1.z)), dot(g5, vec3(f1.x, f0.y, f1.z)),\n dot(g6, vec3(f0.x, f1.y, f1.z)), dot(g7, vec3(f1.x, f1.y, f1.z))), f.z);\n return 2.2 * mix(mix(nz.x,nz.z,f.y), mix(nz.y,nz.w,f.y), f.x);\n}\nfloat Perlin(vec2 P) { return Perlin(vec3(P, 0.0)); }\n\n\nvec4 getFromColor (vec2 uv) {\n return texture2D(uMainSampler, uv);\n}\n\nvec4 getToColor (vec2 uv) {\n if (resizeMode == 2) {\n // cover\n return texture2D(uMainSampler2, 0.5 + (vec2(uv.x, 1.0 - uv.y) - 0.5) * vec2(min(fromRatio / toRatio, 1.0), min((toRatio / fromRatio), 1.0)));\n } else if (resizeMode == 1) {\n // contain\n return texture2D(uMainSampler2, 0.5 + (vec2(uv.x, 1.0 - uv.y) - 0.5) * vec2(max(fromRatio / toRatio, 1.0), max((toRatio / fromRatio), 1.0)));\n } else {\n // stretch\n return texture2D(uMainSampler2, vec2(uv.x, 1.0 - uv.y));\n }\n}\n\nvec4 transition (vec2 uv) { \n vec4 colorFront = getFromColor(uv);\n vec4 colorTo = getToColor(uv);\n\n float noise = (Perlin(vec3(uv.x * noiseX, uv.y * noiseY, noiseZ)) + 1.0) / 2.0\n * (1.0 - (fromEdgeStart + fromEdgeWidth + toEdgeStart + toEdgeWidth))\n + (fromEdgeStart + fromEdgeWidth + toEdgeStart + toEdgeWidth) * 0.5;\n vec4 colorResult = colorFront * smoothstep(progress - (fromEdgeStart + fromEdgeWidth), progress - fromEdgeStart, noise)\n + colorTo * smoothstep((1.0 - progress) - (toEdgeStart + toEdgeWidth), (1.0 - progress) - toEdgeStart, (1.0 - noise));\n return colorResult;\n}\n\nvoid main () {\n vec2 uv = outFragCoord;\n gl_FragColor = transition(uv);\n}\n"}),this._progress=0,this.toFrame=null,this.targetTexture=null,this.resizeMode=1,this.toRatio=1,this.noiseX=0,this.noiseY=0,this.noiseZ=0,this.fromEdgeStart=.01,this.fromEdgeWidth=.05,this.toEdgeStart=.01,this.toEdgeWidth=.05}resetFromJSON(t){return this.setProgress(nk(t,"progress",0)),this.setTransitionTargetTexture(nk(t,"toTexture","__DEFAULT"),nk(t,"toFrame",void 0),nk(t,"resizeMode",1)),this.setNoise(nk(t,"noiseX",void 0),nk(t,"noiseY",void 0),nk(t,"noiseZ",void 0)),this.setFromEdge(nk(t,"fromEdgeStart",.01),nk(t,"fromEdgeWidth",.05)),this.setToEdge(nk(t,"toEdgeStart",.01),nk(t,"toEdgeWidth",.05)),this}onBoot(){}onPreRender(){this.set1f("progress",this.progress),this.set1i("resizeMode",this.resizeMode),this.set1f("noiseX",this.noiseX),this.set1f("noiseY",this.noiseY),this.set1f("noiseZ",this.noiseZ),this.set1f("fromEdgeStart",this.fromEdgeStart),this.set1f("fromEdgeWidth",this.fromEdgeWidth),this.set1f("toEdgeStart",this.toEdgeStart),this.set1f("toEdgeWidth",this.toEdgeWidth)}onDraw(t){this.set1f("fromRatio",t.width/t.height),this.set1f("toRatio",this.toRatio),this.set1i("uMainSampler2",1),this.bindTexture(this.targetTexture,1),this.bindAndDraw(t)}get progress(){return this._progress}set progress(t){this._progress=ak(t,0,1)}setProgress(t){return this.progress=t,this}setTransitionTargetTexture(t,e,i){void 0===t&&(t="__DEFAULT");var s=this.game.textures.getFrame(t,e);return s||(s=this.game.textures.getFrame("__DEFAULT")),this.toRatio=s.width/s.height,this.toFrame=s,this.targetTexture=s.glTexture,void 0!==i&&(this.resizeMode=i),this}setResizeMode(t){return"string"==typeof t&&(t=hk[t]),this.resizeMode=t,this}setNoise(t,e,i){return void 0===t&&(t=4+6*Math.random()),void 0===e&&(e=4+6*Math.random()),void 0===i&&(i=10*Math.random()),this.noiseX=t,this.noiseY=e,this.noiseZ=i,this}setFromEdge(t,e){return this.fromEdgeStart=t,this.fromEdgeWidth=e,this}setToEdge(t,e){return this.toEdgeStart=t,this.toEdgeWidth=e,this}}var hk={stretch:0,contain:1,cover:2};const lk=Phaser.Utils.Array.SpliceOne,dk=.1,ck=[function(t){t.addTransitionMode("slideAwayRight",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.width*s;t.setChildLocalPosition(e,r,0)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0)}}).addTransitionMode("slideAwayLeft",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.width*-s;t.setChildLocalPosition(e,r,0)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0)}}).addTransitionMode("slideAwayDown",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.height*s;t.setChildLocalPosition(e,0,r)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0)}}).addTransitionMode("slideAwayUp",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.height*-s;t.setChildLocalPosition(e,0,r)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0)}})},function(t){t.addTransitionMode("slideRight",{ease:"Linear",dir:"in",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=i.width*(s-1);t.setChildLocalPosition(i,r,0)},onComplete:function(t,e,i,s){t.setChildLocalPosition(i,0,0)}}).addTransitionMode("slideLeft",{ease:"Linear",dir:"in",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=i.width*(1-s);t.setChildLocalPosition(i,r,0)},onComplete:function(t,e,i,s){t.setChildLocalPosition(i,0,0)}}).addTransitionMode("slideDown",{ease:"Linear",dir:"in",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=i.height*(s-1);t.setChildLocalPosition(i,0,r)},onComplete:function(t,e,i,s){t.setChildLocalPosition(i,0,0)}}).addTransitionMode("slideUp",{ease:"Linear",dir:"in",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=i.height*(1-s);t.setChildLocalPosition(i,0,r)},onComplete:function(t,e,i,s){t.setChildLocalPosition(i,0,0)}})},function(t){t.addTransitionMode("pushRight",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.width*s;t.setChildLocalPosition(e,r,0),r=i.width*(s-1),t.setChildLocalPosition(i,r,0)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0),t.setChildLocalPosition(i,0,0)}}).addTransitionMode("pushLeft",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.width*-s;t.setChildLocalPosition(e,r,0),r=i.width*(1-s),t.setChildLocalPosition(i,r,0)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0),t.setChildLocalPosition(i,0,0)}}).addTransitionMode("pushDown",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.height*s;t.setChildLocalPosition(e,0,r),r=i.height*(s-1),t.setChildLocalPosition(i,0,r)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0),t.setChildLocalPosition(i,0,0)}}).addTransitionMode("pushUp",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.height*-s;t.setChildLocalPosition(e,0,r),r=i.height*(1-s),t.setChildLocalPosition(i,0,r)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0),t.setChildLocalPosition(i,0,0)}})},function(t){t.addTransitionMode("zoomOut",{ease:"Linear",dir:"out",mask:!1,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=1-s;t.setChildLocalScale(e,r,r)},onComplete:function(t,e,i,s){t.setChildLocalScale(e,1,1)}}).addTransitionMode("zoomIn",{ease:"Linear",dir:"in",mask:!1,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=s;t.setChildLocalScale(i,r,r)},onComplete:function(t,e,i,s){t.setChildLocalScale(i,1,1)}}).addTransitionMode("zoomInOut",{ease:"Linear",dir:"out",mask:!1,onStart:function(t,e,i,s){i.tint=0},onProgress:function(t,e,i,s){var r;s<.5?(r=1-wo(s),t.setChildLocalScale(e,r,r)):(e.visible&&t.setChildVisible(e,!1),r=1-wo(s),t.setChildLocalScale(i,r,r))},onComplete:function(t,e,i,s){t.setChildLocalScale(e,1,1),t.setChildVisible(e,!0),e.tint=16777215,t.setChildLocalScale(i,1,1),t.setChildVisible(i,!0),i.tint=16777215}})},function(t){t.addTransitionMode("fade",{ease:"Linear",dir:"out",mask:!1,onStart:function(t,e,i,s){i.tint=0},onProgress:function(t,e,i,s){var r;s<.5?(s=wo(s),r=Math.floor(255*(1-s)),e.tint=(r<<16)+(r<<8)+r):(e.visible&&t.setChildVisible(e,!1),s=wo(s),r=Math.floor(255*(1-s)),i.tint=(r<<16)+(r<<8)+r)},onComplete:function(t,e,i,s){t.setChildVisible(e,!0),e.tint=16777215,t.setChildVisible(i,!0),i.tint=16777215}}).addTransitionMode("crossFade",{ease:"Linear",dir:"out",mask:!1,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){t.setChildLocalAlpha(e,1-s),t.setChildLocalAlpha(i,s)},onComplete:function(t,e,i,s){t.setChildLocalAlpha(e,1)}})},function(t){var e,i=(e=t.scene,new Px(e,{type:"Graphics",create:[{name:"rect",type:"rectangle"}],update:function(){this.getShape("rect").fillStyle(16777215).setSize(this.width*this.value,this.height*this.value).setCenterPosition(this.centerX,this.centerY)}}));t.once("destroy",(function(){i.destroy()})).addTransitionMode("irisOut",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){t.setCurrentImageMaskEnable(!0,!0)},onProgress:function(t,e,i,s){t.maskGameObject.setValue(s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("irisIn",{ease:"Linear",dir:"in",mask:i,onStart:function(t,e,i,s){t.setNextImageMaskEnable(!0,!0)},onProgress:function(t,e,i,s){t.maskGameObject.setValue(1-s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("irisInOut",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){i.tint=0,t.setCurrentImageMaskEnable(!0),t.setNextImageMaskEnable(!0)},onProgress:function(t,e,i,s){var r;s<.5?(s=wo(s),r=Math.floor(255*(1-s)),t.maskGameObject.setValue(1-s),e.tint=(r<<16)+(r<<8)+r):(e.visible&&t.setChildVisible(e,!1),s=wo(s),r=Math.floor(255*(1-s)),t.maskGameObject.setValue(1-s),i.tint=(r<<16)+(r<<8)+r)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1),t.setChildVisible(e,!0),e.tint=16777215,t.setChildVisible(i,!0),i.tint=16777215}})},function(t){var e,i=(e=t.scene,new Px(e,{type:"Graphics",create:[{name:"pie",type:"arc"}],update:function(){var t=2*Math.max(this.width,this.height),e=90*this.value;this.getShape("pie").fillStyle(16777215).setCenterPosition(this.centerX,0).setRadius(t).setAngle(90-e,90+e).setPie()}}));t.once("destroy",(function(){i.destroy()})).addTransitionMode("pieOut",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){t.setCurrentImageMaskEnable(!0,!0)},onProgress:function(t,e,i,s){t.maskGameObject.setValue(s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("pieIn",{ease:"Linear",dir:"in",mask:i,onStart:function(t,e,i,s){t.setNextImageMaskEnable(!0,!0)},onProgress:function(t,e,i,s){t.maskGameObject.setValue(1-s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("pieInOut",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){i.tint=0,t.setCurrentImageMaskEnable(!0),t.setNextImageMaskEnable(!0)},onProgress:function(t,e,i,s){var r;s<.5?(s=wo(s),r=Math.floor(255*(1-s)),t.maskGameObject.setValue(1-s),e.tint=(r<<16)+(r<<8)+r):(e.visible&&t.setChildVisible(e,!1),s=wo(s),r=Math.floor(255*(1-s)),t.maskGameObject.setValue(1-s),i.tint=(r<<16)+(r<<8)+r)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1),t.setChildVisible(e,!0),e.tint=16777215,t.setChildVisible(i,!0),i.tint=16777215}})},function(t){var e,i=(e=t.scene,new Px(e,{type:"Graphics",create:[{name:"rect",type:"rectangle"}],update:function(){var t=this.getShape("rect").fillStyle(16777215),e=1-this.value;switch(this.wipeMode){case"right":t.setSize(this.width*e,this.height).setTopLeftPosition(this.width-t.width,0);break;case"left":t.setSize(this.width*e,this.height).setTopLeftPosition(0,0);break;case"down":t.setSize(this.width,this.height*e).setTopLeftPosition(0,this.height-t.height);break;case"up":t.setSize(this.width,this.height*e).setTopLeftPosition(0,0)}}}));t.once("destroy",(function(){i.destroy()})).addTransitionMode("wipeRight",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){t.setCurrentImageMaskEnable(!0),t.maskGameObject.wipeMode="right"},onProgress:function(t,e,i,s){t.maskGameObject.setValue(s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("wipeLeft",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){t.setCurrentImageMaskEnable(!0),t.maskGameObject.wipeMode="left"},onProgress:function(t,e,i,s){t.maskGameObject.setValue(s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("wipeDown",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){t.setCurrentImageMaskEnable(!0),t.maskGameObject.wipeMode="down"},onProgress:function(t,e,i,s){t.maskGameObject.setValue(s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("wipeUp",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){t.setCurrentImageMaskEnable(!0),t.maskGameObject.wipeMode="up"},onProgress:function(t,e,i,s){t.maskGameObject.setValue(s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}})},function(t){var e=function(t,e){var i=new Px(t,{type:"Graphics",create:{rectangle:e},update:function(){for(var t=this.getShapes(),i=this.width/e,s=0;s=0;s--)(a=r[s])instanceof e&&(a.destroy(),lk(r,s));else{s=0;for(var r,n=(r=t.postPipelines).length;s0}(e,ok),delete e.effect}})},function(t){t.addTransitionMode("revealRight",{ease:"Linear",dir:"in",mask:!1,onStart:function(t,e,i,s){i.effect=i.preFX.addReveal(dk,0,0)},onProgress:function(t,e,i,s){i.effect.progress=s},onComplete:function(t,e,i,s){i.preFX.remove(i.effect),delete i.effect}}).addTransitionMode("revealLeft",{ease:"Linear",dir:"in",mask:!1,onStart:function(t,e,i,s){i.effect=i.preFX.addReveal(dk,1,0)},onProgress:function(t,e,i,s){i.effect.progress=s},onComplete:function(t,e,i,s){i.preFX.remove(i.effect),delete i.effect}}).addTransitionMode("revealDown",{ease:"Linear",dir:"in",mask:!1,onStart:function(t,e,i,s){i.effect=i.preFX.addReveal(dk,0,1)},onProgress:function(t,e,i,s){i.effect.progress=s},onComplete:function(t,e,i,s){i.preFX.remove(i.effect),delete i.effect}}).addTransitionMode("revealUp",{ease:"Linear",dir:"in",mask:!1,onStart:function(t,e,i,s){i.effect=i.preFX.addReveal(dk,1,1)},onProgress:function(t,e,i,s){i.effect.progress=s},onComplete:function(t,e,i,s){i.preFX.remove(i.effect),delete i.effect}})}];class uk extends ek{constructor(t,e,i,s,r,n){super(t,e,i,s,r,n);for(var a=0,o=ck.length;at.dropEnable}),this.on("drop",(function(t,e){this._files=e.dataTransfer.files;var i=this._files;if(i&&this.filters)for(var s in this.filters){for(var r=this.filters[s],n=[],a=0,o=i.length;a0&&this.emit(`drop.${s}`,n)}}),this)}get files(){return this._files}}Object.assign(Jk.prototype,Hk),t.register("fileDropZone",(function(t){var e=new Jk(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.FileDropZone",Jk);const qk=Phaser.Math.Wrap;var Zk=function(t,e){if(this.hasRatioFitChild){var i,s,r;0===this.orientation?i=e-(this.getInnerPadding("top")+this.getInnerPadding("bottom"))*this.scaleY:(this.getInnerPadding("left"),this.getInnerPadding("right"),this.scaleX);for(var n=this.sizerChildren,a=0,o=n.length;a(i=0===this.orientation?Math.abs(h.left-t):Math.abs(h.top-e))&&(n=i,r=a)}return h=s[s.length-1],n>(i=0===this.orientation?Math.abs(h.right-t):Math.abs(h.bottom-e))&&(n=i,r=a+1),r};const iw=Phaser.Utils.Objects.IsPlainObject,sw=Phaser.Utils.Objects.GetValue,rw=Phaser.Display.Align.CENTER,nw={min:0,full:-1};var aw=function(t,e,i,s,r,n,a,o,h,l){fv.call(this,t);var d=t.isRexSpace,c=typeof e;if(null===e)return this;if("number"===c);else if("string"===c)e=nw[e];else if(iw(e)){var u;e=sw(u=e,"proportion",void 0),i=sw(u,"align",rw),s=sw(u,"padding",0),r=sw(u,"expand",!1),n=sw(u,"key",void 0),a=sw(u,"index",void 0),t.isRexSizer||(o=sw(u,"minWidth",void 0),h=sw(u,"minHeight",void 0)),l=sw(u,"fitRatio",0)}return"string"==typeof i&&(i=zg[i]),void 0===e&&(e=d?1:0),void 0===i&&(i=rw),void 0===s&&(s=0),void 0===r&&(r=!1),void 0===o&&(d?o=0:t.isRexSizer||(o=t._minWidth)),void 0===h&&(d?h=0:t.isRexSizer||(h=t._minHeight)),void 0===l||!1===l?l=0:!0===l&&(l=An(t)/zn(t)),(u=this.getSizerConfig(t)).proportion=e,u.align=i,u.padding=gv(s),u.expand=r,u.fitRatio=0===e?l:0,void 0===a||a>=this.sizerChildren.length?this.sizerChildren.push(t):this.sizerChildren.splice(a,0,t),t.isRexSizer||(e>0&&(0===this.orientation?t.minWidth=void 0===o?An(t):o:t.minHeight=void 0===h?zn(t):h),r&&(0===this.orientation?t.minHeight=h:t.minWidth=o)),void 0!==n&&this.addChildrenMap(n,t),this},ow={add:aw,addSpace(t){return this.insertSpace(void 0,t),this},insertSpace(t,e){return void 0===e&&(e=1),aw.call(this,new tw(this.scene),{proportion:e,minWidth:0,minHeight:0,index:t}),this},insert(t,e,i,s,r,n,a,o){return iw(i)&&(i.index=t),aw.call(this,e,i,s,r,n,a,t,o),this},insertAtPosition(t,e,i,s,r,n,a,o,h){var l=ew.call(this,t,e);return-1===l&&(l=void 0),this.insert(l,i,s,r,n,a,o,h),this}};const hw=Phaser.Utils.Array.Remove;var lw={remove(t,e){return this.getParentSizer(t)!==this||(hw(this.sizerChildren,t),wv.call(this,t,e)),this},removeAll(t){for(var e=this.sizerChildren.length-1;e>=0;e--)this.remove(this.sizerChildren[e],t);return this},clear(t){return this.sizerChildren.length=0,Ib.call(this,t),this}},dw={getChildAlign(t){return this.getSizerConfig(t).align},setChildAlign(t,e){return"string"==typeof e&&(e=zg[e]),this.getSizerConfig(t).align=e,this}},cw={getChildProportion(t){return this.getSizerConfig(t).proportion},setChildProportion(t,e){return this.getSizerConfig(t).proportion=e,this}},uw={getChildExpand(t){return this.getSizerConfig(t).expand},setChildExpand(t,e){return this.getSizerConfig(t).expand=e,this}},pw={sortChildren(t){return this.sizerChildren.sort(t),this},sortChildrenByData(t,e){return this.sizerChildren.sort((function(i,s){var r=i.getData(t),n=s.getData(t);return e?n-r:r-n})),this},sortChildrenByProperty(t,e){return this.sizerChildren.sort((function(i,s){var r=i[t],n=s[t];return e?n-r:r-n})),this}},gw={getChildrenWidth:function(t){if(this.rexSizer.hidden)return 0;void 0===t&&(t=!0);var e,i,s,r,n,a=0,o=this.sizerChildren,h=!1;if(this.childrenProportion,0===this.orientation)for(var l=!0,d=0,c=o.length;d0&&!i.resolved&&(n=void 0),void 0===n&&(0===s||this.hasProportion0Child?h=!0:n=0)):n=0,h||(n+=((r=e.rexSizer.padding).left+r.right)*this.scaleX,l?l=!1:n+=this.space.item*this.scaleX,a+=n)));else for(d=0,c=o.length;d0&&!i.resolved&&(n=void 0),void 0===n&&(0===s||this.hasProportion0Child?h=!0:n=0)):n=0,h||(n+=((r=i.padding).top+r.bottom)*this.scaleY,c?c=!1:n+=this.space.item*this.scaleY,a+=n)))}return h?void 0:a+(this.space.top+this.space.bottom)*this.scaleY},getExpandedChildWidth:function(t,e){var i;void 0===e&&(e=this.width*this.scaleX);var s=t.rexSizer;if(0===this.orientation)s.proportion>0&&this.proportionLength>0&&(i=s.proportion*this.proportionLength);else if(s.expand){var r=this.space,n=e-(r.left+r.right)*this.scaleX,a=s.padding;i=n-(a.left+a.right)*this.scaleX}return i},getExpandedChildHeight:function(t,e){var i;void 0===e&&(e=this.height);var s=t.rexSizer;if(0===this.orientation){if(s.expand){var r=this.space,n=e-(r.top+r.bottom)*this.scaleY,a=s.padding;i=n-(a.top+a.bottom)*this.scaleY}}else s.proportion>0&&this.proportionLength>0&&(i=s.proportion*this.proportionLength);return i},getChildrenSizers:function(t){void 0===t&&(t=[]);for(var e,i=this.sizerChildren,s=0,r=i.length;s0&&(Yv(t,0,0),e.resolved=!1,this.hasRatioFitChild=!0);return this._childrenProportion=void 0,this.hasProportion0Child=!1,this.proportionLength=void 0,Av.call(this),this},layoutChildren:function(){for(var t,e,i,s,r,n,a,o,h,l,d=this.sizerChildren,c=this.innerLeft,u=this.innerTop,p=this.innerWidth,g=this.innerHeight,v=c,f=u,m=this.startChildIndex,y=0,b=d.length;y0?(e=t-this.getChildrenWidth(!1),this.proportionLength=e/this.childrenProportion):this.proportionLength=0}return t},resolveHeight:function(t){if(void 0!==(t=Bv.call(this,t))&&1===this.orientation&&void 0===this.proportionLength){var e=t-this.childrenHeight;e>0?(e=t-this.getChildrenHeight(!1),this.proportionLength=e/this.childrenProportion):this.proportionLength=0}return t},hasWidthWrap:function(){return!(!this.hasRatioFitChild||1!==this.orientation)||Rv.call(this)},runWidthWrap:function(t){this.wrapResult||(1===this.orientation&&Zk.call(this,t,void 0),Lv.call(this,t))},hasHeightWrap:function(){return!(!this.hasRatioFitChild||0!==this.orientation)||Iv.call(this)},runHeightWrap:function(t){this.wrapResult||(0===this.orientation&&Zk.call(this,void 0,t),Dv.call(this,t))},setChildrenAlignMode:function(t){void 0===t&&(t="left");var e=this.sizerChildren,i=e[0],s=i&&i.isRexSpace;"right"===t||"bottom"===t||"center"===t?s||this.insertSpace(0):s&&this.remove(i,!0);var r=e.length-1,n=e[r],a=n&&n.isRexSpace;return"center"===t?a||this.insertSpace(r+1):a&&this.remove(n,!0),this}};Object.assign(gw,ow,lw,dw,cw,uw,pw);var vw=function(){for(var t,e,i=0,s=this.sizerChildren,r=0,n=s.length;r0?i+=e:0===e&&(this.hasProportion0Child=!0));return i},fw={x:0,h:0,horizontal:0,"left-to-right":0,y:1,v:1,vertical:1,"top-to-bottom":1},mw=function(t){return"string"==typeof t&&(t=fw[t]),t};const yw=Phaser.Utils.Objects.IsPlainObject,bw=Phaser.Utils.Objects.GetValue;class xw extends Cb{constructor(t,e,i,s,r,n,a){yw(e)?(e=bw(a=e,"x",0),i=bw(a,"y",0),s=bw(a,"width",void 0),r=bw(a,"height",void 0),n=bw(a,"orientation",0)):yw(s)?(s=bw(a=s,"width",void 0),r=bw(a,"height",void 0),n=bw(a,"orientation",0)):yw(n)&&(n=bw(a=n,"orientation",0)),void 0===n&&(n=0),super(t,e,i,s,r,a),this.type="rexSizer",this.sizerChildren=[],this.setOrientation(n),this.setItemSpacing(bw(a,"space.item",0)),this.setStartChildIndex(bw(a,"startChildIndex",0)),this.setRTL(bw(a,"rtl",!1)),this.addChildrenMap("items",this.sizerChildren)}setOrientation(t){return this.orientation=mw(t),this}setItemSpacing(t){return this.space.item=t,this}setStartChildIndex(t){return this.startChildIndex=t,this}setRTL(t){return void 0===t&&(t=!0),this.rtl=t,this}get childrenProportion(){return void 0===this._childrenProportion&&(this._childrenProportion=vw.call(this)),this._childrenProportion}}Object.assign(xw.prototype,gw);var Cw=function(t,e,i){if(t){var s=null==e,r=null==i;return s&&r||(s||(t.displayWidth=e),r||(t.displayHeight=i),s&&(t.scaleX=t.scaleY),r&&(t.scaleY=t.scaleX)),t}},kw={appendText:Mi,resetDisplayContent:function(t){void 0===t?t={}:"string"==typeof t&&(t={text:t});var e=t.text||"";this.setText(e);var i=this.childrenMap.icon;if(i){t.icon?this.show(i):this.hide(i);var s=t.iconSize;s&&(this.setChildDisplaySize(i,s,s),void 0!==this.iconWidth&&this.setIconSize(s)),!0!==t.icon&&this.setIconTexture(t.icon,t.iconFrame)}var r=this.childrenMap.action;if(r){t.action?this.show(r):this.hide(r);var n=t.actionSize;n&&(this.setChildDisplaySize(r,n,n),void 0!==this.actionWidth&&this.setActionSize(n)),!0!==t.action&&this.setActionTexture(t.action,t.actionFrame)}return this}};class ww extends xw{get text(){var t=this.childrenMap.text;return t?t.text:""}set text(t){var e=this.childrenMap.text;e&&e.setText(t)}setText(t){return this.text=t,this}setIconTexture(t,e){var i=this.childrenMap.icon;return i&&i.setTexture?(i.setTexture(t,e),void 0!==this.iconWidth&&void 0!==this.iconHeight&&(Cw(i,this.iconWidth,this.iconHeight),this.resetChildScaleState(i)),this):this}setTexture(t,e){return this.setIconTexture(t,e),this}setIconSize(t,e){return void 0===e&&(e=t),this.iconWidth=t,this.iconHeight=e,this}get texture(){var t=this.childrenMap.icon;if(t)return t.texture}get frame(){var t=this.childrenMap.icon;if(t)return t.frame}setActionTexture(t,e){var i=this.childrenMap.action;return i&&i.setTexture?(i.setTexture(t,e),void 0!==this.actionWidth&&void 0!==this.actionHeight&&(Cw(i,this.actionWidth,this.actionHeight),this.resetChildScaleState(i)),this):this}get actionTexture(){var t=this.childrenMap.action;if(t)return t.texture}get actionFrame(){var t=this.childrenMap.action;if(t)return t.frame}setActionSize(t,e){return void 0===e&&(e=t),this.actionWidth=t,this.actionHeight=e,this}preLayout(){var t=this.childrenMap.icon;t&&void 0!==this.iconWidth&&void 0!==this.iconHeight&&Cw(t,this.iconWidth,this.iconHeight);var e=this.childrenMap.action;e&&void 0!==this.actionWidth&&void 0!==this.actionHeight&&Cw(e,this.actionWidth,this.actionHeight),super.preLayout()}postLayout(t,e,i){var s=this.childrenMap.iconMask;s&&(s.setPosition(),this.resetChildPositionState(s));var r=this.childrenMap.actionMask;return r&&(r.setPosition(),this.resetChildPositionState(r)),super.postLayout(t,e,i),this}resize(t,e){super.resize(t,e);var i=this.childrenMap.iconMask;i&&i.resize();var s=this.childrenMap.actionMask;return s&&s.resize(),this}}Object.assign(ww.prototype,kw);var Sw=function(t,e,i,s){var r=new FC(e,i,s);if(t&&!t.isRexSizer){var n=r.createGeometryMask();t.setMask(n),this.once("destroy",(function(){t.setMask(),n.destroy()}))}return this.pin(r),r};const Pw=Phaser.GameObjects.Text;var Tw=function(t){return t instanceof Pw};const Ow=Phaser.GameObjects.BitmapText;var Mw=function(t){return t instanceof Ow},Ew=function(t){return Mw(t)?2:Tw(t)?0:1},_w=function(t,e){for(var i=[],s=t.split("\n"),r=e.style,n=r.wordWrapWidth,a=r.hasOwnProperty("wrapMode")?r.wrapMode:3,o=e.context,h=0,l=s.length;h0&&r.push(h.join("")),r},Lw=function(t,e){switch(Ew(t)){case 0:switch("string"==typeof e&&(e=Be[e]||0),t.style.wrapMode=e,e){case 2:case 3:t.style.wordWrapCallback=_w;break;default:t.style.wordWrapCallback=null}break;case 1:"string"==typeof e&&(e=Be[e]||0),t.style.wrapMode=e}},Bw=function(t,e){return void 0===e&&(e=0),t._minWidth=e,t.runWidthWrap=function(t){return t instanceof hn}(t)?function(t){return function(e){return t.setFixedSize(e,0).runWordWrap(),t.minHeight=t.height,t}}(t):Mw(t)?function(t){return function(e){return t.setMaxWidth(e),t.minHeight=t.height,t}}(t):function(t){return function(e){var i=t.padding,s=e-(i.left+i.right)*t.scaleX,r=t.style;return Tw(t)?(r.wordWrapWidth=s,r.maxLines=0):(0===r.wrapMode&&(r.wrapMode=1),r.wrapWidth=s,r.maxLines=0),r.fixedWidth=e,r.fixedHeight=0,t.updateText(),t.minHeight=t.height,t}}(t),t};const Iw=65535;var Dw=function(t,e,i){if(null==e)return t;if(0===e)return zw(t,0,i),t;var s=t.text.length;if(0===s)return zw(t,e,i),t;var r=Math.floor(1.5*e/s);void 0!==i&&r>i&&(r=Math.floor(i));for(var n={},a=Aw(t,r,e,i,n),o=0;o<=Iw&&0!==a;o++){if((r+=a)<0){r=0;break}a=Aw(t,r,e,i,n)}return o===Iw&&console.warn("FontSizeFit: Test count exceeds 65535"),t.setFontSize(r),zw(t,e,i),t},jw=function(t,e,i){return void 0===i[e]&&(t.setFontSize(e),i[e]={width:t.width,height:t.height}),i[e]},Aw=function(t,e,i,s,r){var n,a=jw(t,e,r),o=jw(t,e+1,r);if(void 0!==s)if(a.height<=s&&o.height>s)n=0;else{if(a.height>s)return-1;n=Math.floor(s-a.height)}if(a.width<=i&&o.width>i)return 0;if(a.width>i)return-1;var h=Math.floor(i-a.width);return void 0===n?h:Math.min(h,n)},zw=function(t,e,i){var s=t.style;s&&(s.fixedWidth=e,s.parent.width=e,void 0!==i&&(s.fixedHeight=i,s.parent.height=i),s.update(!1))};const Fw=Phaser.Utils.Objects.GetValue;var Yw=function(t,e){"number"==typeof e&&(e={minWidth:e});var i=Fw(e,"minWidth",0),s=Fw(e,"minHeight",0),r=Fw(e,"fitHeight",!1);return t._minWidth=i,t._minHeight=s,r?(t.runWidthWrap=function(e){return t.setFixedSize&&t.setFixedSize(0,0),t.setFontSize(1),t},t.resize=function(e,i){return Dw(t,e,i),t}):(t.runWidthWrap=function(e){return t.setFixedSize&&t.setFixedSize(0,0),Dw(t,e,void 0),t},t.resize=function(e,i){return t.width===e&&t.height===i||t.setFixedSize(e,i),t}),t};const Xw=Phaser.Utils.Objects.GetValue;class Ww extends ww{constructor(t,e){void 0===e&&(e={}),super(t,e),this.type="rexLabel";var i,s=Xw(e,"background",void 0),r=Xw(e,"icon",void 0),n=Xw(e,"iconMask",void 0),a=Xw(e,"text",void 0),o=Xw(e,"action",void 0),h=Xw(e,"actionMask",void 0),l=Xw(e,"align",void 0);if(s&&this.addBackground(s),r){0===this.orientation?(a||o)&&(i={right:Xw(e,"space.icon",0),top:Xw(e,"space.iconTop",0),bottom:Xw(e,"space.iconBottom",0),left:Xw(e,"space.iconLeft",0)}):(a||o)&&(i={bottom:Xw(e,"space.icon",0),left:Xw(e,"space.iconLeft",0),right:Xw(e,"space.iconRight",0),top:Xw(e,"space.iconTop",0)});var d=Xw(e,"squareFitIcon",!1)?1:0;if(this.add(r,{proportion:0,padding:i,fitRatio:d}),n&&(n=Sw.call(this,r,r,1)),!d){var c=Xw(e,"iconSize",void 0);this.setIconSize(Xw(e,"iconWidth",c),Xw(e,"iconHeight",c))}}if(a){var u=Xw(e,"wrapText",!1),p=Xw(e,"adjustTextFontSize",!1);u?(!0===u&&(u="word"),Lw(a,u),e.expandTextWidth=!0,Bw(a)):p&&(e.expandTextWidth=!0,e.expandTextHeight=!0,Yw(a,{fitHeight:!0}));var g,v,f=Xw(e,"space.text",0),m=Xw(e,"expandTextWidth",!1),y=Xw(e,"expandTextHeight",!1);0===this.orientation?(g=m?1:0,o&&(i={right:f}),v=y):(g=y?1:0,o&&(i={bottom:f}),v=m),this.add(a,{proportion:g,expand:v,padding:i})}if(o&&(i=0===this.orientation?{top:Xw(e,"space.actionTop",0),bottom:Xw(e,"space.actionBottom",0),right:Xw(e,"space.actionRight",0)}:{left:Xw(e,"space.actionLeft",0),right:Xw(e,"space.actionRight",0),bottom:Xw(e,"space.actionBottom",0)},d=Xw(e,"squareFitAction",!1)?1:0,this.add(o,{proportion:0,padding:i,fitRatio:d}),h&&(h=Sw.call(this,o,o,1)),!d)){var b=Xw(e,"actionSize");this.setActionSize(Xw(e,"actionWidth",b),Xw(e,"actionHeight",b))}this.setChildrenAlignMode(l),this.addChildrenMap("background",s),this.addChildrenMap("icon",r),this.addChildrenMap("iconMask",n),this.addChildrenMap("text",a),this.addChildrenMap("action",o),this.addChildrenMap("actionMask",h)}}const Vw=Phaser.Utils.Objects.GetValue;var Gw=function(t,e){var i=Vw(e,"canvas"),s=Vw(i,"width",128),r=Vw(i,"height",128),n=new Mu(t,0,0,s,r);t.add.existing(n);var a=Vw(i,"key"),o=Vw(i,"frame"),h=Vw(i,"fill");return void 0!==h?n.fill(h):void 0!==a&&n.loadTexture(a,o),n.setTexture=n.loadTexture.bind(n),n};const Hw=Phaser.Utils.Objects.GetValue;var Uw=function(t,e){var i=Hw(e,"clickTarget",this);return"string"==typeof i&&(i=t.getElement(i)),i};const Nw=Phaser.Utils.Objects.GetValue,$w={accept:"image/*",multiple:!1};var Kw=function(t,e){if(0!==e.length){var i=t.childrenMap.icon,s=i.image,r=e[0];return s.loadFromFilePromise(r).then((function(){return i.scaleImage(),t.emit("select",r,t),Promise.resolve(r)}))}},Jw={async openPromise(){var t=this;return Ik(this.scene.game,$w).then((function(e){return Kw(t,e.files)}))},open(){return this.openPromise(),this},setClickOpenEnable(t){return void 0===t&&(t=!0),this.clickBehavior&&this.clickBehavior.setEnable(t),this.fileChooser&&this.fileChooser.setOpenEnable(t),this}},qw={getFileName:function(t){if(!t)return null;var e=t.name;return e.substr(0,e.lastIndexOf("."))},saveTexture:function(t){return this.childrenMap.canvas.generateTexture(t),this}};Object.assign(qw,Jw);const Zw=Phaser.Utils.Objects.GetValue;class Qw extends Ww{constructor(t,e){var i=function(t,e){var i=new mk(t,{scaleUp:Vw(e,"scaleUpIcon",!1),background:Vw(e,"iconBackground"),image:Gw(t,e)});return t.add.existing(i),i}(t,e);e.icon=i,super(t,e),this.type="rexImageFileInputLabel";var s=this.iconWidth,r=this.iconWidth;void 0!==s&&void 0!==r&&i.resize(s,r),this.clickTarget=Uw(this,e),this.clickTarget&&(Zw(e,"domButton",!0)?this.fileChooser=function(t){var e=t.scene,i=new Xk(e,$w);return e.add.existing(i),t.pin(i),i.on("change",(function(){Kw(t,i.files)})),i}(this):this.clickBehavior=function(t,e){var i=Uw(t,e);if(i){var s=Nw(e,"click"),r=new hu(i,s);return r.on("click",t.open,t),r}}(this,e)),this.addChildrenMap("canvas",i.image),this.addChildrenMap("iconBackground",i.background),this.addChildrenMap("fileChooser",this.fileChooser)}postLayout(t,e,i){this.fileChooser&&(this.fileChooser.syncTo(this.clickTarget),this.resetChildState(this.fileChooser)),super.postLayout(t,e,i)}}Object.assign(Qw.prototype,qw),t.register("imageInputLabel",(function(t){var e=new Qw(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ImageInputLabel",Qw);let tS=class extends Ra{constructor(t,e){return super(t),new Proxy(this,this)}get(t,e){if(ae(t,e))return t[e];var i=t.parent;return ae(i,e)?i[e]:void 0}set(t,e,i){return ae(t,e)?t[e]=i:ae(t.parent,e)&&(t.parent[e]=i),!0}get key(){return this.parent.texture.key}set key(t){this.parent.setTexture(t,this.frame)}get frame(){return this.parent.frame.name}set frame(t){this.parent.setFrame(t)}get scale(){return this.parent.scaleX}set scale(t){this.parent.setScale(t)}};const eS=Phaser.Utils.Objects.GetValue;class iS extends Ra{constructor(t,e){super(t,e),this.style=eS(e,"style",this);var i=eS(e,"propertiesMap");this.activeStyle=sS(e,"active",i),this.hoverStyle=sS(e,"hover",i),this.disableStyle=sS(e,"disable",i),this.onModifyStyle=eS(e,"onModifyStyle")}getStyle(t){return Bd(this.style,t)}modifyStyle(t){for(var e in t)this.style[e]=t[e];return this.onModifyStyle&&this.onModifyStyle(this.parent,t),this}applyStyle(t){if(t){var e=this.getStyle(t);return Id(e,t)?void 0:(this.modifyStyle(t),e)}}setActiveState(t){return rS.call(this,"active",t),this}setHoverState(t){return rS.call(this,"hover",t),this}setDisableState(t){return rS.call(this,"disable",t),this}}var sS=function(t,e,i){var s=Rd(t,e);if(i)for(var r in s)i.hasOwnProperty(r)&&(s[i[r]]=s[r],delete s[r]);return s},rS=function(t,e){void 0===e&&(e=!0);var i=`${t}State`,s=`${t}Style`,r=`${t}StyleSave`;this[i]!==e&&(this[i]=e,e?this[r]=this.applyStyle(this[s]):(this.applyStyle(this[r]),this[r]=void 0))},nS={addStyleManager(t){return this.styleManager=new iS(this,t),this},setActiveState(t){return this.styleManager.setActiveState(t),this},setHoverState(t){return this.styleManager.setHoverState(t),this},setDisableState(t){return this.styleManager.setDisableState(t),this}};const aS=Phaser.GameObjects.Image,oS=Phaser.Utils.Objects.GetValue;class hS extends aS{constructor(t,e){void 0===e&&(e={}),super(t,oS(e,"x",0),oS(e,"y",0),oS(e,"key",""),oS(e,"frame",void 0)),this.type="rexStatesImage";var i=oS(e,"effects",!0);i&&Mn(this,i),this.style=new tS(this,e),e.style=this.style,this.addStyleManager(e),delete e.style}}Object.assign(hS.prototype,nS),t.register("statesImage",(function(t){var e=new hS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesImage",hS);class lS extends Dt{constructor(t,e){void 0===e&&(e={}),super(t,e),this.type="rexStatesRoundRectangleShape",e.style=this,e.propertiesMap=dS,this.addStyleManager(e),delete e.style,delete e.propertiesMap}}const dS={color:"fillColor",alpha:"fillAlpha",strokeWidth:"lineWidth"};Object.assign(lS.prototype,nS),t.register("statesRoundRectangle",(function(t){var e=new lS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesRoundRectangle",lS);let cS=class extends Ra{constructor(t,e){return super(t),new Proxy(this,this)}get(t,e){if(ae(t,e))return t[e];var i=t.parent;return ae(i,e)?i[e]:void 0}set(t,e,i){return ae(t,e)?t[e]=i:ae(t.parent,e)&&(t.parent[e]=i),!0}get key(){return this.parent.texture.key}set key(t){this.key!==t&&this.parent.setTexture(t,this.frame)}get frame(){return this.parent.frame.name}set frame(t){this.frame!==t&&this.parent.setFrame(t)}};const uS=Phaser.GameObjects.NineSlice,pS=Phaser.Utils.Objects.GetValue;class gS extends uS{constructor(t,e){void 0===e&&(e={}),super(t,pS(e,"x",0),pS(e,"y",0),pS(e,"key",null),pS(e,"frame",null),pS(e,"width",0),pS(e,"height",0),pS(e,"leftWidth",0),pS(e,"rightWidth",0),pS(e,"topHeight",0),pS(e,"bottomHeight",0)),this.type="rexStatesNineSlice";var i=pS(e,"effects",!0);i&&Mn(this,i),this.style=new cS(this,e),e.style=this.style,this.addStyleManager(e),delete e.style}}Object.assign(gS.prototype,nS),t.register("statesNineSlice",(function(t){var e=new gS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesNineSlice",gS);let vS=class extends Ra{constructor(t,e){return super(t),new Proxy(this,this)}get(t,e){if(ae(t,e))return t[e];var i=t.parent;return ae(i,e)?i[e]:void 0}set(t,e,i){return ae(t,e)?t[e]=i:ae(t.parent,e)&&(t.parent[e]=i),!0}get key(){return this.parent.textureKey}set key(t){this.key!==t&&this.parent.setBaseTexture(t,this.baseFrameName)}get frame(){return this.parent.baseFrameName}set frame(t){this.frame!==t&&this.parent.setBaseTexture(this.parent.textureKey,t)}};const fS=Phaser.Utils.Objects.GetValue;class mS extends k{constructor(t,e){void 0===e&&(e={}),super(t,e),this.type="rexStatesNinePatch";var i=fS(e,"effects",!0);i&&Mn(this,i),this.style=new vS(this,e),e.style=this.style,this.addStyleManager(e),delete e.style}}Object.assign(mS.prototype,nS),t.register("statesNinePatch",(function(t){var e=new mS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesNinePatch",mS);const yS=Phaser.GameObjects.Text,bS=Phaser.Utils.Objects.GetValue;class xS extends yS{constructor(t,e){void 0===e&&(e={}),super(t,bS(e,"x",0),bS(e,"y",0),bS(e,"text",""),e),this.type="rexStatesText",e.style=this.style,e.onModifyStyle=function(t,e){var i=e.hasOwnProperty("fontStyle")||e.hasOwnProperty("fontSize")||e.hasOwnProperty("fontFamily");t.style.update(i)},this.addStyleManager(e),delete e.style}}Object.assign(xS.prototype,nS),t.register("statesText",(function(t){var e=new xS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesText",xS);class CS extends Ra{constructor(t,e){return super(t),new Proxy(this,this)}get(t,e){if(ae(t,e))return t[e];var i=t.parent;return ae(i,e)?i[e]:void 0}set(t,e,i){return ae(t,e)?t[e]=i:ae(t.parent,e)&&(t.parent[e]=i),!0}get key(){return this.parent.texture.key}set key(t){this.parent.setTexture(t,this.frame)}get fontSize(){return this.parent.fontSize}set fontSize(t){this.parent.setFontSize(t)}get tint(){return this.parent.tintTopLeft}set tint(t){this.parent.setTint(t)}get letterSpacing(){return this.parent.letterSpacing}set letterSpacing(t){this.parent.setLetterSpacing(t)}get lineSpacing(){return this.parent.lineSpacing}set lineSpacing(t){this.parent.setLineSpacing(t)}}const kS=Phaser.GameObjects.BitmapText,wS=Phaser.Utils.Objects.GetValue;class SS extends kS{constructor(t,e){void 0===e&&(e={});var i=wS(e,"x",0),s=wS(e,"y",0),r=wS(e,"font",""),n=wS(e,"fontSize",!1),a=wS(e,"align",0),o=wS(e,"tint");super(t,i,s,r,"",n,a),this.type="rexStatesBitmapText",void 0!==o&&this.setTint(o);var h=wS(e,"effects",!0);h&&Mn(this,h),this.style=new CS(this,e),e.style=this.style,this.addStyleManager(e),delete e.style}}Object.assign(SS.prototype,nS),t.register("statesBitmapText",(function(t){var e=new SS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesBitmapText",SS);class PS extends dp{constructor(t,e){void 0===e&&(e={}),e.hasOwnProperty("value")||(e.value=0),e.hasOwnProperty("hover.bar")||(e["hover.bar"]=!0),e.hasOwnProperty("easeDuration")||(e.easeDuration=200),e.hasOwnProperty("ease")||(e.ease="Quad"),P(e,"easeValue.duration",e.easeDuration),P(e,"easeValue.ease",e.ease),super(t,e),this.type="rexStatesBarRectangleShape",this.barState=!1,e.style=this,e.propertiesMap=TS,this.addStyleManager(e),delete e.style,delete e.propertiesMap}get bar(){return this.barState}set bar(t){t=!!t,this.barState!==t&&(this.barState=t,this.easeValueTo(this.barState?1:0))}}const TS={color:"trackColor",strokeColor:"trackStrokeColor",strokeWidth:"trackStrokeThickness"};Object.assign(PS.prototype,nS),t.register("statesBarRectangle",(function(t){var e=new PS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesBarRectangle",PS);var OS=function(t,e){void 0===e&&(e={}),void 0===e.options&&(e.options={});var i=e.options;i.responsive=!1,i.maintainAspectRatio=!1,i.hasOwnProperty("devicePixelRatio")||(i.devicePixelRatio=1);var s=!1;void 0===i.animation?i.animation={}:!1===i.animation&&(s=!0,i.animation={});var r=i.animation;s&&(r.duration=0);var n=r.onProgress;r.onProgress=function(e){n&&n(e),t.needRedraw()};var a=r.onComplete;return r.onComplete=function(e){a&&a(e),t.needRedraw()},e};let MS=class extends Mu{constructor(t,e,i,s,r,n){super(t,e,i,s,r),this.type="rexChart",this.chart=void 0,void 0!==n&&this.setChart(n)}destroy(t){this.scene&&(this.chart&&(this.chart.destroy(),this.chart=void 0),super.destroy(t))}resize(t,e){if(t===this.width&&e===this.height)return this;if(super.resize(t,e),this.chart){var i=this.chart;i.height=this.canvas.height,i.width=this.canvas.width,i.aspectRatio=i.height?i.width/i.height:null,i.update()}return this}};var ES={setChart:function(t){return window.Chart?(this.chart&&this.chart.destroy(),this.chart=new Chart(this.context,OS(this,t)),this):(console.error("Can not find chartjs! Load chartjs in preload stage.\nscene.load.script('chartjs', 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/Chart.min.js');"),this)},getChartDataset:function(t){if(void 0!==this.chart){if("string"!=typeof t)return this.chart.data.datasets[t];for(var e,i=this.chart.data.datasets,s=0,r=i.length;s=0;e--){var i=this.sizerChildren[e];i&&this.remove(i,t)}return this},clear(t){return AS(this.sizerChildren,null),Ib.call(this,t),this}},FS={setColumnSpace(t){if(this.space.column||(this.space.column=[]),this.space.column.length=this.columnCount-1,"number"==typeof t)AS(this.space.column,t);else for(var e=0,i=this.columnCount-1;e=0;s--){var r=s*this.columnCount+t;this.sizerChildren.splice(r,0,null)}return this.columnProportions.push(e),this.columnWidth.length+=1,this.space.column.splice(t,0,i),this},VS={getChildrenWidth:function(t){if(this.rexSizer.hidden)return 0;void 0===t&&(t=!0);var e,i,s,r,n,a=0,o=this.sizerChildren,h=!1;this.totalColumnProportions;for(var l=0;l0){var i=t-this.getChildrenWidth(!1);i>=0&&(this.proportionWidthLength=i/e)}else this.proportionWidthLength=0}return t},resolveHeight:function(t){if(void 0!==(t=Bv.call(this,t))&&void 0===this.proportionHeightLength){var e=this.totalRowProportions;if(e>0){var i=t-this.getChildrenHeight(!1);i>=0&&(this.proportionHeightLength=i/e)}else this.proportionHeightLength=0}return t},resolveChildrenWidth:function(t){var e,i,s,r;for(var n in this.sizerChildren)(e=this.sizerChildren[n])&&e.isRexSizer&&!e.ignoreLayout&&(r=this.getColumnWidth(parseInt(n)%this.columnCount),i=this.getExpandedChildWidth(e,r),void 0===(s=e.resolveWidth(i))&&(s=i),e.resolveChildrenWidth(s))},resolveChildrenHeight:function(t){var e,i,s,r;for(var n in this.sizerChildren)(e=this.sizerChildren[n])&&e.isRexSizer&&!e.ignoreLayout&&(r=this.getRowHeight(Math.floor(parseInt(n)/this.rowCount)),i=this.getExpandedChildHeight(e,r),void 0===(s=e.resolveHeight(i))&&(s=i),e.resolveChildrenHeight(s))},runWidthWrap:function(t){var e,i,s,r;for(var n in this.sizerChildren)!(e=this.sizerChildren[n])||e.isRexSizer&&e.ignoreLayout||!e.runWidthWrap||(r=this.getColumnWidth(parseInt(n)%this.columnCount),i=this.getExpandedChildWidth(e,r),e.isRexSizer&&void 0===(s=e.resolveWidth(i))&&(s=i),e.runWidthWrap(s));return this},runHeightWrap:function(t){var e,i,s,r;for(var n in this.sizerChildren)!(e=this.sizerChildren[n])||e.isRexSizer&&e.ignoreLayout||!e.runHeightWrap||(r=this.getRowHeight(Math.floor(parseInt(n)/this.rowCount)),i=this.getExpandedChildHeight(e,r),e.isRexSizer&&void 0===(s=e.resolveHeight(i))&&(s=i),e.runHeightWrap(s));return this},resetGrid:function(t,e,i,s,r){if(void 0===i&&(i=0),void 0===s&&(s=0),this.columnCount=t,this.rowCount=e,this.gridCount=t*e,this.removeAll(),this.sizerChildren.length=t*e,AS(this.sizerChildren,null),this.columnProportions=[],this.columnProportions.length=t,"number"==typeof i)AS(this.columnProportions,i);else for(var n=0;n0?e+=t:0===t&&(this.hasColumnProportion0Child=!0);return e},HS=function(){for(var t,e=0,i=0;i0?e+=t:0===t&&(this.hasRowProportion0Child=!0);return e};const US=Phaser.Utils.Objects.IsPlainObject,NS=Phaser.Utils.Objects.GetValue;class $S extends Cb{constructor(t,e,i,s,r,n,a,o,h,l){US(e)?(e=NS(l=e,"x",0),i=NS(l,"y",0),s=NS(l,"width",void 0),r=NS(l,"height",void 0),n=NS(l,"column",l.col||0),a=NS(l,"row",0),o=NS(l,"columnProportions",0),h=NS(l,"rowProportions",0)):US(s)?(s=NS(l=s,"width",void 0),r=NS(l,"height",void 0),n=NS(l,"column",l.col||0),a=NS(l,"row",0),o=NS(l,"columnProportions",0),h=NS(l,"rowProportions",0)):US(n)?(n=NS(l=n,"column",l.col||0),a=NS(l,"row",0),o=NS(l,"columnProportions",0),h=NS(l,"rowProportions",0)):US(o)&&(o=NS(l=o,"columnProportions",0),h=NS(l,"rowProportions",0)),super(t,e,i,s,r,l),this.type="rexGridSizer",this.sizerChildren=[],this.addChildrenMap("items",this.sizerChildren),this.setCreateCellContainerCallback(NS(l,"createCellContainerCallback")),this.setIndentLeft(NS(l,"space.indentLeftOdd",0),NS(l,"space.indentLeftEven",0)),this.setIndentTop(NS(l,"space.indentTopOdd",0),NS(l,"space.indentTopEven",0)),this.resetGrid(n,a,o,h,NS(l,"space",void 0))}destroy(t){this.scene&&!this.ignoreDestroy&&(super.destroy(t),this.columnProportions=void 0,this.rowProportions=void 0,this.columnWidth=void 0,this.rowHeight=void 0,this.createCellContainerCallback=void 0)}setColumnProportion(t,e){return t>=this.columnProportions.length||(this.columnProportions[t]=e),this}setRowProportion(t,e){return t>=this.rowProportions.length||(this.rowProportions[t]=e),this}get totalColumnProportions(){return void 0===this._totalColumnProportions&&(this._totalColumnProportions=GS.call(this)),this._totalColumnProportions}get totalRowProportions(){return void 0===this._totalRowProportions&&(this._totalRowProportions=HS.call(this)),this._totalRowProportions}getChildAt(t,e){return this.sizerChildren[e*this.columnCount+t]}childToGridIndex(t,e){if(!t)return null;var i=this.sizerChildren.indexOf(t);return-1===i?null:(void 0===e&&(e={}),e.x=i%this.columnCount,e.y=Math.floor(i/this.columnCount),e)}getColumnWidth(t){var e=this.columnProportions[t];return 0===e?this.columnWidth[t]:e*this.proportionWidthLength}getRowHeight(t){var e=this.rowProportions[t];return 0===e?this.rowHeight[t]:e*this.proportionHeightLength}setCreateCellContainerCallback(t){return this.createCellContainerCallback=t,this}}Object.assign($S.prototype,VS),t.register("gridSizer",(function(t,e,i,s,r,n,a,o,h){var l=new $S(this.scene,t,e,i,s,r,n,a,o,h);return this.scene.add.existing(l),l})),P(window,"RexPlugins.UI.GridSizer",$S);var KS=function(t,e,i,s){return e/t<=i?e/(s-1):0},JS=function(t){var e,i,s,r,n,a={lines:[],width:0,height:0},o=this.sizerChildren,h=0,l=a.lines,d=void 0;if(0===this.orientation){for(var c=0,u=o.length;co.height/2)){r>(h=qS(o.left,o.centerY,t,e))&&(r=h,s=n);var h,l=i[n+1];l&&l.y===o.y||r>(h=qS(o.right,o.centerY,t,e))&&(r=h,s=n+1)}}return s};const QS=Phaser.Utils.Objects.IsPlainObject,tP=Phaser.Utils.Objects.GetValue,eP=Phaser.Display.Align.CENTER;var iP=function(t,e,i,s){return"\n"===t?(this.addNewLine(),this):(fv.call(this,t),QS(e)&&(e=tP(r=e,"padding",0),i=tP(r,"key",void 0),s=tP(r,"index",void 0)),void 0===e&&(e=0),(r=this.getSizerConfig(t)).align=eP,r.padding=gv(e),void 0===s||s>=this.sizerChildren.length?this.sizerChildren.push(t):this.sizerChildren.splice(s,0,t),void 0!==i&&this.addChildrenMap(i,t),this);var r},sP={add(t,e,i){if(Tm(t))for(var s=t,r=0,n=s.length;r=0;e--)this.remove(this.sizerChildren[e],t);return this},clear(t){return this.sizerChildren.length=0,Ib.call(this,t),this}},aP={getChildrenWidth:function(t){return this.rexSizer.hidden?0:(void 0===t&&(t=!0),void 0!==(e=0===this.orientation&&t?this.maxChildWidth:this.rexSizer.resolved?this.wrapResult.width:void 0)?e+(this.space.left+this.space.right)*this.scaleX:void 0);var e},getChildrenHeight:function(t){return this.rexSizer.hidden?0:(void 0===t&&(t=!0),void 0!==(e=1===this.orientation&&t?this.maxChildHeight:this.rexSizer.resolved?this.wrapResult.height:void 0)?e+(this.space.top+this.space.bottom)*this.scaleY:void 0);var e},getChildrenSizers:function(t){void 0===t&&(t=[]);for(var e,i=this.sizerChildren,s=0,r=i.length;s=t.dragThreshold?"DRAG":"DRAGBEGIN":"IDLE"}update_DRAGBEGIN(t,e){this.next()}next_DRAG(){var t,e=this.parent;return e.dragState.isUp&&(t=e.outOfBounds?"BACK":e.slidingEnable?"SLIDE":"IDLE"),t}update_DRAG(t,e){var i=this.parent;i.dragState.justMoved&&i.dragging(),this.next()}enter_DRAG(){this.parent.onDragStart()}exit_DRAG(){this.parent.onDragEnd()}next_SLIDE(){var t,e=this.parent;return e.dragState.isDown?t="DRAG":e.isSliding||(t="IDLE"),t}enter_SLIDE(){this.parent.onSliding()}exit_SLIDE(){this.parent.stop()}update_SLIDE(t,e){this.parent.sliding(t,e),this.next()}next_BACK(){var t,e=this.parent;return e.dragState.isDown?t="DRAG":e.isPullBack||(t="IDLE"),t}enter_BACK(){this.parent.onPullBack()}exit_BACK(){this.parent.stop()}update_BACK(t,e){this.parent.pullBack(t,e),this.next()}}const JP=Phaser.Utils.Objects.GetValue,qP=Phaser.Math.Distance.Between;class ZP extends Ra{constructor(t,e){super(t,e),this._enable=void 0,this.rectBoundsInteractive=JP(e,"rectBoundsInteractive",!1),this.rectBoundsInteractive||t.setInteractive(JP(e,"inputConfig",void 0)),this.resetFromJSON(e),this.boot()}resetFromJSON(t){return this.pointer=void 0,this.isInTouched=!1,this.holdStartTime=void 0,this.x=void 0,this.y=void 0,this.preX=void 0,this.preY=void 0,this.localX=void 0,this.localY=void 0,this.justMoved=!1,this.setEnable(JP(t,"enable",!0)),this.holdThreshold=JP(t,"holdThreshold",50),this.pointerOutReleaseEnable=JP(t,"pointerOutRelease",!0),this}boot(){var t=this.scene,e=this.parent;this.rectBoundsInteractive?(t.input.on("pointerdown",this.onPointIn,this),t.input.on("pointerup",this.onPointOut,this),t.input.on("pointermove",this.onPointerMove,this)):(e.on("pointerdown",this.onPointIn,this),e.on("pointerup",this.onPointOut,this),this.pointerOutReleaseEnable&&e.on("pointerout",this.onPointOut,this),e.on("pointermove",this.onPointerMove,this)),t.sys.events.on("preupdate",this.preupdate,this)}shutdown(t){if(!this.isShutdown){var e=this.scene;this.parent,this.rectBoundsInteractive&&(e.input.off("pointerdown",this.onPointIn,this),e.input.off("pointerup",this.onPointOut,this),e.input.off("pointermove",this.onPointerMove,this)),e.sys.events.off("preupdate",this.preupdate,this),this.pointer=void 0,super.shutdown(t)}}get enable(){return this._enable}set enable(t){this._enable!==t&&(t||(this.isInTouched=!1,this.pointer=void 0),this._enable=t)}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}toggleEnable(){return this.setEnable(!this.enable),this}setPointerOutReleaseEnable(t){return void 0===t&&(t=!0),this.pointerOutReleaseEnable=t,this}get isDown(){return this.pointer&&this.pointer.isDown}get isUp(){return!this.isDown}get dx(){return this.x-this.preX}get dy(){return this.y-this.preY}get dt(){return rc(this.scene)}get speed(){return this.x===this.preX&&this.y===this.preY?0:qP(this.preX,this.preY,this.x,this.y)/(.001*this.dt)}get speedX(){return this.dx/(.001*this.dt)}get speedY(){return this.dy/(.001*this.dt)}onPointIn(t,e,i){this.enable&&t.isDown&&void 0===this.pointer&&(this.rectBoundsInteractive&&!Pm(this.parent,t)||(this.pointer=t,this.localX=e,this.localY=i))}onPointOut(t){this.enable&&this.pointer===t&&(this.pointer=void 0)}onPointerMove(t,e,i){this.enable&&t.isDown&&this.pointer===t&&(this.rectBoundsInteractive&&this.pointerOutReleaseEnable&&!Pm(this.parent,t)?this.onPointOut(t):(this.localX=e,this.localY=i))}preupdate(t,e){if(this.enable){var i=this.pointer;this.justMoved=!1,i&&!this.isInTouched?(this.x=i.worldX,this.y=i.worldY,this.preX=i.worldX,this.preY=i.worldY,this.isInTouched=!0,this.holdStartTime=void 0,this.emit("touchstart",i,this.localX,this.localY)):i&&this.isInTouched?this.x===i.x&&this.y===i.y?void 0===this.holdStartTime?this.holdStartTime=t:t-this.holdStartTime>this.holdThreshold&&(this.preX=this.x,this.preY=this.y):(this.preX=this.x,this.preY=this.y,this.x=i.worldX,this.y=i.worldY,this.holdStartTime=void 0,this.justMoved=!0,this.emit("touchmove",i,this.localX,this.localY)):!i&&this.isInTouched&&(this.isInTouched=!1,this.holdStartTime=void 0,this.emit("touchend",i))}}}const QP=Phaser.Utils.Objects.GetValue;class tT{constructor(t){this.resetFromJSON(t)}resetFromJSON(t){return this.setValue(QP(t,"value",0)),this.setSpeed(QP(t,"speed",0)),this.setAcceleration(QP(t,"acceleration",0)),this}reset(){this.setValue(0),this.setSpeed(0),this.setAcceleration(0)}setValue(t){return this.value=t,this}setSpeed(t){return this.speed=t,this}setAcceleration(t){return this.acceleration=t,this}updateSpeed(t){return 0!==this.acceleration&&(this.speed+=this.acceleration*t,this.speed<0&&(this.speed=0)),this}getDeltaValue(t){return this.updateSpeed(t),this.speed<=0?0:this.speed*t}update(t){return this.updateSpeed(t),this.speed>0&&(this.value+=this.getDeltaValue(t)),this}get isMoving(){return this.speed>0}}class eT{constructor(){this.value,this.dir,this.movement=new tT}init(t,e,i,s,r){return this.value=t,this.end=r,this.dir=void 0!==r?tthis.end&&(this.value=this.end):this.valuethis.maxValue}overMin(t){return null!=this.minValue&&t0,Math.abs(e),i)}sliding(t,e){e*=.001;var i=this._slowDown.update(e).value;this.overMax(i)?(this.value=this.maxValue,this._slowDown.stop()):this.overMin(i)?(this.value=this.minValue,this._slowDown.stop()):this.value=i}onPullBack(){var t=this.value,e=this.outOfMinBound?this.minValue:this.maxValue,i=Math.abs(e-t),s=this.backDeceleration,r=Math.sqrt(2*s*i);this._slowDown.init(t,void 0,r,s,e)}pullBack(t,e){e*=.001,this.value=this._slowDown.update(e).value,this._slowDown.isMoving||this._state.next()}stop(){this._slowDown.stop()}}const nT={y:0,v:0,vertical:0,x:1,h:1,horizontal:1},aT=Phaser.Utils.Objects.GetValue;class oT extends Ra{constructor(t,e){switch(super(t,e),this.parent!==this.scene?this.focusMode=aT(e,"focus",!0):this.focusMode=!1,"boolean"==typeof this.focusMode&&(this.focusMode=this.focusMode?1:0),this.setSpeed(aT(e,"speed",.1)),this.setEnable(aT(e,"enable",!0)),this.focusMode){case 0:case 2:this.scene.input.on("wheel",this.onSceneScroll,this);break;default:t.setInteractive(aT(e,"inputConfig",void 0)).on("wheel",(function(t,e,i,s,r){this.tryScroll(i)}),this)}}destroy(){switch(this.focusMode){case 0:case 2:this.scene.input.off("wheel",this.onSceneScroll,this)}}onSceneScroll(t,e,i,s,r,n){(2!==this.focusMode||Pm(this.parent,t))&&this.tryScroll(s)}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}setSpeed(t){return this.speed=t,this}tryScroll(t){if(this.enable)return this.scroll(t),this}scroll(t){return t*=this.speed,this.emit("scroll",t,this.parent,this),this}}const hT=Phaser.Utils.Objects.GetValue;var lT=function(t,e,i,s){var r,n,a="Y"===(i=i.toUpperCase()),o=2===t.scrollMode,h=t.childrenMap.child,l=`slider${i}`;if(r=o||s.hasOwnProperty(l)?hT(s,l,void 0):hT(s,"slider",void 0)){var d,c,u;!0===r&&(r={}),r.orientation=a?1:0,n=function(t,e){void 0===e&&(e={});var i=Ve(e);(e={slider:i}).orientation=i.orientation,delete i.orientation,e.background=i.background,delete i.background,e.buttons=i.buttons,delete i.buttons,e.value=null;var s=new $P(t,e);t.add.existing(s);var r=s.childrenMap.slider;return s.addChildrenMap("track",r.childrenMap.track),s.addChildrenMap("indicator",r.childrenMap.indicator),s.addChildrenMap("thumb",r.childrenMap.thumb),s}(t.scene,r);var p=hT(r,"position",0);"string"==typeof p&&(p=dT[p]);var g,v,f=hT(s,`space.slider${i}`,void 0);void 0===f&&void 0===(f=hT(s,"space.slider",void 0))&&(o?f=0:g=hT(s,"space.child",0)),v=void 0===g?"number"==typeof f:"number"==typeof g,a?0===p?(d=2,c=1,u=void 0===g?v?{left:f}:f:{left:hT(g,"right",g)}):(d=0,c=1,u=void 0===g?v?{right:f}:f:{right:hT(g,"left",g)}):0===p?(d=1,c=2,u=void 0===g?v?{top:f}:f:{top:hT(g,"bottom",g)}):(d=1,c=0,u=void 0===g?v?{bottom:f}:f:{bottom:hT(g,"top",g)}),e.add(n,{column:d,row:c,align:"center",padding:u,expand:!0}),t[`hideUnscrollableSlider${i}`]=hT(r,"hideUnscrollableSlider",!1),t[`adaptThumb${i}SizeMode`]=hT(r,"adaptThumbSize",!1),t[`minThumb${i}Size`]=hT(r,"minThumbSize",void 0)}else t[`hideUnscrollableSlider${i}`]=!1,t[`adaptThumb${i}SizeMode`]=!1,t[`minThumb${i}Size`]=void 0;var m,y,b=hT(s,"scrollDetectionMode");"string"==typeof b&&(b=cT[b]);var x=`scroller${i}`;(m=o||s.hasOwnProperty(x)?hT(s,x,!0):hT(s,"scroller",!0))&&h&&(!0===m&&(m={}),m.orientation=a?0:1,void 0!==b&&(m.rectBoundsInteractive=1===b),y=new rT(h,m),h.isRexContainerLite&&h.sendChildToBack(h));var C,k,w,S,P,T=hT(s,o?`mouseWheelScroller${i}`:"mouseWheelScroller",!1);T&&h&&(void 0!==b&&(T.focus=1===b?2:0),C=new oT(h,T)),t.addChildrenMap(`slider${i}`,n),t.addChildrenMap(`scroller${i}`,y),t.addChildrenMap(`mouseWheelScroller${i}`,C),o&&!a||(t.hideUnscrollableSlider=t[`hideUnscrollableSlider${i}`],t.adaptThumbSizeMode=t[`adaptThumb${i}SizeMode`],t.minThumbSize=t[`minThumb${i}Size`],t.addChildrenMap("slider",n),t.addChildrenMap("scroller",y),t.addChildrenMap("mouseWheelScroller",C)),n&&(o?(k=a?"t":"s",S=`scroll${i}`):(k="t",S="scroll"),n.on("valuechange",(function(e){t[k]=e,t.emit(S,t)}))),y&&(o?(w=`childO${i}`,S=`scroll${i}`):(w="childOY",S="scroll"),y.on("valuechange",(function(e){t[w]=e,t.emit(S,t)}))),C&&(P=o?`addChildO${i}`:"addChildOY",C.on("scroll",(function(e){t[P](-e,!0)})))};const dT={right:0,left:1,bottom:0,top:1},cT={gameObject:0,rectBounds:1},uT=Phaser.Utils.Objects.GetValue;var pT=function(t,e){var i=t.scene,s=[0,1,0],r=[0,1,0],n=uT(e,"width"),a=uT(e,"height");n||uT(e,"child.expandWidth",!0)||(s[1]=0),a||uT(e,"child.expandHeight",!0)||(r[1]=0);var o=new $S(i,{column:3,row:3,columnProportions:s,rowProportions:r});switch(function(t,e,i){var s=bP(i,"child"),r=bP(s,"gameObject",void 0);if(r){var n=bP(i,"space.child",0);t.childMargin={};var a=t.childMargin,o={};if("number"==typeof n)switch(t.scrollMode){case 0:case 1:a.top=0,a.bottom=0,a.left=0,a.right=0;break;default:a.top=n,a.bottom=n,a.left=n,a.right=n}else switch(t.scrollMode){case 0:a.top=bP(n,"top",0),a.bottom=bP(n,"bottom",0),o.left=bP(n,"left",0),o.right=bP(n,"right",0);break;case 1:a.top=bP(n,"left",0),a.bottom=bP(n,"right",0),o.top=bP(n,"top",0),o.bottom=bP(n,"bottom",0);break;default:a.top=bP(n,"top",0),a.bottom=bP(n,"bottom",0),a.left=bP(n,"left",0),a.right=bP(n,"right",0)}e.add(r,{column:1,row:1,align:bP(s,"align","center"),padding:o,expand:{width:bP(s,"expandWidth",!0),height:bP(s,"expandHeight",!0)}})}t.addChildrenMap("child",r)}(t,o,e),t.scrollMode){case 0:lT(t,o,"y",e);break;case 1:lT(t,o,"x",e);break;default:lT(t,o,"y",e),lT(t,o,"x",e)}return o},gT=function(t){var e,i,s,r;switch(this.scrollMode){case 0:case 1:e=this.topChildOY,i=this.bottomChildOY,s=this.childrenMap.scroller,r=this.childrenMap.slider,t=0===this.scrollMode?"Y":"X";break;default:"Y"===(t=t.toUpperCase())?(e=this.topChildOY,i=this.bottomChildOY):(e=this.leftChildOX,i=this.rightChildOX),s=this.childrenMap[`scroller${t}`],r=this.childrenMap[`slider${t}`]}if(s){var n="Y"===t?this.scaleY:this.scaleX;s.setBounds(e,i*n)}r&&r.setEnable(e!==i)},vT=function(t){switch(this.scrollMode){case 0:case 1:(e=this.childrenMap.slider)&&this.hideUnscrollableSlider&&this.setChildVisible(e,this.isOverflow);break;default:t=t.toUpperCase();var e=this.childrenMap[`slider${t}`],i=this[`hideUnscrollableSlider${t}`],s=this[`isOverflow${t}`];e&&i&&this.setChildVisible(e,s)}},fT=function(t){switch(this.scrollMode){case 0:case 1:if(!this.adaptThumbSizeMode)return;if(!(o=this.childrenMap.slider))return;var e=Math.min(this.childVisibleHeight/this.childHeight,1),i=o.childrenMap.track,s=o.childrenMap.thumb,r=this.minThumbSize;if(0===this.scrollMode){var n=i.displayHeight*e;void 0!==r&&n0?t.setText(e).getTextBounds().wrappedText.split("\n"):e.split("\n")}return i},wT=function(t){return(t-this.textLineSpacing)/(this.textLineHeight+this.textLineSpacing)},ST=function(t){return t*(this.textLineHeight+this.textLineSpacing)-this.textLineSpacing},PT=function(t){var e,i=t+this.visibleLinesCount+1;switch(this.textObjectType){case 0:case 2:e=this.lines.slice(t,i).join("\n");break;case 1:var s=this.lines.getLineStartIndex(t),r=this.lines.getLineEndIndex(i-1);e=this.lines.getSliceTagText(s,r,!0)}return e},TT=function(t,e){switch(Ew(t)){case 0:var i=(r=t.style).wordWrapWidth,s=r.wordWrapCallback;r.wordWrapWidth=0,r.wordWrapCallback=void 0,t.setText(e),r.wordWrapWidth=i,r.wordWrapCallback=s;break;case 1:var r,n=(r=t.style).wrapMode;r.wrapMode=0,t.setText(e),r.wrapMode=n;break;case 2:var a=t._maxWidth;t._maxWidth=0,t.setText(e),t._maxWidth=a}},OT=function(){var t=this.textObject.rexSizer;this.textObject.y+=t.offsetY-t.preOffsetY,t.preOffsetY=t.offsetY,this.resetChildPositionState(this.textObject),this.textCropEnable&&MT.call(this)},MT=function(){if(this.textObject.setCrop){var t,e,i=this.textObject.rexSizer.offsetY;i<=0?(t=-i,e=this.height):(t=0,e=this.height-i),this.textObject.setCrop(0,t,this.width,e)}},ET=function(t,e,i){if(i+=this.textLineHeight+this.textLineSpacing,this.textObjectWidth!==e||this._textObjectRealHeight!==i){switch(this.textObjectWidth=e,this._textObjectRealHeight=i,this.textObjectType){case 0:case 1:t.setFixedSize(e,i);var s=t.style,r=Math.max(e,0);0===this.textObjectType?s.wordWrapWidth=r:(0===s.wrapMode&&(s.wrapMode=1),s.wrapWidth=r);break;case 2:t.setMaxWidth(e)}this.setText()}},_T={setText:function(t){return void 0!==t&&(this.text=t),this.lines=kT(this.textObject,this.text,this.lines),this.linesCount=this.lines.length,this._textHeight=void 0,this._textVisibleHeight=void 0,this.updateTextObject(),this},updateTextObject:function(){var t=Math.max(Math.floor(wT.call(this,-this.textOY)),0),e=ST.call(this,t)+this.textOY,i=PT.call(this,t);return TT(this.textObject,i),this.textObject.rexSizer.offsetY=e,OT.call(this),this},preLayout:function(){return this._textLineHeight=void 0,this._textLineSpacing=void 0,this._visibleLinesCount=void 0,this._textHeight=void 0,this._textVisibleHeight=void 0,Av.call(this),this},layoutChildren:function(){var t,e,i,s,r,n,a,o=this.left,h=this.top;(t=this.textObject).rexSizer.hidden||(s=o+(i=(e=t.rexSizer).padding).left*this.scaleX,r=h+i.top*this.scaleY,n=this.width*this.scaleX-(i.left+i.right)*this.scaleX,a=this.height*this.scaleY-(i.top+i.bottom)*this.scaleY,ET.call(this,t,n,a),hv(t,s,r,n,a,e.align),e.preOffsetY=0,OT.call(this),this.textMask&&(this.textMask.setPosition().resize(),this.resetChildPositionState(this.textMask)))}};const RT=Phaser.Utils.Objects.IsPlainObject,LT=Phaser.Utils.Objects.GetValue,BT=Phaser.Display.Align.TOP_LEFT;class IT extends Cb{constructor(t,e,i,s,r,n){RT(e)?(e=LT(n=e,"x",0),i=LT(n,"y",0),s=LT(n,"width",void 0),r=LT(n,"height",void 0)):RT(s)&&(s=LT(n=s,"width",void 0),r=LT(n,"height",void 0)),super(t,e,i,s,r,n),this.type="rexTextBlock",this.textObject=void 0,this.linesCount=0,this.textMask=void 0,this.textObjectType=void 0,this._textLineHeight=void 0,this._textLineSpacing=void 0,this._visibleLinesCount=void 0,this._textHeight=void 0,this._textVisibleHeight=void 0,this._textObjectRealHeight=0,this.lines=void 0,this.text=LT(n,"content",""),this._textOY=0,this.execeedTopState=!1,this.execeedBottomState=!1,this.setClampMode(LT(n,"clampTextOY",!0)),this.alwaysScrollable=LT(n,"alwaysScrollable",!1);var a=LT(n,"background",void 0),o=LT(n,"text",void 0);void 0===o&&(o=DT(t)),this.textCropEnable=LT(n,"textCrop",!!o.setCrop);var h=LT(n,"textMask",!this.textCropEnable);a&&this.addBackground(a),this.add(o),this.sizerChildren=[o];var l=this.getSizerConfig(o);l.align=BT,l.padding=gv(0),l.expand=!0,this.textObject=o,this.textObjectType=Ew(o),l.preOffsetY=0,l.offsetY=0,h&&(this.textMask=Sw.call(this,this.textObject,this)),this.addChildrenMap("background",a),this.addChildrenMap("text",o)}destroy(t){if(this.scene&&!this.ignoreDestroy){if(this.textObject=void 0,this.textMask=void 0,this.lines){switch(this.textObjectType){case 0:case 2:this.lines.length=0;break;case 1:this.lines.destroy()}this.lines=void 0}super.destroy(t)}}setClampMode(t){return void 0===t&&(t=!0),this.clampTextOY=t,this}get textLineHeight(){if(void 0===this._textLineHeight){var t;switch(this.textObjectType){case 0:case 1:var e=this.textObject.style;t=e.metrics.fontSize+e.strokeThickness;break;case 2:var i=this.textObject.fontSize/this.textObject.fontData.size;t=this.textObject.fontData.lineHeight*i}this._textLineHeight=t}return this._textLineHeight}get textLineSpacing(){if(void 0===this._textLineSpacing){var t;switch(this.textObjectType){case 0:case 1:t=this.textObject.lineSpacing;break;case 2:t=0}this._textLineSpacing=t}return this._textLineSpacing}get visibleLinesCount(){return void 0===this._visibleLinesCount&&(this._visibleLinesCount=Math.floor(wT.call(this,this._textObjectRealHeight))),this._visibleLinesCount}get topTextOY(){return 0}get bottomTextOY(){return-this.textVisibleHeight}get textHeight(){return void 0===this._textHeight&&(this._textHeight=ST.call(this,this.linesCount)),this._textHeight}get textObjectHeight(){return this._textObjectRealHeight-(this.textLineHeight+this.textLineSpacing)}get textVisibleHeight(){if(void 0===this._textVisibleHeight){var t=this.textHeight-this.textObjectHeight;!this.alwaysScrollable&&t<0&&(t=0),this._textVisibleHeight=t}return this._textVisibleHeight}textOYExceedTop(t){return void 0===t&&(t=this.textOY),t>this.topTextOY}textOYExeceedBottom(t){return void 0===t&&(t=this.textOY),tthis.linesCount?t=0:s?t=e:r&&(t=i)),this._textOY!==t&&(this._textOY=t,this.updateTextObject()),s&&(this.execeedTopState||this.emit("execeedtop",this,t,e)),this.execeedTopState=s,r&&(this.execeedBottomState||this.emit("execeedbottom",this,t,i)),this.execeedBottomState=r}setTextOY(t){return this.textOY=t,this}set t(t){this.textOY=-this.textVisibleHeight*t}get t(){var t=this.textVisibleHeight;return 0===t?0:this.textOY/-t}setTextOYByPercentage(t){return this.t=t,this}}var DT=function(t){return t.add.text(0,0,"")};Object.assign(IT.prototype,_T);var jT={setText(t){return this.childrenMap.child.setText(t),this.resizeController(),this},appendText(t){return this.setText(this.text+t),this}},AT={scrollToLine(t){return this.setChildOY(-this.lineHeight*t),this},scrollToNextLine(t){void 0===t&&(t=1);var e=this.lineIndex+t;return this.scrollToLine(e),this}};const zT=Phaser.Utils.Objects.GetValue;class FT extends xT{constructor(t,e){void 0===e&&(e={});var i=zT(e,"text",void 0),s=zT(e,"textWidth",void 0),r=zT(e,"textHeight",void 0),n=zT(e,"textCrop",!!i.setCrop),a=zT(e,"textMask",!n),o=zT(e,"content",""),h=new IT(t,{width:s,height:r,text:i,textMask:a,textCrop:n&&!a,content:o,clampTextOY:zT(e,"clampChildOY",!1),alwaysScrollable:zT(e,"alwaysScrollable",!1)});t.add.existing(h),function(t){Object.defineProperty(t,"childOY",{configurable:!0,get:function(){return t.textOY},set:function(e){t.textOY=e}}),Object.defineProperty(t,"topChildOY",{get:function(){return t.topTextOY}}),Object.defineProperty(t,"bottomChildOY",{get:function(){return t.bottomTextOY}}),Object.defineProperty(t,"childVisibleHeight",{get:function(){return t.textObjectHeight}}),Object.defineProperty(t,"childHeight",{get:function(){return t.textHeight}})}(h),e.scrollMode=0,e.type="rexTextArea",e.child={gameObject:h,expandWidth:void 0===s,expandHeight:void 0===r};var l=zT(e,"space",void 0);l&&(l.child=zT(l,"text",0)),super(t,e),this.addChildrenMap("text",i)}get text(){return this.childrenMap.child.text}get lineHeight(){var t=this.childrenMap.child;return t.textLineHeight+t.textLineSpacing}get lineIndex(){return Math.floor(-this.childOY/this.lineHeight)}get linesCount(){return this.childrenMap.child.linesCount}get contentHeight(){return this.childrenMap.child.textHeight}}Object.assign(FT.prototype,jT,AT);const YT=Phaser.Utils.Objects.GetValue;var XT=function(t,e,s){e=e?i(e):{};var r=YT(s,"background",vP),n=YT(s,"text",WT),a=YT(s,"track",vP),o=YT(s,"thumb",vP);r?e.background=r(t,e.background):delete e.background,n?e.text=n(t,e.text):delete e.text;var h=e.slider;!1!==h&&null!==h&&(void 0===h&&(h={}),a?h.track=a(t,h.track):delete h.track,o?h.thumb=o(t,h.thumb):delete h.thumb,e.slider=h);var l=new FT(t,e);return t.add.existing(l),l},WT=function(t,e){var i,s;switch(e&&(e.hasOwnProperty("$type")?i=e.$type:e.hasOwnProperty("key")&&(i="bitmaptext",e.font=e.key)),i){case"bitmaptext":case"bitmap":s=new SS(t,e);break;case"bbcodetext":case"bbcode":s=new ds(t,0,0,"",e);break;case"label":s=new UT(t,e);break;case"textarea":s=XT(t,e);break;default:s=new xS(t,e)}return gP(s,e),t.add.existing(s),s},VT=function(t,e){var i,s;switch(e&&(e.hasOwnProperty("$type")?i=e.$type:e.hasOwnProperty("leftWidth")?i="nineSlice":(e.hasOwnProperty("color")||e.hasOwnProperty("strokeColor"))&&(i="roundRectangle")),i){case"nineSlice":s=e.hasOwnProperty("stretchMode")?new mS(t,e):new gS(t,e);break;case"roundRectangle":s=new lS(t,e);break;default:s=new hS(t,e)}return gP(s,e),t.add.existing(s),s};const GT=Phaser.Utils.Objects.GetValue;var HT=function(t,e,s){e=e?i(e):{};var r=GT(s,"background",vP),n=GT(s,"text",WT),a=GT(s,"icon",VT),o=GT(s,"action",VT);return null!==e.background&&r?e.background=r(t,e.background):delete e.background,null!==e.text&&n?e.text=n(t,e.text):delete e.text,null!==e.icon&&a?e.icon=a(t,e.icon):delete e.icon,null!==e.action&&o?e.action=o(t,e.action):delete e.action,e};class UT extends Ww{constructor(t,e,i){super(t,e=HT(t,e,i)),this.type="rexSimpleLabel"}setActiveState(t){return NT(this.getChildren(),"setActiveState",t),this}setHoverState(t){return NT(this.getChildren(),"setHoverState",t),this}setDisableState(t){return NT(this.getChildren(),"setDisableState",t),this}}var NT=function(t,e,i){for(var s=0,r=t.length;sthis.maxExp&&(t=this.maxExp),void 0===e&&(e=this.getLevel(t)),this._exp=t,this._level=e,this._requiredExp=this.getRequiredExpToNextLevel(e,t),this}get exp(){return this._exp}set exp(t){if(this.hasMaxLevel&&t>this.maxExp&&(t=this.maxExp),tthis.maxLevel?this.exp=this.maxExp:this.exp=this.getExp(t)}get requiredExp(){return this._requiredExp}getExp(t){return void 0===t?this._exp:this.isLevelMapFunction?this.levelTable(t):(this.hasMaxLevel&&t>this.maxLevel&&(t=this.maxLevel),this.levelTable[t])}getLevel(t,e){if(void 0===t)return this._level;for(void 0===e&&(e=0);;){var i=this.getExp(e+1);if(i>t)break;if(e++,this.hasMaxLevel&&i===this.maxExp)break}return e}getRequiredExpToNextLevel(t,e){return void 0===t&&(t=this.level),void 0===e&&(e=this.exp),this.getExp(t+1)-e}checkLevel(t,e){return e>=this.getExp(t)&&e=0;n--)s=cO(t[n],e,i);else for(var n=0,a=t.length;ns?1:it)return this;for(var e=this.commands;;){var i=e[this.index],s=i[1];if(Tm(s)||(s=Bc(fO,i,1)),cO(s,this.scope),this.emit("runcommand",s,this.scope),this.index>=e.length-1)return this.nextTime=0,this.complete(),this;if(this.index++,this.nextTime=this.getNextDt(this.nextTime),this.nextTime>t)return this}}complete(){this.clock.stop(),this.state=2,this.emit("complete",this.parent,this)}getNextDt(t){var e=this.commands[this.index][0];return 1===this.timeUnit&&(e*=1e3),1===this.dtMode&&(e+=t),e}setDtMode(t){return"string"==typeof t&&(t=yO[t]),this.dtMode=t,this}setTimeUnit(t){return"string"==typeof t&&(t=mO[t]),this.timeUnit=t,this}}var fO=[];const mO={ms:0,s:1,sec:1},yO={abs:0,absolute:0,inc:1,increment:1};var bO=function(t,e,i,s,r){var n=(i-e)/(r-s)*this.totalEaseDuration,a=i===r?t+1:t;this.player.append(0,this.setEaseValueDuration,n).append(0,this.easeValueTo,i,s,r).append(0,this.emit,"levelup.start",t,e,i,this).append(n,h).append(0,this.emit,"levelup.end",a,e,i,this),this.player.isPlaying||this.player.start()},xO={setExpTable(t){return this.levelCounter.setTable(t),this},resetExp(t){return this.levelCounter.resetExp(t),this.setValue(this.exp,this.getExp(this.level),this.getExp(this.level+1)),this},getExp(t){return this.levelCounter.getExp(t)},getLevel(t,e){return this.levelCounter.getLevel(t,e)},getRequiredExpToNextLevel(t,e){return this.levelCounter.getRequiredExpToNextLevel(t,e)},gainExp(t){return this.levelCounter.gainExp(t),this},setExp(t){return this.levelCounter.setExp(t),this},setLevel(t){return this.levelCounter.setLevel(t),this}};const CO=Phaser.Utils.Objects.GetValue;class kO extends lO{constructor(t,e){super(t,e),this.type="rexExpBar",this.setTotalEaseDuration(CO(e,"easeDuration",1e3)),this.levelCounter=new dO(CO(e,"levelCounter")),this.player=new vO(this,{scope:this,dtMode:1}),this.levelCounter.on("levelup",bO,this),this.player.on("complete",(function(){this.player.clear(),this.emit("levelup.complete",this.level,this)}),this),this.setValue(this.exp,this.getExp(this.level),this.getExp(this.level+1))}destroy(t){this.scene&&!this.ignoreDestroy&&(this.levelCounter.destroy(),this.levelCounter=void 0,this.player.destroy(),this.player=void 0,super.destroy(t))}get exp(){return this.levelCounter.exp}set exp(t){this.levelCounter.exp=t}get level(){return this.levelCounter.level}set level(t){this.levelCounter.level=t}get requiredExp(){return this.levelCounter.requiredExp}setTotalEaseDuration(t){return this.totalEaseDuration=t,this}}Object.assign(kO.prototype,xO),t.register("expBar",(function(t){var e=new kO(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ExpBar",kO);const wO=xw.prototype.add,SO=xw.prototype.addSpace;var PO=function(t){var e=!t.isRexSpace,i=!e||this.buttonsExpand?1:0;if(0===this.sizerChildren.length)if(e){!this.buttonsExpand&&("right"===this.buttonsAlign||"center"===this.buttonsAlign||"bottom"===this.buttonsAlign)&&SO.call(this),wO.call(this,t,{proportion:i,expand:!0});var s=!this.buttonsExpand&&"center"===this.buttonsAlign;s&&SO.call(this),this.hasTailSpace=s}else wO.call(this,t,{proportion:i,expand:!0}),this.hasTailSpace=!1;else if(this.hasTailSpace){var r=this.sizerChildren.length-1;wO.call(this,t,{index:r,proportion:i,expand:!0})}else wO.call(this,t,{proportion:i,expand:!0});return e&&this.buttonGroup.add(t),this},TO={addButton(t){if(Tm(t))for(var e=t,i=0,s=e.length;i=0;i--)EO.call(this,e[i],t);return this}},RO=function(t,e,i){if(t){var s=this.setValueCallback,r=this.setValueCallbackScope;s&&(r?s.call(r,t,e,i):s(t,e,i)),this.fireEvent("button.statechange",t,e,i)}},LO=function(t){var e=this;t._selected=void 0,Object.defineProperty(t,"selected",{get:function(){return t._selected},set:function(i){if(t._selected!==i){var s=t._selected;t._selected=i,RO.call(e,t,i,s)}},enumerable:!0,configurable:!0}),t.selected=!1},BO={add(t){return this.buttons.push(t),t._click||(t._click=new hu(t,this.clickConfig),t._click.on("click",(function(t,e,i,s){this.fireEvent("button.click",e,i,s)}),this).on("enable",(function(t,e){this.fireEvent("button.enable",e)}),this).on("disable",(function(t,e){this.fireEvent("button.disable",e)}),this).on("over",(function(t,e,i,s){this.fireEvent("button.over",e,i,s)}),this).on("out",(function(t,e,i,s){this.fireEvent("button.out",e,i,s)}),this).on("down",(function(t,e,i,s){this.fireEvent("button.down",e,i,s)}),this).on("up",(function(t,e,i,s){this.fireEvent("button.up",e,i,s)}),this),t.isRexContainerLite&&t.sendChildToBack(t)),this.buttonsType&&(void 0===t.name&&console.error(`${this.parent.constructor.name}: Option button miss value`),LO.call(this,t)),this},addMultiple(t){for(var e=0,i=t.length;e0},setButtonEnable(t,e){var i=this.buttons;if(void 0===t||"boolean"==typeof t){e=t;for(var s=0,r=i.length;s=0;i--)KO.call(this,e[i],t);return this}};const qO=Phaser.Utils.Objects.GetValue;class ZO extends $S{constructor(t,e){void 0===e&&(e={});var i=qO(e,"row",0),s=qO(e,"column",e.col||0),r=qO(e,"createCellContainerCallback"),n=qO(e,"buttons",void 0),a=qO(e,"expand",!0),o=a?1:0;if(r&&(e.createCellContainerCallback=void 0),void 0!==n){i=Math.max(i,n.length);for(var h=0,l=n.length;hr&&QO.addNewLine(this)}else for(n=0,a=t.length;n=0;i--)rM.call(this,e[i],t);return this}};const aM=Phaser.Utils.Objects.GetValue;class oM extends cP{constructor(t,e){void 0===e&&(e={});var i=e.space;"number"==typeof i&&(e.space={item:i,line:i}),super(t,e),this.type="rexFixWidthButtons",this.buttonGroup=new YO({parent:this,eventEmitter:aM(e,"eventEmitter",this),groupName:aM(e,"groupName",void 0),clickConfig:aM(e,"click",void 0)}).setButtonsType(e);var s=aM(e,"background",void 0),r=aM(e,"buttons",void 0);this.buttonsAlign=aM(e,"align",void 0),s&&this.addBackground(s),r&&this.addButtons(r),this.addChildrenMap("background",s),this.addChildrenMap("buttons",this.buttonGroup.buttons)}destroy(t){this.scene&&!this.ignoreDestroy&&(super.destroy(t),this.buttonGroup.destroy(),this.buttonGroup=void 0)}get buttons(){return this.buttonGroup.buttons}get groupName(){return this.buttonGroup.groupName}set groupName(t){this.buttonGroup.groupName=t}get eventEmitter(){return this.buttonGroup.eventEmitter}}Object.assign(oM.prototype,eM,nM,FO,WO),t.register("fixWidthButtons",(function(t){var e=new oM(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.FixWidthButtons",oM);var hM={setAccept(t){return this.childrenMap.fileChooser.setAccept(t),this},setMultiple(t){return this.childrenMap.fileChooser.setMultiple(t),this},loadFile(t,e,i,s,r){return this.childrenMap.fileChooser.loadFile(t,e,i,s,r),this},loadFilePromise(t,e,i,s){return this.childrenMap.fileChooser.loadFilePromise(t,e,i,s)}};const lM=Phaser.Utils.Objects.GetValue;class dM extends Ww{constructor(t,e){super(t,e),this.type="rexFileSelectorButton";var i=new Xk(t);t.add.existing(i),this.addBackground(i),this.addChildrenMap("fileChooser",i),this.setAccept(lM(e,"accept","")),this.setMultiple(lM(e,"multiple",!1)),i.on("change",(function(t){var e=t.files;0!==e.length&&(e=Array.from(e),this.emit("select",e,this))}),this)}get files(){return this.childrenMap.fileChooser.files}}Object.assign(dM.prototype,hM),t.register("fileSelectorButton",(function(t){var e=new dM(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.FileSelectorButton",dM);var cM={getChoice(t){var e=this.childrenMap.choicesSizer;return e?e.getButton(t):void 0},getAction(t){return this.childrenMap.actionsSizer.getButton(t)},getToolbar(t){return this.childrenMap.toolbarSizer.getButton(t)},getLeftToolbar(t){return this.childrenMap.leftToolbarSizer.getButton(t)},setChoiceEnable(t,e){var i=this.childrenMap.choicesSizer;return i&&i.setButtonEnable(t,e),this},setActionEnable(t,e){return this.childrenMap.actionsSizer.setButtonEnable(t,e),this},setToolbarEnable(t,e){return this.childrenMap.toolbarSizer.setButtonEnable(t,e),this},setLeftToolbarEnable(t,e){return this.childrenMap.leftToolbarSizer.setButtonEnable(t,e),this},toggleChoiceEnable(t){var e=this.childrenMap.choicesSizer;return e&&e.toggleButtonEnable(t),this},toggleActionEnable(t){return this.childrenMap.actionsSizer.toggleButtonEnable(t),this},toggleToolbarEnable(t){return this.childrenMap.toolbarSizer.toggleButtonEnable(t),this},toggleLeftToolbarEnable(t){return this.childrenMap.leftToolbarSizer.toggleButtonEnable(t),this},getChoiceEnable(t){var e=this.childrenMap.choicesSizer;return!!e&&e.getButtonEnable(t)},getActionEnable(t){return this.childrenMap.actionsSizer.getButtonEnable(t)},getToolbarEnable(t){return this.childrenMap.toolbarSizer.getButtonEnable(t)},getLeftToolbarEnable(t){return this.childrenMap.leftToolbarSizer.getButtonEnable(t)},emitChoiceClick(t){var e=this.childrenMap.choicesSizer;return e&&e.emitButtonClick(t),this},emitActionClick(t){return this.childrenMap.actionsSizer.emitButtonClick(t),this},emitToolbarClick(t){return this.childrenMap.toolbarSizer.emitButtonClick(t),this},emitLeftToolbarClick(t){return this.childrenMap.leftToolbarSizer.emitButtonClick(t),this},showChoice(t){var e=this.childrenMap.choicesSizer;return e&&e.showButton(t),this},showAction(t){return this.childrenMap.actionsSizer.showButton(t),this},showToolbar(t){return this.childrenMap.toolbarSizer.showButton(t),this},showLeftToolbar(t){return this.childrenMap.leftToolbarSizer.showButton(t),this},hideChoice(t){var e=this.childrenMap.choicesSizer;return e&&e.hideButton(t),this},hideAction(t){return this.childrenMap.actionsSizer.hideButton(t),this},hideToolbar(t){return this.childrenMap.toolbarSizer.hideButton(t),this},hideLeftToolbar(t){return this.childrenMap.leftToolbarSizer.hideButton(t),this},addChoice(t){var e=this.childrenMap.choicesSizer;return e&&e.addButton(t),this},addAction(t){return this.childrenMap.actionsSizer.addButton(t),this},addToolbar(t){return this.childrenMap.toolbarSizer.addButton(t),this},addLeftToolbar(t){return this.childrenMap.leftToolbarSizer.addButton(t),this},removeChoice(t,e){var i=this.childrenMap.choicesSizer;return i&&i.removeButton(t,e),this},removeAction(t,e){return this.childrenMap.actionsSizer.removeButton(t,e),this},removeToolbar(t,e){return this.childrenMap.toolbarSizer.removeButton(t,e),this},removeLeftToolbar(t,e){return this.childrenMap.leftToolbarSizer.removeButton(t,e),this},clearChoices(t){var e=this.childrenMap.choicesSizer;return e&&e.clearButtons(t),this},clearActions(t){return this.childrenMap.actionsSizer.clearButtons(t),this},clearToolbar(t){return this.childrenMap.toolbarSizer.clearButtons(t),this},clearLeftToolbar(t){return this.childrenMap.leftToolbarSizer.clearButtons(t),this},forEachChoice(t,e){var i=this.childrenMap.choicesSizer;return i&&i.forEachButtton(t,e),this},forEachAction(t,e){return this.childrenMap.actionsSizer.forEachButtton(t,e),this},forEachToolbar(t,e){return this.childrenMap.toolbarSizer.forEachButtton(t,e),this},forEachLeftToolbar(t,e){return this.childrenMap.leftToolbarSizer.forEachButtton(t,e),this},setAllButtonsEnable(t){return void 0===t&&(t=!0),this.childrenMap.toolbarSizer&&this.setToolbarEnable(t),this.childrenMap.leftToolbarSizer&&this.setLeftToolbarEnable(t),this.childrenMap.actionsSizer&&this.setActionEnable(t),this.childrenMap.choicesSizer&&this.setChoiceEnable(t),this},getChoicesButtonStates(){var t=this.childrenMap.choicesSizer;return t?t.getAllButtonsState():{}},getChoicesButtonState(t){var e=this.childrenMap.choicesSizer;return void 0===t?e?e.getAllButtonsState():{}:!!e&&e.getButtonState(t)},setChoicesButtonState(t,e){var i=this.childrenMap.choicesSizer;return i&&i.setButtonState(t,e),this},clearChoicesButtonStates(){var t=this.childrenMap.choicesSizer;return t&&t.clearAllButtonsState(),this},getChoicesSelectedButtonName(){var t=this.childrenMap.choicesSizer;return t?t.getSelectedButtonName():""},setChoicesSelectedButtonName(t){var e=this.childrenMap.choicesSizer;return e&&e.setSelectedButtonName(t),this},hasAnyChoice(){var t=this.childrenMap.choicesSizer;return!!t&&t.hasAnyButton()},hasAnyAction(){var t=this.childrenMap.actionsSizer;return!!t&&t.hasAnyButton()},hasAnyToolbar(){var t=this.childrenMap.toolbarSizer;return!!t&&t.hasAnyButton()},hasAnyLeftToolbar(){var t=this.childrenMap.leftToolbarSizer;return!!t&&t.hasAnyButton()}},uM={onCreateModalBehavior(t){t.on("button.click",(function(e,i,s,r,n){var a=!1;switch(i){case"actions":a=!0;break;case"choices":t.hasAnyAction()||(a=!0)}if(a){var o={index:s,text:e.text,button:e,dialog:t};switch(t.buttonsType){case"radio":o.value=t.getChoicesSelectedButtonName();break;case"checkboxes":o.value=t.getChoicesButtonStates();break;default:o.value=void 0}t.modalClose(o)}}))},modal(t,e){return t&&!1===t.defaultBehavior?this.onCreateModalBehavior=!1:delete this.onCreateModalBehavior,xm.modal.call(this,t,e),this}},pM={};Object.assign(pM,cM,uM);const gM=Phaser.Utils.Objects.GetValue;class vM extends xw{constructor(t,e){void 0===e&&(e={}),e.orientation=1,super(t,e),this.type="rexDialog",this.eventEmitter=gM(e,"eventEmitter",this);var i,s,r,n,a=gM(e,"background",void 0),o=gM(e,"title",void 0),h=gM(e,"toolbar",void 0),l=gM(e,"toolbarBackground",void 0),d=gM(e,"leftToolbar",void 0),c=gM(e,"leftToolbarBackground",void 0),u=gM(e,"content",void 0),p=gM(e,"description",void 0),g=gM(e,"choices",void 0),v=gM(e,"choicesBackground",void 0),f=gM(e,"actions",void 0),m=gM(e,"actionsBackground",void 0),y=gM(e,"click",void 0);if(a&&this.addBackground(a),h&&(r=new GO(t,{groupName:"toolbar",background:l,buttons:h,orientation:0,space:{item:gM(e,"space.toolbarItem",0)},click:y,eventEmitter:this.eventEmitter}),t.add.existing(r)),d&&(n=new GO(t,{groupName:"leftToolbar",background:c,buttons:d,orientation:0,space:{item:gM(e,"space.leftToolbarItem",0)},click:y,eventEmitter:this.eventEmitter}),t.add.existing(n)),o||h||d){var b,x=!!o&&gM(e,"expand.title",!0),C=gM(e,"align.title","center"),k=!(o&&!x&&"center"===C||!o&&(h||d));b=k?new xw(t,{orientation:0}):new Yb(t),t.add.existing(b);var w=!!k||{height:!0};if(n&&b.add(n,{align:"left",expand:w}),o){k&&!x&&"right"===C&&b.addSpace();var S={left:gM(e,"space.titleLeft",0),right:gM(e,"space.titleRight",0)},P=x?1:0;b.add(o,{align:C,proportion:P,expand:w,padding:S}),k&&!x&&"left"===C&&b.addSpace()}r&&(k&&!o&&b.addSpace(),b.add(r,{align:"right",expand:w})),(u||p||g||f)&&(S={bottom:gM(e,"space.title",0),top:gM(e,"space.titleTop",0)}),P=gM(e,"proportion.title",0),this.add(b,{padding:S,proportion:P,expand:!0})}if(u){var T=gM(e,"align.content","center"),O=gM(e,"space.content",0),M=(S={left:gM(e,"space.contentLeft",0),right:gM(e,"space.contentRight",0),bottom:p||g||f?O:0},P=gM(e,"proportion.content",0),gM(e,"expand.content",!0));this.add(u,{align:T,padding:S,proportion:P,expand:M})}if(p){T=gM(e,"align.description","center");var E=gM(e,"space.description",0);S={left:gM(e,"space.descriptionLeft",0),right:gM(e,"space.descriptionRight",0),bottom:g||f?E:0},P=gM(e,"proportion.description",0),M=gM(e,"expand.description",!0),this.add(p,{align:T,padding:S,proportion:P,expand:M})}if(g){var _=gM(e,"choicesType","").split("-"),R=fM(_,"wrap")?oM:fM(_,"grid")?ZO:GO,L=fM(_,"radio")?"radio":fM(_,"checkboxes")?"checkboxes":void 0,B={left:gM(e,"space.choicesBackgroundLeft",0),right:gM(e,"space.choicesBackgroundRight",0),top:gM(e,"space.choicesBackgroundTop",0),bottom:gM(e,"space.choicesBackgroundBottom",0)},I=gM(e,"space.choice",0);R===GO?B.item=I:R===oM?(B.item=I,B.line=gM(e,"space.choiceLine",I)):(B.column=gM(e,"space.choiceColumn",I),B.row=gM(e,"space.choiceRow",I));var D={width:gM(e,"choicesWidth",void 0),height:gM(e,"choicesHeight",void 0),groupName:"choices",buttonsType:L,background:v,buttons:g,space:B,click:y,eventEmitter:this.eventEmitter,setValueCallback:gM(e,"choicesSetValueCallback",void 0),setValueCallbackScope:gM(e,"choicesSetValueCallbackScope",void 0)};R===GO&&(D.orientation=fM(_,"x")?0:1),i=new R(t,D),t.add.existing(i);var j=gM(e,"space.choices",0);S={left:gM(e,"space.choicesLeft",0),right:gM(e,"space.choicesRight",0),bottom:f?j:0},T=gM(e,"align.choices","center"),P=gM(e,"proportion.choices",0),M=gM(e,"expand.choices",!0),this.add(i,{align:T,padding:S,proportion:P,expand:M}),this.buttonsType=L}f&&(s=new GO(t,{groupName:"actions",background:m,buttons:f,orientation:0,space:{item:gM(e,"space.action",0)},expand:gM(e,"expand.actions",!1),align:gM(e,"align.actions","center"),click:y,eventEmitter:this.eventEmitter}),t.add.existing(s),S={left:gM(e,"space.actionsLeft",0),right:gM(e,"space.actionsRight",0),bottom:gM(e,"space.actionsBottom",0)},P=gM(e,"proportion.action",0),this.add(s,{align:"center",padding:S,proportion:P,expand:!0})),yM(this,"click"),yM(this,"over"),yM(this,"out"),yM(this,"enable"),yM(this,"disable"),this.addChildrenMap("background",a),this.addChildrenMap("title",o),this.addChildrenMap("toolbar",h),this.addChildrenMap("leftToolbar",d),this.addChildrenMap("content",u),this.addChildrenMap("description",p),this.addChildrenMap("choices",i?i.buttons:void 0),this.addChildrenMap("actions",s?s.buttons:void 0),this.addChildrenMap("choicesSizer",i),this.addChildrenMap("actionsSizer",s),this.addChildrenMap("toolbarSizer",r),this.addChildrenMap("leftToolbarSizer",n)}}var fM=function(t,e){return-1!==t.indexOf(e)},mM={actions:"action",choices:"choice",toolbar:"toolbar",leftToolbar:"leftToolbar"},yM=function(t,e){t.on(`button.${e}`,(function(i,s,r,n,a){mM.hasOwnProperty(s)&&t.emit(`${mM[s]}.${e}`,i,r,n,a)}))};Object.assign(vM.prototype,pM),t.register("dialog",(function(t){var e=new vM(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.Dialog",vM);var bM=function(t,e,i){var s=new UT(t,e,i);return t.add.existing(s),s},xM=function(t){var e=this.childrenMap.title;null===(t=t.title)?e.hide():(e.show(),e.resetDisplayContent(t))},CM=function(t){var e=this.childrenMap.content;if(null===(t=t.content))e.hide();else if(e.show(),e.resetDisplayContent)e.resetDisplayContent(t);else{var i=t||"";e.setText(i)}},kM=function(t){var e=this.childrenMap.actions;if(e){var i=t.buttons;if(i){for(var s=this.scene,r=this.defaultActionConfig,n=this.defaultActionButtonCreator,a=0,o=i.length;a=0&&t=0&&i0&&s)){if(0===n)return 2===e&&(i+=1),i;if(1===e){var a=i;(s=(i+=1)>=0&&i=this.colCount?null:e*this.colCount+t}rowIndexToHeight(t,e){if(this.defaultCellHeightMode)return(e-t+1)*this.defaultCellHeight;for(var i=0,s=t;s<=e;s++)i+=this.getRowHeight(s);return i}colIndexToWidth(t,e){return(e-t+1)*this.defaultCellWidth}getRowHeight(t){var e=this.colCount;if(e<=1)return this.getCellHeight(this.colRowToCellIndex(0,t));for(var i,s=0,r=0;rthis.topTableOY,n=tthis.leftTableOX,n=tt?this.removeCells(t,e-t):this.insertNewCells(e,t-e)),this},insertNewCells:function(t,e){return"object"==typeof t&&(t=t.index),void 0===e&&(e=1),e<=0||(t=_E(t,0,this.cellsCount),this.table.insertNewCells(t,e)),this},removeCells:function(t,e){if("object"==typeof t&&(t=t.index),void 0===e&&(e=1),t<0&&(e+=t,t=0),e<=0)return this;if(t>this.cellsCount)return this;for(var i,s=t,r=t+e;sthis.topChildOY}childOYExeceedBottom(t){return void 0===t&&(t=this.childOY),tthis.leftChildOX}childOXExeceedRight(t){return void 0===t&&(t=this.childOX),tthis.childHeight?t=0:s?t=e:r&&(t=i)),this._childOY!==t&&(this._childOY=t,this.resetChildPosition()),s&&(this.execeedTopState||this.emit("execeedtop",this,t,e)),this.execeedTopState=s,r&&(this.execeedBottomState||this.emit("execeedbottom",this,t,i)),this.execeedBottomState=r}get childOX(){return this._childOX}set childOX(t){var e=this.leftChildOX,i=this.rightChildOX,s=this.childOXExceedLeft(t),r=this.childOXExeceedRight(t);this.clampChildOX&&(this.childVisibleWidth>this.childWidth?t=0:s?t=e:r&&(t=i)),this._childOX!==t&&(this._childOX=t,this.resetChildPosition()),s&&(this.execeedLeftState||this.emit("execeedleft",this,t,e)),this.execeedLeftState=s,r&&(this.execeedRightState||this.emit("execeedright",this,t,i)),this.execeedRightState=r}setChildOY(t){return this.childOY=t,this}setChildOX(t){return this.childOX=t,this}set t(t){this.childOY=-this.visibleHeight*t}get t(){var t=this.visibleHeight;return 0===t?0:this.childOY/-t}set s(t){this.childOX=-this.visibleWidth*t}get s(){var t=this.visibleWidth;return 0===t?0:this.childOX/-t}setChildOYByPercentage(t){return this.t=t,this}setChildOXByPercentage(t){return this.s=t,this}}Object.assign(w_.prototype,b_);const S_=["top","bottom","centerY","center"],P_=["left","right","centerX","center"];var T_=function(t,e,i){var s,r="Y"===(e=e.toUpperCase()),n=this.childrenMap.child;if(r){if(i)for(var a=0,o=S_.length;a=0?0:Math.abs(l)<=Math.abs(d)?l:d}}else{if(i)for(a=0,o=P_.length;a=0?0:Math.abs(c)<=Math.abs(u)?c:u}}switch(this.scrollMode){case 0:case 1:this.childOY+=s;break;default:this[`childO${e}`]+=s}};const O_=Phaser.Utils.Objects.GetValue;class M_ extends xT{constructor(t,e){void 0===e&&(e={});var i=mP(e),s=O_(e,"panel",void 0);void 0===s&&(s={}),s.scrollMode=i,s.clampChildOY=O_(e,"clampChildOY",!1),s.clampChildOX=O_(e,"clampChildOX",!1);var r,n,a=new w_(t,s);switch(t.add.existing(a),i){case 0:r=O_(e,"expand.panel",!0),n=!0;break;case 1:r=!0,n=O_(e,"expand.panel",!0);break;default:r=!0,n=!0}e.type="rexScrollablePanel",e.child={gameObject:a,expandWidth:r,expandHeight:n,align:O_(e,"align.panel","center")};var o=O_(e,"space",void 0);o&&(o.child=O_(o,"panel",0)),super(t,e),this.addChildrenMap("panel",a.child),this.addChildrenMap("panelLayer",a.maskLayer),this.addChildrenMap("mask",a.maskGameObject),this.addChildrenMap("scrollableBlock",a)}setChildrenInteractive(t){return void 0===t&&(t={}),t.hasOwnProperty("eventEmitter")||(t.eventEmitter=this),t.hasOwnProperty("targets")||(t.targets=[this.childrenMap.panel]),yb(this.childrenMap.child,t),this}}var E_={scrollToChild:function(t,e){if(!this.hasChild(t))return this;switch(this.scrollMode){case 0:T_.call(this,t,"y",e);break;case 1:T_.call(this,t,"x",e);break;default:T_.call(this,t,"y",e),T_.call(this,t,"x",e)}return this}};Object.assign(M_.prototype,E_);const __=Phaser.Utils.Objects.GetValue;var R_=function(){var t,e=this.scene,i=this.listCreateBackgroundCallback;i&&(t=i.call(this,e),e.add.existing(t));var s=[],r=this.listCreateButtonCallback;if(r)for(var n=this.options,a=0,o=n.length;a0||this.listMaxHeight>0)){if(s=L_(e,u),this.listMaxHeight>0&&(s.layout(),s.height<=this.listMaxHeight&&(d=s)),!d){0===c&&(c=this.listMaxHeight);var p=B_(e,this.listCreateSliderTrackCallback),g=B_(e,this.listCreateSliderThumbCallback);d=new M_(e,{height:c,scrollMode:0,panel:{child:s,mask:{padding:1}},slider:{track:p,thumb:g,adaptThumbSize:this.listSliderAdaptThumbSizeEnable},scrollDetectionMode:1,scroller:this.listScrollerConfig,mouseWheelScroller:this.listMouseWheelScrollerConfig,space:{panel:__(this.listSpace,"panel",0)}}),e.add.existing(d)}}else u.height=c,s=L_(e,u),d=s;return t&&d.addBackground(t,"background"),this.listDraggable&&d.setDraggable(!0),d!==s&&s.on("button.over",(function(t,e,i,s){d.emit("button.over",t,e,i,s)})).on("button.out",(function(t,e,i,s){d.emit("button.out",t,e,i,s)})).on("button.click",(function(t,e,i,s){d.emit("button.click",t,e,i,s)})),d},L_=function(t,e,i){var s;return i?(e.orientation="x",s=new oM(t,e)):(e.orientation="y",s=new GO(t,e)),t.add.existing(s),s},B_=function(t,e,i){var s;return e&&(s=e.call(i,t),t.add.existing(s)),s};const I_=Phaser.Utils.Objects.GetValue;var D_=function(t,e){var i=I_(e,"expandDirection",void 0);"string"==typeof i&&(i=j_[i]);var s,r,n,a,o,h,l,d=(n="alignTargetX",Td(s=e,r="alignTarget")?J(s,r):n&&Td(s,n)?J(s,n):a&&Td(s,a)?J(s,a):o),c=I_(e,"alignTargetY",d),u=I_(e,"alignOffsetX",0),p=I_(e,"alignOffsetY",0),g=I_(e,"alignSide","").includes("right"),v=I_(e,"bounds"),f=0===i,m=!(f||1===i),y=g?1:0,b=f||m?0:1;t.setOrigin(y,b),h=g?d.getTopRight().x:d.getTopLeft().x,l=c.getBottomLeft().y,t.setPosition(h+u,l+p);var x=v;x||(x=aa(t.scene)),m&&t.getBottomLeft().y>x.bottom&&(l=c.getTopLeft().y,t.setOrigin(0,1).setPosition(h+u,l+p))};const j_={down:0,up:1},A_=Phaser.Utils.Objects.GetValue;class z_ extends im{constructor(t,e){void 0===e&&(e={}),null==e.transitIn&&(e.transitIn=function(t,e){Zv(t,e,"y","Cubic")}),null==e.transitOut&&(e.transitOut=function(t,e){!function(t,e,i,s,r){void 0===s&&(s="Linear");var n={mode:0};switch(i){case 0:case"x":n.end={x:0};break;case 1:case"y":n.end={y:0};break;default:n.end=0}n.duration=e,n.ease=s,void 0===r?r=new Jv(t,n):r.resetFromJSON(n),r.restart()}(t,e,"y","Linear")}),e.manualClose=!0,e.clickOutsideClose=!0,e.destroy=!0,super(t,e),D_(t,e),t.isRexSizer&&t.layout();var i=A_(e,"touchOutsideClose",!1),s=A_(e,"anyTouchClose",!1);s&&(i=!1),s?this.once("open",this.anyTouchClose,this):i&&this.once("open",this.touchOutsideClose,this),this.requestOpen()}shutdown(t){this.isShutdown||(this.scene.input.off("pointerup",this.touchCloseCallback,this),super.shutdown(t))}touchOutsideClose(){return this.scene.input.on("pointerup",this.touchCloseCallback,this),this.clickOutsideTest=!0,this}anyTouchClose(){return this.scene.input.once("pointerup",this.touchCloseCallback,this),this}touchCloseCallback(t){this.clickOutsideTest&&pm(this.parent,t.worldX,t.worldY)||this.requestClose()}onOpen(){this.emit("open",this.parent,this),super.onOpen()}onClose(){this.emit("close",this.parent,this),super.onClose()}}var F_={focusNextButton(){if(!this.isOpened)return this;var t,e=this.currentOverIndex;return t=void 0===e?0:(e+1)%this.listPanel.getButtons().length,this.emitButtonOver(t),this},focusPrevButton(){if(!this.isOpened)return this;var t,e=this.currentOverIndex;if(void 0===e)t=0;else{var i=this.listPanel.getButtons().length;t=(e-1+i)%i}return this.emitButtonOver(t),this}},Y_={openListPanel:function(){if(this.listPanel)return this;if(0===this.options.length)return this;var t,e=R_.call(this);e.on("button.over",(function(t,i,s,r){this.currentOverIndex=i,this.listOnButtonOver&&this.listOnButtonOver.call(this,t,i,s,r),this.emit("button.over",this,e,t,i,s,r)}),this).on("button.out",(function(t,i,s,r){this.currentOverIndex===i&&(this.currentOverIndex=void 0),this.listOnButtonOut&&this.listOnButtonOut.call(this,t,i,s,r),this.emit("button.out",this,e,t,i,s,r)}),this),t=this.listAlignMode&&"label"!==this.listAlignMode?this.getElement(this.listAlignMode):this;var i=new z_(e,{duration:{in:this.listEaseInDuration,out:this.listEaseOutDuration},transitIn:this.listTransitInCallback,transitOut:this.listTransitOutCallback,expandDirection:this.listExpandDirection,alignTargetX:t,alignTargetY:this,alignSide:this.listAlignSide,bounds:this.listBounds}).on("open",(function(){e.on("button.click",(function(t,i,s,r){this.listOnButtonClick&&this.listOnButtonClick.call(this,t,i,s,r),this.emit("button.click",this,e,t,i,s,r),this.dropDownBehavior.requestClose()}),this),this.emit("list.open",this,e)}),this).on("close",(function(){this.listPanel=void 0,this.dropDownBehavior=void 0,this.emit("list.close",this)}),this);return e.onClickOutside((function(){i.requestClose()})),this.listPanel=e,this.dropDownBehavior=i,this.pin(e),this},closeListPanel:function(){return this.dropDownBehavior?(this.dropDownBehavior.requestClose(),this.currentOverIndex=void 0,this):this},toggleListPanel:function(){return this.listPanel?this.closeListPanel():this.openListPanel(),this},emitButtonClick:function(t){if(void 0===t&&(t=this.currentOverIndex),void 0===t)return this;var e=this.listPanel,i=e?e.getButton(t):this.options[t];return this.listOnButtonClick&&this.listOnButtonClick.call(this,i,t),this.emit("button.click",this,e,i,t),this},emitButtonOver:function(t){var e=this.listPanel;return e?(e.emitButtonOver(t),this):this}};Object.assign(Y_,m_,F_);const X_=Phaser.Utils.Objects.GetValue;class W_ extends Ww{constructor(t,e){super(t,e),this.type="rexDropDownList",this.timer=void 0,this.listPanel=void 0,this.currentOverIndex=void 0,this.setOptions(X_(e,"options"));var i=X_(e,"list");this.setWrapEnable(X_(i,"wrap",!1)),this.setCreateButtonCallback(X_(i,"createButtonCallback")),this.setCreateListBackgroundCallback(X_(i,"createBackgroundCallback")),this.setCreateListSliderTrackCallback(X_(i,"createTrackCallback")),this.setCreateListSliderThumbCallback(X_(i,"createThumbCallback")),this.setListSliderAdaptThumbSizeEnable(X_(i,"sliderAdaptThumbSize",!1)),this.setListScrollerConfig(X_(i,"scroller")),this.setListMouseWheelScrollerConfig(X_(i,"mouseWheelScroller")),this.setButtonClickCallback(X_(i,"onButtonClick")),this.setButtonOverCallback(X_(i,"onButtonOver")),this.setButtonOutCallback(X_(i,"onButtonOut")),this.setListExpandDirection(X_(i,"expandDirection")),this.setListEaseInDuration(X_(i,"easeIn",500)),this.setListEaseOutDuration(X_(i,"easeOut",100)),this.setListTransitInCallback(X_(i,"transitIn")),this.settListTransitOutCallback(X_(i,"transitOut")),this.setListMaxHeight(X_(i,"maxHeight",0)),this.setListSize(X_(i,"width"),X_(i,"height",0)),this.setListAlignmentMode(X_(i,"alignParent","text")),this.setListAlignmentSide(X_(i,"alignSide","")),this.setListBounds(X_(i,"bounds")),this.setListSpace(X_(i,"space")),this.setListDraggable(X_(i,"draggable",!1)),this.setValueChangeCallback(X_(e,"setValueCallback"),X_(e,"setValueCallbackScope")),this.setValue(X_(e,"value")),this.onClick(this.toggleListPanel,this)}destroy(t){this.scene&&!this.ignoreDestroy&&(this.listPanel&&(this.listPanel.destroy(t),this.listPanel=void 0),super.destroy(t))}get isOpened(){return!!this.listPanel}setOptions(t){return void 0===t&&(t=[]),this.options=t,this}setValueChangeCallback(t,e){return this.valueChangeCallback=t,this.valueChangeCallbackScope=e,this}setValue(t){return this.value=t,this}get value(){return this._value}set value(t){if(this._value!==t){var e=this._value;this._value=t;var i=this.valueChangeCallback,s=this.valueChangeCallbackScope;i&&(s?i.call(s,this,t,e):i(this,t,e)),this.emit("valuechange",this,t,e)}}}Object.assign(W_.prototype,Y_),t.register("dropDownList",(function(t){var e=new W_(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.DropDownList",W_);var V_=function(t,e,s){void 0===s&&(s={});var r=(e=e?i(e):{}).label||e.button,n=e.button||e.label;delete e.label,delete e.button;var a=s.label||s.button||s,o=s.button||s.label||s,h=HT(t,r,a);h.list=e.list||{},h.list.createButtonCallback=function(t,e){var i=bM(t,n,o).resetDisplayContent(e);return e.hasOwnProperty("value")&&(i.value=e.value),i};var l=e.track;l&&(h.list.createTrackCallback=function(t){return vP(t,l)},delete e.track);var d=e.thumb;return d&&(h.list.createThumbCallback=function(t){return vP(t,d)},delete e.thumb),h.list.onButtonOver=function(t,e,i,s){t.setHoverState&&t.setHoverState(!0)},h.list.onButtonOut=function(t,e,i,s){t.setHoverState&&t.setHoverState(!1)},h};class G_ extends W_{constructor(t,e,i){super(t,e=V_(t,e,i)),this.type="rexSimpleDropDownList"}setOptions(t){void 0===t&&(t=[]);for(var e=0,i=t.length;e0?Math.ceil(s/this.pageLinesCount):1;for(var r=0;r0?t+i:this.totalLinesCount}var s;switch(e>this.totalLinesCount&&(e=this.totalLinesCount),this.textObjectType){case 0:case 2:s=this.lines.slice(t,e).join("\n");break;case 1:var r=this.lines.getLineStartIndex(t),n=this.lines.getLineEndIndex(e-1);((s=this.lines.getSliceTagText(r,n,!0)).match(/\n/g)||[]).length>e-t-1&&(s=s.substring(0,s.length-1))}return s}};Object.assign(K_,H_,N_,$_);const J_=Phaser.Utils.Objects.GetValue;Phaser.Math.Clamp;class q_ extends Ra{constructor(t,e){super(t,{eventEmitter:!1}),this.textObjectType=Ew(this.parent),this.pageStartIndexes=[],this.lines=kT(this.parent,""),this.sections=[],this.resetFromJSON(e)}resetFromJSON(t){this.setMaxLines(J_(t,"maxLines",void 0)),this.setPageBreak(J_(t,"pageBreak","\f\n")),this.setText(J_(t,"text","")),this.startLineIndex=J_(t,"start",-1),this.endLineIndex=J_(t,"end",void 0);var e=J_(t,"page");return void 0===e?this.resetIndex():this.setPageIndex(e),this}toJSON(){return{maxLines:this.maxLines,text:this.content,start:this.startLineIndex,end:this.endLineIndex,page:this.pageIndex,pageBreak:this.pageBreak}}shutdown(t){if(!this.isShutdown){switch(this.textObjectType){case 0:case 2:this.lines.length=0;break;case 1:this.lines.destroy()}this.pageStartIndexes.length=0,this.sections.length=0,this.lines=void 0,this.pageStartIndexes=void 0,this.sections=void 0,super.shutdown(t)}}setMaxLines(t){return this.maxLines=t,this}setPageBreak(t){return this.pageBreak=t,this}get pageCount(){return this.pageStartIndexes.length}get lastPageIndex(){return this.pageCount-1}get isFirstPage(){return this.pageIndex<=0}get isLastPage(){return this.pageIndex>=this.pageCount-1}get totalLinesCount(){return this.lines?this.lines.length:0}get pageLinesCount(){if(void 0!==this.maxLines)return this.maxLines;var t;switch(this.textObjectType){case 0:case 1:var e=this.parent.style.maxLines;t=e>0?e:Math.floor(function(t){var e,i,s;switch(Ew(t)){case 0:case 1:e=t.height-t.padding.top-t.padding.bottom,i=t.lineSpacing,s=t.style.metrics.fontSize+t.style.strokeThickness;break;case 2:e=t.height,i=0;var r=t.fontSize/t.fontData.size;s=t.fontData.lineHeight*r}return(e-i)/(s+i)}(this.parent));break;case 2:t=this.totalLinesCount}return t}get isFirstLine(){return this.startLineIndex<=0}get isLastLine(){return this.endLineIndex===this.totalLinesCount}get content(){return this.sections.join(this.pageBreak)}}Object.assign(q_.prototype,K_);var Z_={setText(t){this.setTextCallback&&(t=this.setTextCallbackScope?this.setTextCallback.call(this.setTextCallbackScope,t,this.isLastChar,this.insertIndex):this.setTextCallback(t,this.isLastChar,this.insertIndex)),this.textWrapEnable?TT(this.parent,t):this.parent.setText(t)},appendText(t){var e=this.text.concat(Ae(t));return this.isTyping?this.setTypingContent(e):this.start(e,void 0,this.textLength),this}},Q_=function(t,e){return t.getPlainText&&(e=t.getPlainText(e)),e},tR=function(t,e){for(var i=void 0,s=0;s0?eR(n,t,a=(o=i)-d,o):"";var c,u=e-d;u>0?(o=(a=0)+u,this.insertIndex=o,c=eR(n,t,a,o)):(c="",this.insertIndex=0),r=c+l}return this.insertChar=r.charAt(this.insertIndex-1),r},sR={start:function(t,e,i,s){return void 0!==t&&this.setTypingContent(t),void 0!==e&&(this.speed=e),void 0===i&&(i=0),this.typingIndex=i+1,0===this.speed?this.stop(!0):(this.setText(""),this.startTimer(s)),this},startFromLine:function(t,e,i,s,r){var n;if(e>0){void 0===s&&(s=0);var a=Q_(this.parent,t);n=tR(a,e)+s}return this.start(t,i,n,r)},stop:function(t){if(this.getTimer()&&this.freeTimer(),t){for(;!this.isLastChar;)iR.call(this,this.text,this.typingIndex,this.textLength,this.typeMode),this.emit("typechar",this.insertChar),this.typingIndex++;this.setText(this.text),this.emit("type"),this.emit("complete",this,this.parent)}return this},pause:function(){var t=this.getTimer();return t&&(t.paused=!0),this},resumeTyping:function(){var t=this.getTimer();return t&&(t.paused=!1),this}};Object.assign(sR,Z_);const rR=Phaser.Utils.Objects.GetFastValue,nR=Phaser.Utils.Objects.GetValue;class aR extends Ra{constructor(t,e){super(t,e),this.timer=null,this.resetFromJSON(e)}resetFromJSON(t){this.setTextWrapEnable(nR(t,"wrap",!1)),this.setTypeMode(nR(t,"typeMode",0)),this.setTypingSpeed(nR(t,"speed",333)),this.setTextCallback=rR(t,"setTextCallback",null),this.setTextCallbackScope=rR(t,"setTextCallbackScope",null),this.setTypingContent(rR(t,"text","")),this.typingIndex=rR(t,"typingIndex",0),this.insertIndex=null,this.insertChar=null;var e=rR(t,"elapsed",null);return null!==e&&this.start(void 0,void 0,this.typingIndex,e),this}shutdown(t){this.isShutdown||(this.freeTimer(),super.shutdown(t))}setTypeMode(t){return"string"==typeof t&&(t=oR[t]),this.typeMode=t,this}setTypeSpeed(t){return this.speed=t,this}setTypingSpeed(t){return this.speed=t,this}setTextWrapEnable(t){return void 0===t&&(t=!0),this.textWrapEnable=t,this}set text(t){var e=Ae(t);this.textWrapEnable&&(e=function(t,e){switch(Ew(t)){case 0:t.style.syncFont(t.canvas,t.context),e=t.runWordWrap(e);break;case 1:e=t.getText(e,void 0,void 0,!0);break;case 2:e=t.setText(e).getTextBounds().wrappedText}return e}(this.parent,e)),this._text=e}get text(){return this._text}get isTyping(){return null!==this.getTimer()}get isLastChar(){return this.typingIndex===this.textLength}setTypingContent(t){return this.text=t,this.textLength=Q_(this.parent,this.text).length,this}onTyping(){var t=iR.call(this,this.text,this.typingIndex,this.textLength,this.typeMode);this.setText(t),this.emit("typechar",this.insertChar),this.emit("type"),this.isLastChar?(this.freeTimer(),this.scene.sys.events.once("preupdate",(function(){this.emit("complete",this,this.parent)}),this)):(this.timer.delay=this.speed,this.typingIndex++)}startTimer(t){var e;return this.timer&&this.freeTimer(),void 0===t?e=0:(this.speed,e=t),this.timer=this.scene.time.addEvent({delay:1e-4,startAt:e,loop:!0,callback:this.onTyping,callbackScope:this}),this}getTimer(){return this.timer}freeTimer(){return this.timer&&(this.timer.remove(),this.timer=null),this}setText(t){this.setTextCallback&&(t=this.setTextCallbackScope?this.setTextCallback.call(this.setTextCallbackScope,t,this.isLastChar,this.insertIndex):this.setTextCallback(t,this.isLastChar,this.insertIndex)),this.textWrapEnable?TT(this.parent,t):this.parent.setText(t)}}const oR={"left-to-right":0,"right-to-left":1,"middle-to-sides":2,"sides-to-middle":3};Object.assign(aR.prototype,sR);const hR=Phaser.Utils.Objects.GetValue,lR={page:0,line:1};class dR extends(function(t,e){return void 0===e&&(e="rexTextBox"),class extends t{constructor(t,i){super(t,i),this.type=e,this.isRunning=!1,this._isPageEnd=!1;var s=this.childrenMap.text,r=hR(i,"expandTextWidth",!1),n=hR(i,"expandTextHeight",!1);if(r||n){var a=Ew(s);switch(a){case 0:case 1:if(s.resize=function(t,e){var i=r?t:0,a=n?e:0;s.setFixedSize(i,a),i>0&&s.setWordWrapWidth(i)},1===a){var o=s.style;0===o.wrapMode&&(o.wrapMode=1)}}r&&(s._minWidth=0),n&&(s._minHeight=0)}this.setTypingMode(hR(i,"typingMode","page")),this.page=new q_(s,hR(i,"page",void 0)),this.typing=new aR(s,hR(i,"typing",i.type)),this.typing.on("complete",this.onTypingComplete,this).on("type",this.onType,this).on("typechar",this.onTypeChar,this),this.textWidthSave=s.width,this.textHeightSave=s.height}setTypingMode(t){return"string"==typeof t&&(t=lR[t]),this.typingMode=t,this}start(t,e){return void 0!==e&&this.setTypingSpeed(e),this.isRunning=!0,this.page.setText(t),this.emit("start"),0===this.typingMode?this.typeNextPage():this.typeNextLine(),this}more(t,e){if(void 0!==e&&this.setTypingSpeed(e),!this.isRunning){if(this.isRunning=!0,this.page.appendText(t),this.emit("start"),0===this.typingMode){this._isPageEnd=!1;var i=this.page.getPage(),s=this.typing.textLength;this.typing.start(i,void 0,s)}return this}this.page.appendText(t),this.typing.appendText(t)}typeNextPage(){if(!this.isRunning)return this;if(this.isLastPage)this.emit("complete");else{this._isPageEnd=!1;var t=this.page.getNextPage();this.typing.start(t)}return this}typeNextLine(){if(!this.isRunning)return this;if(this.isLastLine)this.isRunning=!1,this.emit("pageend"),this.emit("complete");else{var t,e=this.page.getPageOfNextLine();t=this.isFirstLine?0:this.page.pageLinesCount-1,this.typing.startFromLine(e,t)}}pause(){return this.isRunning?(this.isTyping&&(this.typing.pause(),this.emit("pause")),this):this}resume(){return this.isRunning?(this.isTyping||(this.emit("resume"),this.typing.resume()),this):this}stop(t){return this.isRunning?(this.typing.stop(t),this):this}showLastPage(){return this.isRunning?(this.typing.stop(),0===this.typingMode?this.page.showLastPage():this.page.showLastLine(),this.emit("type"),this.onTypingComplete(),this):this}setTypeSpeed(t){return this.typing.setTypingSpeed(t),this}setTypingSpeed(t){return this.typing.setTypingSpeed(t),this}get isTyping(){return this.typing.isTyping}get isPageEnd(){return this._isPageEnd}get isLastPage(){return this.page.isLastPage}get isFirstPage(){return this.page.isFirstPage}get pageCount(){return this.page.pageCount}get pageIndex(){return this.page.pageIndex}get isLastLine(){return this.page.isLastLine}get isFirstLine(){return this.page.isFirstLine}get lineCound(){return this.page.totalLinesCount}get startLineIndex(){return this.page.startLineIndex}get endLineIndex(){return this.page.endLineIndex}get typingSpeed(){return this.typing.speed}onType(){var t=this.childrenMap.text;this.textWidthSave===t.width&&this.textHeightSave===t.height||(this.textWidthSave=t.width,this.textHeightSave=t.height,this.getTopmostSizer().layout()),this.emit("type")}onTypeChar(t){this.emit("typechar",t)}onTypingComplete(){if(0===this.typingMode){this._isPageEnd=!0;var t=this.isLastPage;this.isRunning=!t,this.emit("pageend"),t&&this.emit("complete")}else this.typeNextLine()}}}(ZT)){constructor(t,e){void 0===e&&(e={}),e.hasOwnProperty("layoutMode")||(e.layoutMode=1),super(t,e)}}t.register("textBox",(function(t){var e=new dR(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.TextBox",dR);class cR extends dR{constructor(t,e,i){super(t,e=tO(t,e,i))}}t.register("simpleTextBox",(function(t){var e=new cR(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.SimpleTextBox",cR);const uR=Phaser.Utils.Objects.GetValue;class pR extends xw{constructor(t,e){super(t,e),this.type="rexNumberBar";var i,s,r,n=uR(e,"background",void 0),a=uR(e,"icon",void 0),o=uR(e,"iconMask",void 0),h=uR(e,"slider",void 0),l=uR(e,"text",void 0),d=uR(e,"space.icon",0),c=uR(e,"space.slider",0);(n&&this.addBackground(n),a&&(0===this.orientation?(h||l)&&(s={right:d}):(h||l)&&(s={bottom:d}),this.add(a,{proportion:0,align:"center",padding:s}),o&&(o=Sw.call(this,a,a,1))),h)&&(h.orientation=this.orientation,h.eventEmitter=this,h.value=null,h.hasOwnProperty("input")||(h.input=-1),i=new GP(t,h),t.add.existing(i),0===this.orientation?l&&(s={right:c}):l&&(s={bottom:c}),r=0===this.orientation?void 0===uR(h,"width",void 0)?1:0:void 0===uR(h,"height",void 0)?1:0,this.add(i,{proportion:r,align:"center",padding:s}));l&&this.add(l),this.addChildrenMap("background",n),this.addChildrenMap("icon",a),this.addChildrenMap("iconMask",o),this.addChildrenMap("slider",i),this.addChildrenMap("text",l);var u=uR(e,"valuechangeCallback",null);if(null!==u){var p=uR(e,"valuechangeCallbackScope",void 0);this.on("valuechange",u,p)}this.setEnable(uR(e,"enable",void 0)),this.setValue(uR(e,"value",0))}get enable(){return!!this.childrenMap.slider&&this.childrenMap.slider.enable}set enable(t){this.childrenMap.slider&&this.childrenMap.slider.setEnable(t)}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}get value(){return this.childrenMap.slider?this.childrenMap.slider.value:0}set value(t){this.childrenMap.slider&&(this.childrenMap.slider.value=t)}setValue(t,e,i){return this.childrenMap.slider&&this.childrenMap.slider.setValue(t,e,i),this}addValue(t,e,i){return this.childrenMap.slider&&this.childrenMap.slider.addValue(t,e,i),this}getValue(t,e){return this.childrenMap.slider?this.childrenMap.slider.getValue(t,e):0}easeValueTo(t,e,i){return this.childrenMap.slider&&this.childrenMap.slider.easeValueTo(t,e,i),this}stopEaseValue(){return this.childrenMap.slider&&this.childrenMap.slider.stopEaseValue(),this}setEaseValueDuration(t){return this.childrenMap.slider&&this.childrenMap.slider.setEaseValueDuration(t),this}setEaseValueFunction(t){return this.childrenMap.slider&&this.childrenMap.slider.setEaseValueFunction(t),this}get text(){var t=this.childrenMap.text;return void 0===t?"":t.text?t.text:t.getData("text")}set text(t){var e=this.childrenMap.text;void 0!==e&&(e.setText?e.setText(t):e.setData("text",t))}setText(t){return this.text=t,this}}t.register("numberBar",(function(t){var e=new pR(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.NumberBar",pR),t.register("scrollBar",(function(t){var e=new $P(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ScrollBar",$P);const gR=Phaser.Utils.Objects.GetValue,vR={leftTop:"left-top",centerTop:"center-top",rightTop:"right-top",leftCenter:"left-center",center:"center",rightCenter:"right-center",leftBottom:"left-bottom",centerBottom:"center-bottom",rightBottom:"right-bottom"};class fR extends Yb{constructor(t,e){super(t,e),this.type="rexBadge";var i=gR(e,"background",void 0);i&&this.addBackground(i),this.addChildrenMap("background",i);var s=gR(e,"main",void 0);for(var r in s&&this.add(s,{key:"main",align:"center",expand:!1}),this.addChildrenMap("main",s),vR){var n=gR(e,r,void 0);n&&(this.add(n,{key:r,align:vR[r],expand:!1}),this.addChildrenMap(r,n))}}}t.register("badgeLabel",(function(t){var e=new fR(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.BadgeLabel",fR);const mR=Yb.prototype.add;var yR=function(t,e,i,s,r,n,a,o,h){return t.setVisible(!1),mR.call(this,t,e,i,s,r,n,a,o,h),this},bR={add:yR,addPage:yR};const xR=Dg.prototype.setChildVisible;var CR={getPage:function(t){return void 0===t?null:this.sizerChildren.hasOwnProperty(t)?this.sizerChildren[t]:null},swapPage:function(t,e){this._previousKey=this._currentKey;var i=this.previousPage;i&&(0===this.swapMode?(xR.call(this,i,!1),this.emit("pageinvisible",i,this._previousKey,this)):i.destroy()),t&&!this.sizerChildren.hasOwnProperty(t)&&this.emit("createpage",t,this),this._currentKey=t;var s=this.currentPage;return s&&(xR.call(this,s,!0),this.emit("pagevisible",s,this._currentKey,this),void 0===e&&(e=this.fadeInDuration),e>0&&s.setAlpha(0).fadeIn(e,1)),this},hasPage:function(t){return this.sizerChildren.hasOwnProperty(t)}};Object.assign(CR,bR);const kR=Phaser.Utils.Objects.GetValue;class wR extends Yb{constructor(t,e){super(t,e),this.type="rexPages",this.childrenMap=this.sizerChildren,this._previousKey=void 0,this._currentKey=void 0,this.setSwapMode(kR(e,"swapMode",0)),this.setFadeInDuration(kR(e,"fadeIn",0))}setSwapMode(t){return"string"==typeof t&&(t=SR[t]),this.swapMode=t,this}setFadeInDuration(t){return this.fadeInDuration=t,this}get previousKey(){return this._previousKey}get currentKey(){return this._currentKey}set currentKey(t){this.swapPage(t)}get currentPage(){return this.getPage(this.currentKey)}get previousPage(){return this.getPage(this.previousKey)}get keys(){return Object.keys(this.sizerChildren)}}Object.assign(wR.prototype,CR);const SR={invisible:0,destroy:1};t.register("pages",(function(t){var e=new wR(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.Pages",wR);const PR=Phaser.GameObjects.Mesh;class TR extends PR{get tint(){return 0===this.vertices.length?16777215:this.vertices[0].color}forceUpdate(){return this.dirtyCache[10]=1,this}}const OR=Phaser.Math.Vector3,MR=Phaser.Math.Matrix4;var ER=new OR,_R=new OR,RR=new MR;const LR=Phaser.Utils.Objects.IsPlainObject,BR=Phaser.Utils.Objects.GetValue,IR=Phaser.Geom.Mesh.GenerateGridVerts,DR=Phaser.Math.RadToDeg,jR=Phaser.Math.DegToRad,AR=1+1/Math.sin(jR(45));let zR=class extends TR{constructor(t,e,i,s,r,n){LR(e)&&(e=BR(n=e,"x",0),i=BR(n,"y",0),s=BR(n,"key",null),r=BR(n,"frame",null)),super(t,e,i,s,r),this.type="rexPerspectiveImage",this.setSizeToFrame(),this.resetPerspective(),this.panZ(AR),this.hideCCW=BR(n,"hideCCW",!0);var a=BR(n,"gridWidth",0),o=BR(n,"gridHeight",a);this.resetVerts(a,o),this.prevFrame=this.frame}preUpdate(t,e){this.prevFrame!==this.frame&&(this.prevFrame=this.frame,this.syncSize()),super.preUpdate(t,e)}get originX(){return.5}get originY(){return.5}resetPerspective(){return this.setPerspective(this.width,this.height,45),this}resetVerts(t,e){if(void 0!==t&&(this.gridWidth=t),void 0!==e&&(this.gridHeight=e),this.clear(),this.dirtyCache[9]=-1,0===this.width||0===this.height)return this;var i=this.frame.cutWidth,s=this.frame.cutHeight;0===this.gridWidth?t=Math.max(i/8,32):e=this.gridWidth,e=0===this.gridHeight?Math.max(s/8,32):this.gridHeight,IR({mesh:this,width:i/this.height,height:s/this.height,widthSegments:Math.ceil(i/t),heightSegments:Math.ceil(s/e)});var r=this.transformInfo;return r&&this.transformVerts(r.x,r.y,r.z,r.rotateX,r.rotateY,r.rotateZ),this}syncSize(){return this.setSizeToFrame(),this.resetPerspective(),this.resetVerts(),this}get rotationX(){return this.modelRotation.x}set rotationX(t){this.modelRotation.x=t}get angleX(){return DR(this.rotationX)}set angleX(t){this.rotationX=jR(t)}get rotationY(){return this.modelRotation.y}set rotationY(t){this.modelRotation.y=t}get angleY(){return DR(this.rotationY)}set angleY(t){this.rotationY=jR(t)}get rotationZ(){return this.modelRotation.z}set rotationZ(t){this.modelRotation.z=t}get angleZ(){return DR(this.rotationZ)}set angleZ(t){this.rotationZ=jR(t)}transformVerts(t,e,i,s,r,n){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===r&&(r=0),void 0===n&&(n=0),this.transformInfo||(this.transformInfo={}),this.transformInfo.x=t,this.transformInfo.y=e,this.transformInfo.rotateX=s,this.transformInfo.rotateY=r,this.transformInfo.rotateZ=n,function(t,e,i,s,r,n,a){void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===r&&(r=0),void 0===n&&(n=0),void 0===a&&(a=0),ER.set(e,i,s),_R.set(r,n,a),RR.fromRotationXYTranslation(_R,ER,!0);for(var o=0,h=t.vertices.length;o=0;i--)this.removePage(e[i].name,t);return this}},SL={top:1,left:3,right:5,bottom:7},PL={top:"bottom",left:"right",right:"left",bottom:"top"},TL={setTabsPadding(t,e){return this.childrenMap.tabs.setOuterPadding(t,e),this},getTabsPadding(t){return this.childrenMap.tabs.getOuterPadding(t)}},OL={getPageKey:function(t){var e=this.getElement("tabs.buttons");if(!(t>=e.length))return e[t].name},getPageIndex:function(t){for(var e=this.getElement("tabs.buttons"),i=0,s=e.length;i=a.y)continue;break;case 2:if(n.x<=a.x)continue;break;case 3:if(n.x>=a.x)continue}MB.call(r,s,a.x,a.y)}}(t,s,r,i),t.transitInCallback(e,i,t)},RB={showMessage(t){var e=function(t,e,i){var s=e(t.scene,i,t);if(TB.call(s,(function(){t.removeMessage(s)})),t.displayTime){var r=t.transitInTime+t.displayTime+10;OB.call(s,r,(function(){t.removeMessage(s)}))}return s}(this,this.createMessageLabelCallback,t);return _B(this,e,this.transitInTime),this},removeMessage(t){if(this.getParentSizer(t)!==this)return this;if(!t.__isDestroying){t.__isDestroying=!0;var e=this.transitOutTime;return this.transitOutCallback(t,e,this),OB.call(t,e+10,(function(){delete t.__isDestroying,t.destroy()})),this}},removeAllMessages(){for(var t=this.childrenMap.items,e=0,i=t.length;e0&&{height:this.colorComponentsHeight,formatLabel:this.colorComponentsFormatLabelConfig,inputText:this.colorComponentsInputTextConfig,space:this.colorComponentsSpace};var a=new TI(t,{width:s,height:n,background:e,space:this.colorPickerSpace,hPalette:{position:this.colorPickerHPalettePosition},colorComponents:r,value:this.value});return t.add.existing(a),a},MI={openColorPicker:function(){if(!this.colorPicker){var t=OI.call(this).layout(),e=new z_(t,{duration:{in:this.colorPickerEaseInDuration,out:this.colorPickerEaseOutDuration},transitIn:this.colorPickerTransitInCallback,transitOut:this.colorPickerTransitOutCallback,expandDirection:this.colorPickerExpandDirection,alignTargetX:this,alignTargetY:this,bounds:this.colorPickerBounds,touchOutsideClose:!0}).on("open",(function(){t.on("valuechange",(function(t){this.setValue(t)}),this)}),this).on("close",(function(){this.colorPicker=void 0,this.dropDownBehavior=void 0}),this);return this.colorPicker=t,this.dropDownBehavior=e,this.pin(t),this}}};Object.assign(MI,KB);const EI=Phaser.Utils.Objects.GetValue;class _I extends $B{constructor(t,e){void 0===e&&(e={}),super(t,e),this.type="rexColorInput",e.hasOwnProperty("colorPicker")||(e.colorPicker={background:{color:0}});var i=e.colorPicker,s=!1!==i&&null!==i;if(s){var r;this.setColorPickerSize(EI(i,"width",160),EI(i,"height",170));var n=EI(i,"background");r=n?function(t){return vP(t,n)}:EI(i,"createBackgroundCallback"),this.setCreateColorPickerBackgroundCallback(r),this.setColorPickerHPalettePosition(EI(i,"hPalettePosition",0)),this.setColorPickerExpandDirection(EI(i,"expandDirection")),this.setColorPickerEaseInDuration(EI(i,"easeIn",200)),this.setColorPickerEaseOutDuration(EI(i,"easeOut",200)),this.setColorPickerTransitInCallback(EI(i,"transitIn")),this.setColorPickerTransitOutCallback(EI(i,"transitOut")),this.setColorPickerBounds(EI(i,"bounds"));var a=EI(i,"space");void 0===a&&(a={left:10,right:10,top:10,bottom:10,item:8}),this.setColorPickerSpace(a)}var o=e.colorComponents;if(s&&!1!==o&&null!==o){this.setColorComponentsHeight(EI(o,"height",30)),this.setColorComponentsFormatLabelConfig(EI(o,"formatLabel"));var h=EI(o,"inputText");h||(h=EI(e,"inputText")),this.setColorComponentsInputTextConfig(h);var l=EI(o,"space");void 0===l&&(l={item:8}),this.setColorComponentsSpace(l)}var d=this.childrenMap.swatch;d&&s&&this.onClick(d,this.openColorPicker,this)}}Object.assign(_I.prototype,MI),t.register("colorInput",(function(t){var e=new _I(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ColorInput",_I),t.register("colorInputLite",(function(t){var e=new $B(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ColorInputBase",$B),t.register("colorPicker",(function(t){var e=new mI(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ColorPicker",mI),t.register("colorComponents",(function(t){var e=new SI(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ColorComponents",SI);var RI=function(t){for(var e,i=t.scene.input,s=i.manager,r=s.pointersTotal,n=s.pointers,a=0;a0&&c0&&u0&&b0&&xh;d--){for(c=0;c0&&this.wrapMode!==Ee&&0===this.wrapWidth}setStyle(t,e,i){if(void 0===e&&(e=!0),void 0===i&&(i=!1),t&&t.hasOwnProperty("wordWrap")){var s=t.wordWrap;s.hasOwnProperty("width")&&(t.wrap={mode:"word",width:s.width})}if(t&&t.hasOwnProperty("wrap")){var r=t.wrap;if(r.hasOwnProperty("mode")){var n=r.mode;"string"==typeof n&&(r.mode=Be[n])}else r.hasOwnProperty("width")&&(r.mode=1)}t&&t.rtl&&i&&!t.hasOwnProperty("halign")&&(t.halign="right"),t&&t.hasOwnProperty("fontSize")&&"number"==typeof t.fontSize&&(t.fontSize=t.fontSize.toString()+"px");var a=this.propertyMap;for(var o in a){var h=a[o],l=h[0],d=i?h[1]:this[o],c=h[2];if("wrapCallback"===o||"wrapCallbackScope"===o)this[o]=De(t,l,d);else{var u=Ie(t,l,d);c&&(u=c(u)),this[o]=u}}var p=De(t,"font",null);this._font=null===p?this.fontStyle+" "+this.fontSize+" "+this.fontFamily:p;var g=De(t,"fill",null);null!==g&&(this.color=Jt(g));var v=De(t,"metrics",!1);return v?this.metrics={ascent:De(v,"ascent",0),descent:De(v,"descent",0),fontSize:De(v,"fontSize",0)}:!e&&this.metrics||(this.metrics=Pe(this)),e?this.parent.updateText():this.parent}syncFont(t,e){e.font=this._font}syncStyle(t,e){e.textBaseline="alphabetic",e.fillStyle=this.color,e.strokeStyle=this.stroke,e.lineWidth=this.strokeThickness,e.lineCap="round",e.lineJoin="round"}syncShadow(t,e){e?(t.shadowOffsetX=this.shadowOffsetX,t.shadowOffsetY=this.shadowOffsetY,t.shadowColor=this.shadowColor,t.shadowBlur=this.shadowBlur):(t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowColor=0,t.shadowBlur=0)}update(t){return t&&(this._font=`${this.fontStyle} ${this.fontSize} ${this.fontFamily}`.trim(),this.metrics=Pe(this)),this.parent.updateText(t)}buildFont(){var t=`${this.fontStyle} ${this.fontSize} ${this.fontFamily}`.trim();return t!==this._font&&(this._font=t),this}setFont(t){return"string"==typeof t?(this.fontFamily=t,this.fontSize="",this.fontStyle=""):(this.fontFamily=De(t,"fontFamily","Courier"),this.fontSize=De(t,"fontSize","16px"),this.fontStyle=De(t,"fontStyle","")),this.update(!0)}setFontFamily(t){return this.fontFamily=t,this.update(!0)}setFontStyle(t){return this.fontStyle=t,this.update(!0)}setFontSize(t){return"number"==typeof t&&(t=t.toString()+"px"),this.fontSize=t,this.update(!0)}setTestString(t){return this.testString=t,this.update(!0)}setFixedSize(t,e){return this.fixedWidth=t,this.fixedHeight=e,t&&(this.parent.width=t),e&&(this.parent.height=e),this.update(this.isWrapFitMode)}setResolution(t){return this.resolution=t,this.update(!1)}setXOffset(t){return this.xOffset=t,this.update(!1)}setBackgroundColor(t,e,i){return void 0===i&&(i=!0),this.backgroundColor=Jt(t,this.parent.canvas,this.parent.context),this.backgroundColor2=Jt(e,this.parent.canvas,this.parent.context),this.backgroundHorizontalGradient=i,this.update(!1)}setBackgroundStrokeColor(t,e){return this.backgroundStrokeColor=Jt(t,this.parent.canvas,this.parent.context),this.backgroundStrokeLineWidth=e,this.update(!1)}setBackgroundCornerRadius(t,e){return this.backgroundCornerRadius=t,this.backgroundCornerIteration=e,this.update(!1)}setFill(t){return this.color=Jt(t,this.parent.canvas,this.parent.context),this.update(!1)}setColor(t){return this.color=Jt(t,this.parent.canvas,this.parent.context),this.update(!1)}setStroke(t,e){return void 0===t?this.strokeThickness=0:(void 0===e&&(e=this.strokeThickness),this.stroke=Jt(t,this.parent.canvas,this.parent.context),this.strokeThickness=e),this.update(!0)}setShadow(t,e,i,s,r,n){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i="#000"),void 0===s&&(s=0),void 0===r&&(r=!1),void 0===n&&(n=!0),this.shadowOffsetX=t,this.shadowOffsetY=e,this.shadowColor=Jt(i,this.parent.canvas,this.parent.context),this.shadowBlur=s,this.shadowStroke=r,this.shadowFill=n,this.update(!1)}setShadowOffset(t,e){return void 0===t&&(t=0),void 0===e&&(e=t),this.shadowOffsetX=t,this.shadowOffsetY=e,this.update(!1)}setShadowColor(t){return void 0===t&&(t="#000"),this.shadowColor=Jt(t,this.parent.canvas,this.parent.context),this.update(!1)}setShadowBlur(t){return void 0===t&&(t=0),this.shadowBlur=t,this.update(!1)}setShadowStroke(t){return this.shadowStroke=t,this.update(!1)}setShadowFill(t){return this.shadowFill=t,this.update(!1)}setUnderline(t,e,i){return void 0===t&&(t="#000"),void 0===e&&(e=0),void 0===i&&(i=0),this.underlineColor=Jt(t,this.parent.canvas,this.parent.context),this.underlineThickness=e,this.underlineOffset=i,this.update(!1)}setUnderlineColor(t){return void 0===t&&(t="#000"),this.underlineColor=Jt(t,this.parent.canvas,this.parent.context),this.update(!1)}setUnderlineThickness(t){return void 0===t&&(t=0),this.underlineThickness=t,this.update(!1)}setUnderlineOffset(t){return void 0===t&&(t=0),this.underlineOffset=t,this.update(!1)}setStrikethrough(t,e,i){return void 0===t&&(t="#000"),void 0===e&&(e=0),void 0===i&&(i=0),this.strikethroughColor=Jt(t,this.parent.canvas,this.parent.context),this.strikethroughThickness=e,this.strikethroughOffset=i,this.update(!1)}setStrikethroughColor(t){return void 0===t&&(t="#000"),this.strikethroughColor=Jt(t,this.parent.canvas,this.parent.context),this.update(!1)}setStrikethroughThickness(t){return void 0===t&&(t=0),this.strikethroughThickness=t,this.update(!1)}setStrikethroughOffset(t){return void 0===t&&(t=0),this.strikethroughOffset=t,this.update(!1)}setWrapMode(t){return"string"==typeof t&&(t=Be[t.toLowerCase()]||0),this.wrapMode=t,this.update(!0)}setWrapWidth(t){return this.wrapWidth=t,this.update(!1)}setAlign(t,e){return void 0===t&&(t="left"),void 0===e&&(e="top"),this.halign=t,this.valign=e,this.update(!1)}setHAlign(t){return void 0===t&&(t="left"),this.halign=t,this.update(!1)}setVAlign(t){return void 0===t&&(t="top"),this.valign=t,this.update(!1)}setMaxLines(t){return void 0===t&&(t=0),this.maxLines=t,this.update(!1)}getTextMetrics(){var t=this.metrics;return{ascent:t.ascent,descent:t.descent,fontSize:t.fontSize}}setTextMetrics(t,e){return this.metrics.ascent=t.ascent,this.metrics.descent=t.descent,this.metrics.fontSize=t.fontSize,e&&("string"==typeof e?(this.fontFamily=e,this.fontSize="",this.fontStyle=""):(this.fontFamily=De(e,"fontFamily",this.fontFamily),this.fontSize=De(e,"fontSize",this.fontSize),this.fontStyle=De(e,"fontStyle",this.fontStyle))),this.parent.updateText(!0)}get lineHeight(){return this.metrics.fontSize+this.parent.lineSpacing}toJSON(){var t={},e=this.propertyMap;for(var i in e)t[i]=this[i];return t.metrics=this.getTextMetrics(),t}destroy(){this.parent=void 0}};var Ae=function(t){return null==t?t="":Array.isArray(t)?t=t.join("\n"):"number"==typeof t&&(t=t.toString()),t},ze={draw(t,e,i,s){var r=this.penManager;this.hitAreaManager.clear();var n=this.context;n.save();var a=this.defaultStyle;this.clear(),ie(this,a.backgroundColor,a.backgroundStrokeColor,a.backgroundStrokeLineWidth,a.backgroundCornerRadius,a.backgroundColor2,a.backgroundHorizontalGradient,a.backgroundCornerIteration),t+=this.startXOffset,e+=this.startYOffset;var o,h,l,d,c,u,p=a.halign,g=a.valign,v=a.lineHeight,f=r.lines,m=f.length,y=a.maxLines;y>0&&m>y?(h=y,l="center"===g?Math.floor((m-h)/2):"bottom"===g?m-h:0):(h=m,l=0),d=l+h;var b=this.rtl,x=b?this.parent.width:void 0;u="center"===g?Math.max((s-h*v)/2,0):"bottom"===g?Math.max(s-h*v-2,0):0,u+=e;for(var C=l;C0){var o=this.defaultStyle.metrics,h=i-o.ascent,l=o.fontSize;this.drawRectangle(e,h,t.width,l,a.bgcolor,a)}if(a.underlineThickness>0&&t.width>0){var d=i+a.underlineOffset-a.underlineThickness/2;this.drawLine(e,d,t.width,a.underlineThickness,a.underlineColor,a)}if(t.isTextPen&&(a.buildFont(),a.syncFont(r,n),a.syncStyle(r,n),this.drawText(e,i,t.text,a)),t.isImagePen&&this.drawImage(e,i,t.prop.img,t.prop.color,a),a.strikethroughThickness>0&&t.width>0&&(d=i+a.strikethroughOffset-a.strikethroughThickness/2,this.drawLine(e,d,t.width,a.strikethroughThickness,a.strikethroughColor,a)),n.restore(),t.hasAreaMarker&&t.width>0){var c,u=t.prop.area;if(u)c={key:u};else{var p=t.prop.url;c={key:`url:${p}`,url:p}}this.hitAreaManager.add(e,i-this.startYOffset,t.width,this.defaultStyle.lineHeight,c)}},clear(){var t=this.canvas;this.context.clearRect(0,0,t.width,t.height)},drawRectangle(t,e,i,s,r,n){this.autoRound&&(t=Math.round(t),e=Math.round(e));var a=this.context;a.fillStyle=r,a.fillRect(t,e,i,s)},drawLine(t,e,i,s,r,n){this.autoRound&&(t=Math.round(t),e=Math.round(e));var a=this.context;n.syncShadow(a,n.shadowStroke);var o=a.lineCap;a.lineCap="butt",a.strokeStyle=r,a.lineWidth=s,a.beginPath(),a.moveTo(t,e),a.lineTo(t+i,e),a.stroke(),a.lineCap=o},drawText(t,e,i,s){this.autoRound&&(t=Math.round(t),e=Math.round(e));var r=this.context;s.stroke&&"none"!==s.stroke&&s.strokeThickness>0&&(s.syncShadow(r,s.shadowStroke),r.strokeText(i,t,e)),s.color&&"none"!==s.color&&(s.syncShadow(r,s.shadowFill),r.fillText(i,t,e))},drawImage(t,e,i,s,r){e-=this.startYOffset,this.parent.imageManager.draw(i,this.context,t,e,s,this.autoRound)}};const Fe=Phaser.Utils.Objects.GetValue,Ye=Te,Xe=Oe;class We{constructor(t){this.prop={},this.resetFromJSON(t)}resetFromJSON(t){this.text=Fe(t,"text",""),this.x=Fe(t,"x",0),this.y=Fe(t,"y",0),this.width=Fe(t,"width",0);var e=Fe(t,"prop",null);null===e&&(e={}),this.prop=e,this.newLineMode=Fe(t,"newLineMode",0),this.startIndex=Fe(t,"startIndex",0)}get plainText(){var t=this.text;return this.newLineMode===Xe&&(t+="\n"),t}get wrapText(){var t=this.text;return this.newLineMode!==Ye&&(t+="\n"),t}get rawTextLength(){var t=this.text.length;return this.newLineMode===Xe&&(t+=1),t}get endIndex(){return this.startIndex+this.rawTextLength}get lastX(){return this.x+this.width}get isTextPen(){return""!==this.text}get isImagePen(){return!!this.prop.img}get hasAreaMarker(){return!!this.prop.area||!!this.prop.url}}var Ve=function(t,e){var i=Array.isArray(t);if(void 0===e?e=i?[]:{}:q(e),i){e.length=t.length;for(var s=0,r=t.length;s=this.lines.length)return this.getLineEndIndex(t);var e=this.lines[t];return e&&e[0]?e[0].startIndex:0}getLineEndIndex(t){t>=this.lines.length&&(t=this.lines.length-1);var e,i,s=!1;for(e=t;e>=0&&!(s=null!=(i=this.lines[e])&&i.length>0);e--);return s?i[i.length-1].endIndex:0}getLineWidth(t){var e=this.lines[t];if(!e)return 0;var i=e[e.length-1];return null==i?0:i.lastX}getMaxLineWidth(){if(void 0!==this.maxLinesWidth)return this.maxLinesWidth;for(var t,e=0,i=0,s=this.lines.length;ie&&(e=t);return this.maxLinesWidth=e,e}getLineWidths(){for(var t=[],e=0,i=this.lines.length;e=t&&h<=e||(a=a.substring(t-o,e-o)),this.tagToTextScope?c+=this.tagToText.call(this.tagToTextScope,a,l,d):c+=this.tagToText(a,l,d),d=l,!(h>=e)));u++);return c}get length(){return this.lines.length}set length(t){this.clear()}}var $e={};const Ke=Phaser.Geom.Rectangle;var Je=new I;class qe{constructor(){this.hitAreas=[]}destroy(){this.clear()}clear(){for(var t=0,e=this.hitAreas.length;ts&&pi(v)){""!==b?a.push(n.getLine(b,x,ai)):0===C&&r>0&&a.push(n.getLine("",0,ai)),a.push(...ci(v,e,li,s,0,n));var w=a.pop();b=w.text,x=w.width,n.freeLine(w)," "===b&&(b="",x=0)}else(m=x+f)>h?(a.push(n.getLine(b,x,ai)),b=v,x=f,h=s):(b+=v,x=m),C===k-1&&a.push(n.getLine(b,x,l))}return a},ui=function(t,e){var i;switch(e){case hi:i=[];for(var s=0,r=(t=t.split(" ")).length;s0&&e!==vi&&i0&&t>e&&(t=e),t}get linesWidth(){return Math.ceil(this.penManager.getMaxLineWidth())}get linesHeight(){var t=this.displayLinesCount,e=this.defaultStyle.lineHeight*t;return t>0&&(e-=this.defaultStyle.lineSpacing),e}get imageManager(){return this.parent.imageManager}get rtl(){return this.parent.style.rtl}newPenManager(){return new Ne({pensPool:this.pensPool,linesPool:this.linesPool,tagToText:this.parser.propToTagText,tagToTextScope:this.parser})}get tmpPenManager(){return null===this._tmpPenManager&&(this._tmpPenManager=this.newPenManager()),this._tmpPenManager}getPlainText(t,e,i){var s;if(null==t)s=this.penManager.plainText;else{var r=this.parser.splitText(t,1);s="";for(var n=0,a=r.length;n${t}`:e.hasOwnProperty("_style")?`${t}`:t}destroy(){this.tags=void 0}isTextTag(t){var e=this.tags[t];return!!e&&null==e.img}};var gs=function(t){for(var e,i,s,r={},n=0,a=(t=t.split(";")).length;n=1&&(s.color=o[0]),h>=2&&(s.thickness=parseInt(o[1].replace("px","")));break;case"shadow":o=s.split(" "),s={},(h=o.length)>=1&&(s.color=o[0]),h>=2&&(s.offsetX=parseInt(o[1].replace("px",""))),h>=3&&(s.offsetY=parseInt(o[2].replace("px",""))),h>=4&&(s.blur=parseInt(o[3].replace("px","")));break;case"u":case"underline":case"s":case"strikethrough":var h;o=s.split(" "),s={},(h=o.length)>=1&&(s.color=o[0]),h>=2&&(s.thickness=parseInt(o[1].replace("px",""))),h>=3&&(s.offset=parseInt(o[2].replace("px",""))),"underline"===i?i="u":"strikethrough"===i&&(i="s");break;case"y":s=parseFloat(s)}r[i]=s}return r},vs=function(t){return 0===(t=t.replace(Cs,"")).length},fs=/<\s*class=["|']([^"|']+)["|']\s*\>([\s\S]*?)<\s*\/class\s*\>|<\s*style=["|']([^"|']+)["|']\s*\>([\s\S]*?)<\s*\/style\s*\>/g,ms=/<\s*class=/i,ys=/<\s*class=["|']([^"|']+)["|']\s*\>([\s\S]*?)<\s*\/class\s*\>/,bs=/<\s*style=/i,xs=/<\s*style=["|']([^"|']+)["|']\s*\>([\s\S]*?)<\s*\/style\s*\>/,Cs=/^\s+|\s+$/;const ks=Phaser.Utils.Objects.GetValue;class ws extends Yi{constructor(t,e,i,s,r){var n=ks(r,"tags",void 0);super(t,e,i,s,r,"rexTagText",new ps(n))}addTag(t,e){return this.parser.addTag(t,e),this.updateText(!0)}addTags(t){for(var e in t)this.parser.addTag(e,t[e]);return this.updateText(!0)}getTag(t){return this.parser.getTag(t)}preDestroy(){super.preDestroy(),this.parser.destroy(),this.parser=void 0}}t.register("tagText",(function(t,e,i,s){var r=new ws(this.scene,t,e,i,s);return this.scene.add.existing(r),r})),P(window,"RexPlugins.UI.TagText",ws);const Ss=Phaser.Utils.Objects.GetValue;var Ps=function(t,e){return void 0===e?t:t[e]},Ts=function(t,e,i){void 0===t&&(t={}),void 0===e&&(e=0);var s=typeof e;return"string"===s?t[e]=i:"number"===s?(t.left=e,t.right=e,t.top=e,t.bottom=e):(t.left=Ss(e,"left",0),t.right=Ss(e,"right",0),t.top=Ss(e,"top",0),t.bottom=Ss(e,"bottom",0)),t};let Os=class{constructor(t,e){this.setParent(t),this.type=e,this.renderable=!1,this.reset().setActive()}destroy(){this.parent.removeChild(this)}setParent(t){return this.parent=t,this}get scene(){return this.parent.scene}get canvas(){return this.parent?this.parent.canvas:null}get context(){return this.parent?this.parent.context:null}setDirty(t){return t&&this.parent&&(this.parent.dirty=!0),this}get active(){return this._active}set active(t){this.setDirty(this._active!=t),this._active=t}setActive(t){return void 0===t&&(t=!0),this.active=t,this}modifyPorperties(t){return this}onFree(){this.reset().setParent()}reset(){return this}render(){}contains(t,e){return!1}};Object.assign(Os.prototype,Z);var Ms={renderContent(){},render(){if(!this.willRender)return this;var t=this.context;if(t.save(),t.globalAlpha=this.alpha,this.toLocalPosition){var e=this.drawX,i=this.drawY;this.autoRound&&(e=Math.round(e),i=Math.round(i)),t.translate(e,i),t.scale(this.scaleX,this.scaleY),t.rotate(this.rotation)}return this.drawBelowCallback&&this.drawBelowCallback(this),this.renderContent(),this.drawAboveCallback&&this.drawAboveCallback(this),t.restore(),this}};const Es=Phaser.Math.RotateAround;var _s;const Rs=Phaser.Geom.Rectangle;var Ls,Bs=function(t){void 0===Ls&&(Ls=new Rs);var e=t.drawTLX,i=t.drawTLY;return Ls.setTo(e,i,t.drawTRX-e,t.drawBLY-i),Ls};const Is=Phaser.Math.RotateAround;var Ds,js=function(t,e,i,s){return void 0===s?s={}:!0===s&&(void 0===Ds&&(Ds={}),s=Ds),s.x=e,s.y=i,0!==t.rotation&&Is(s,0,0,t.rotation),s.x=s.x*t.scaleX+t.drawX,s.y=s.y*t.scaleY+t.drawY,s};const As=Phaser.GameObjects.Components.TransformMatrix;var zs,Fs,Ys={},Xs=function(t,e,i,s,r){var n=js(e,i,s,!0),a=function(t,e,i,s){void 0===s?s={}:!0===s&&(s=Ys);var r=e-t.width*t.originX,n=i-t.height*t.originY;return void 0===zs&&(zs=new As,Fs=new As),t.parentContainer?t.getWorldTransformMatrix(zs,Fs):zs.applyITRS(t.x,t.y,t.rotation,t.scaleX,t.scaleY),zs.transformPoint(r,n,s),s}(t,n.x,n.y,r);return a},Ws=function(t,e,i,s,r){"number"!=typeof i&&(r=i,i=0,s=0);var n=e.drawCenterX+i,a=e.drawCenterY+s;return Xs(t,e,n,a,r)},Vs={contains:function(t,e){if(0===this.width||0===this.height)return!1;var i=function(t,e,i,s){return void 0===s?s={}:!0===s&&(void 0===_s&&(_s={}),s=_s),s.x=(t-i.drawX)/i.scaleX,s.y=(e-i.drawY)/i.scaleY,0!==i.rotation&&Es(s,0,0,-i.rotation),s}(t,e,this,!0);return Bs(this).contains(i.x,i.y)},getWorldPosition:function(t,e,i){return Ws(this.parent,this,t,e,i)}};Object.assign(Vs,Ms);const Gs=Phaser.Math.DegToRad,Hs=Phaser.Math.RadToDeg,Us=Phaser.Utils.Objects.GetValue;class Ns extends Os{constructor(t,e){super(t,e),this.renderable=!0,this.scrollFactorX=1,this.scrollFactorY=1,this.toLocalPosition=!0,this.originX=0,this.offsetX=0,this.offsetY=0}get visible(){return this._visible}set visible(t){this.setDirty(this._visible!=t),this._visible=t}setVisible(t){return void 0===t&&(t=!0),this.visible=t,this}get alpha(){return this._alpha}set alpha(t){this.setDirty(this._alpha!=t),this._alpha=t}setAlpha(t){return this.alpha=t,this}get x(){return this._x}set x(t){this.setDirty(this._x!=t),this._x=t}setX(t){return this.x=t,this}get y(){return this._y}set y(t){this.setDirty(this._y!=t),this._y=t}setY(t){return this.y=t,this}setPosition(t,e){return this.x=t,this.y=e,this}setInitialPosition(t,e){return this.x0=t,this.y0=e,this}setScrollFactorX(t){return this.scrollFactorX=t,this}setScrollFactorY(t){return this.scrollFactorY=t,this}setScrollFactor(t,e){return void 0===e&&(e=t),this.scrollFactorX=t,this.scrollFactorY=e,this}get rotation(){return this._rotation}set rotation(t){this.setDirty(this._rotation!=t),this._rotation=t}setRotation(t){return this.rotation=t,this}get angle(){return Hs(this._rotation)}set angle(t){this.rotation=Gs(t)}setAngle(t){return this.angle=t,this}get scaleX(){return this._scaleX}set scaleX(t){this.setDirty(this._scaleX!==t),this._scaleX=t}setScaleX(t){return this.scaleX=t,this}get width(){return 0}set width(t){}setWidth(t,e){return void 0===e&&(e=!1),this.width=t,e&&(this.scaleY=this.scaleX),this}get leftSpace(){return this._leftSpace}set leftSpace(t){this.setDirty(this._leftSpace!==t),this._leftSpace=t}setLeftSpace(t){return this.leftSpace=t,this}get rightSpace(){return this._rightSpace}set rightSpace(t){this.setDirty(this._rightSpace!==t),this._rightSpace=t}setRightSpace(t){return this.rightSpace=t,this}get outerWidth(){return this.width+this.leftSpace+this.rightSpace}get scaleY(){return this._scaleY}set scaleY(t){this.setDirty(this._scaleY!==t),this._scaleY=t}setScaleY(t){return this.scaleY=t,this}get height(){return 0}set height(t){}setHeight(t,e){return void 0===e&&(e=!1),this.height=t,e&&(this.scaleX=this.scaleY),this}setScale(t,e){return void 0===e&&(e=t),this.scaleX=t,this.scaleY=e,this}setOrigin(t){return this.originX=t,this}setAlign(t){return this.align=t,this}modifyPorperties(t){if(!t)return this;t.hasOwnProperty("x")&&this.setX(t.x),t.hasOwnProperty("y")&&this.setY(t.y),t.hasOwnProperty("rotation")?this.setRotation(t.rotation):t.hasOwnProperty("angle")&&this.setAngle(t.angle),t.hasOwnProperty("alpha")&&this.setAlpha(t.alpha);var e=Us(t,"width",void 0),i=Us(t,"height",void 0),s=Us(t,"scaleX",void 0),r=Us(t,"scaleY",void 0);return void 0!==e?void 0===i&&void 0===r?this.setWidth(e,!0):this.setWidth(e):void 0!==s&&this.setScaleX(s),void 0!==i?void 0===e&&void 0===s?this.setHeight(i,!0):this.setHeight(i):void 0!==r&&this.setScaleY(r),t.hasOwnProperty("leftSpace")&&this.setLeftSpace(t.leftSpace),t.hasOwnProperty("rightSpace")&&this.setRightSpace(t.rightSpace),t.hasOwnProperty("align")&&this.setAlign(t.align),this}setDrawBelowCallback(t){return this.drawBelowCallback=t,this}setDrawAboveCallback(t){return this.drawAboveCallback=t,this}reset(){return this.setVisible().setAlpha(1).setPosition(0,0).setRotation(0).setScale(1,1).setLeftSpace(0).setRightSpace(0).setOrigin(0).setAlign().setDrawBelowCallback().setDrawAboveCallback(),this}get willRender(){return this.visible&&this.alpha>0}get drawX(){var t=this.x+this.leftSpace+this.offsetX-this.originX*this.width;return this.parent._textOX*this.scrollFactorX+t}get drawY(){var t=this.y+this.offsetY;return this.parent._textOY*this.scrollFactorY+t}get drawTLX(){return 0}get drawTLY(){return 0}get drawBLX(){return 0}get drawBLY(){return 0}get drawTRX(){return 0}get drawTRY(){return 0}get drawBRX(){return 0}get drawBRY(){return 0}get drawCenterX(){return(this.drawTRX+this.drawTLX)/2}get drawCenterY(){return(this.drawBLY+this.drawTLY)/2}}Object.assign(Ns.prototype,Vs);var $s=function(t,e,i){return e.hasOwnProperty(t)?e[t]:i[t]};const Ks=Phaser.Utils.Objects.GetValue;class Js extends Ns{constructor(t,e){super(t,"background"),this.setScrollFactor(0),this.setColor(Ks(e,"color",null),Ks(e,"color2",null),Ks(e,"horizontalGradient",!0)),this.setStroke(Ks(e,"stroke",null),Ks(e,"strokeThickness",2)),this.setCornerRadius(Ks(e,"cornerRadius",0),Ks(e,"cornerIteration",null))}set color(t){t=Jt(t,this.canvas,this.context),this.setDirty(this._color!=t),this._color=t}get color(){return this._color}set color2(t){t=Jt(t,this.canvas,this.context),this.setDirty(this._color2!=t),this._color2=t}get color2(){return this._color2}set horizontalGradient(t){this.setDirty(this._horizontalGradient!=t),this._horizontalGradient=t}get horizontalGradient(){return this._horizontalGradient}setColor(t,e,i){return void 0===i&&(i=!0),this.color=t,this.color2=e,this.horizontalGradient=i,this}set stroke(t){t=Jt(t,this.canvas,this.context),this.setDirty(this._stroke!=t),this._stroke=t}get stroke(){return this._stroke}set strokeThickness(t){this.setDirty(this._strokeThickness!=t),this._strokeThickness=t}get strokeThickness(){return this._strokeThickness}setStroke(t,e){return null!=t&&void 0===e&&(e=2),this.stroke=t,this.strokeThickness=e,this}set cornerRadius(t){this.setDirty(this._cornerRadius!=t),this._cornerRadius=t}get cornerRadius(){return this._cornerRadius}set cornerIteration(t){this.setDirty(this._cornerIteration!=t),this._cornerIteration=t}get cornerIteration(){return this._cornerIteration}modifyStyle(t){return t.hasOwnProperty("color")&&this.setColor(t.color,$s("color2",t,this),$s("horizontalGradient",t,this)),t.hasOwnProperty("stroke")&&this.setStroke(t.stroke,$s("strokeThickness",t,this)),t.hasOwnProperty("cornerRadius")&&this.setCornerRadius(t.cornerRadius,$s("cornerIteration",t,this)),this}modifyPorperties(t){return super.modifyPorperties(t),this.modifyStyle(t),this}setCornerRadius(t,e){return this.cornerRadius=t,this.cornerIteration=e,this}renderContent(){ie(this.parent,this.color,this.stroke,this.strokeThickness,this.cornerRadius,this.color2,this.horizontalGradient,this.cornerIteration)}}const qs=Phaser.Utils.Objects.GetValue;class Zs extends Ns{constructor(t,e){super(t,"innerbounds"),this.setScrollFactor(0),this.setColor(qs(e,"color",null),qs(e,"color2",null),qs(e,"horizontalGradient",!0)),this.setStroke(qs(e,"stroke",null),qs(e,"strokeThickness",2))}set color(t){t=Jt(t,this.canvas,this.context),this.setDirty(this._color!=t),this._color=t}get color(){return this._color}set color2(t){t=Jt(t,this.canvas,this.context),this.setDirty(this._color2!=t),this._color2=t}get color2(){return this._color2}set horizontalGradient(t){this.setDirty(this._horizontalGradient!=t),this._horizontalGradient=t}get horizontalGradient(){return this._horizontalGradient}setColor(t,e,i){return void 0===i&&(i=!0),this.color=t,this.color2=e,this.horizontalGradient=i,this}set stroke(t){t=Jt(t,this.canvas,this.context),this.setDirty(this._stroke!=t),this._stroke=t}get stroke(){return this._stroke}set strokeThickness(t){this.setDirty(this._strokeThickness!=t),this._strokeThickness=t}get strokeThickness(){return this._strokeThickness}setStroke(t,e){return null!=t&&void 0===e&&(e=2),this.stroke=t,this.strokeThickness=e,this}modifyPorperties(t){super.modifyPorperties(t),t.hasOwnProperty("color")&&this.setColor(t.color,qs(t,"color2",null),qs(t,"horizontalGradient",!0)),t.hasOwnProperty("stroke")&&this.setStroke(t.stroke,qs(t,"strokeThickness",2))}renderContent(){var t,e,i=this.parent.padding,s=i.left,r=i.top,n=this.parent.width-i.left-i.right,a=this.parent.height-i.top-i.bottom,o=this.context;null!=this.color&&(null!=this.color2?((e=this.horizontalGradient?o.createLinearGradient(0,0,n,0):o.createLinearGradient(0,0,0,a)).addColorStop(0,this.color),e.addColorStop(1,this.color2),t=e):t=this.color,o.fillStyle=t,o.fillRect(s,r,n,a));null!=this.stroke&&this.strokeThickness>0&&(o.strokeStyle=this.stroke,o.lineWidth=this.strokeThickness,o.strokeRect(s,r,n,a))}}const Qs=Phaser.Utils.Objects.GetValue;class tr{constructor(t,e){this.parent=t,this.set(e)}toJSON(){return{bold:this.bold,italic:this.italic,fontSize:this.fontSize,fontFamily:this.fontFamily,color:this.color,stroke:this.stroke,strokeThickness:this.strokeThickness,shaodwColor:this.shadowColor,shadowBlur:this.shadowBlur,shadowOffsetX:this.shadowOffsetX,shadowOffsetY:this.shadowOffsetY,offsetX:this.offsetX,offsetY:this.offsetY,leftSpace:this.leftSpace,rightSpace:this.rightSpace,backgroundHeight:this.backgroundHeight,backgroundBottomY:this.backgroundBottomY,align:this.align}}set(t){return this.setBold(Qs(t,"bold",!1)),this.setItalic(Qs(t,"italic",!1)),this.setFontSize(Qs(t,"fontSize","16px")),this.setFontFamily(Qs(t,"fontFamily","Courier")),this.setColor(Qs(t,"color","#fff")),this.setStrokeStyle(Qs(t,"stroke",null),Qs(t,"strokeThickness",0)),this.setShadow(Qs(t,"shadowColor",null),Qs(t,"shadowOffsetX",0),Qs(t,"shadowOffsetY",0),Qs(t,"shadowBlur",0)),this.setOffset(Qs(t,"offsetX",0),Qs(t,"offsetY",0)),this.setSpace(Qs(t,"leftSpace",0),Qs(t,"rightSpace",0)),this.setAlign(Qs(t,"align",void 0)),this.setBackgroundColor(Qs(t,"backgroundColor",null)),this.setBackgroundHeight(Qs(t,"backgroundHeight",void 0)),this.setBackgroundBottomY(Qs(t,"backgroundBottomY",void 0)),this}modify(t){return t.hasOwnProperty("bold")&&this.setBold(t.bold),t.hasOwnProperty("italic")&&this.setItalic(t.italic),t.hasOwnProperty("fontSize")&&this.setFontSize(t.fontSize),t.hasOwnProperty("fontFamily")&&this.setFontFamily(t.fontFamily),t.hasOwnProperty("color")&&this.setColor(t.color),(t.hasOwnProperty("stroke")||t.hasOwnProperty("strokeThickness"))&&this.setStrokeStyle($s("stroke",t,this),$s("strokeThickness",t,this)),t.hasOwnProperty("shadowColor")&&this.setShadowColor(t.shadowColor),(t.hasOwnProperty("shadowOffsetX")||t.hasOwnProperty("shadowOffsetY"))&&this.setShadowOffset($s("shadowOffsetX",t,this),$s("shadowOffsetY",t,this)),t.hasOwnProperty("shadowBlur")&&this.setShadowBlur(t.shaodwBlur),t.hasOwnProperty("offsetX")&&this.setOffsetX(t.offsetX),t.hasOwnProperty("offsetY")&&this.setOffsetY(t.offsetY),t.hasOwnProperty("leftSpace")&&this.setLeftSpace(t.leftSpace),t.hasOwnProperty("rightSpace")&&this.setRightSpace(t.rightSpace),t.hasOwnProperty("align")&&this.setAlign(t.align),t.hasOwnProperty("backgroundColor")&&this.setBackgroundColor(t.backgroundColor),t.hasOwnProperty("backgroundHeight")&&this.setBackgroundHeight(t.backgroundHeight),t.hasOwnProperty("backgroundBottomY")&&this.setBackgroundBottomY(t.backgroundBottomY),this}setUpdateTextFlag(){return this.parent&&(this.parent.updateTextFlag=!0),this}clone(){return new tr(null,this.toJSON())}copyFrom(t){return this.set(t.toJSON()),this}copyTo(t){return t.set(this.toJSON()),this}setBold(t){return void 0===t&&(t=!0),this.bold=t,this.setUpdateTextFlag(),this}setItalic(t){return void 0===t&&(t=!0),this.italic=t,this.setUpdateTextFlag(),this}get fontStyle(){return this.bold&&this.italic?"bold italic":this.bold?"bold":this.italic?"italic":""}setFontSize(t){return"number"==typeof t&&(t=`${t}px`),this.fontSize=t,this.setUpdateTextFlag(),this}setFontFamily(t){return this.fontFamily=t,this.setUpdateTextFlag(),this}get font(){return`${this.fontStyle} ${this.fontSize} ${this.fontFamily}`}setColor(t){return this.color=Jt(t),this}get hasFill(){return null!=this.color}setStrokeStyle(t,e){return this.stroke=Jt(t),void 0!==e&&(this.strokeThickness=e),this}setStrokeThickness(t){return this.strokeThickness=t,this}get hasStroke(){return null!=this.stroke&&this.strokeThickness>0}setShadowColor(t){return this.shadowColor=Jt(t),this}setShadowOffset(t,e){return void 0===t&&(t=0),void 0===e&&(e=0),this.shadowOffsetX=t,this.shadowOffsetY=e,this}setShadowBlur(t){return void 0===t&&(t=0),this.shaodwBlur=t,this}setShadow(t,e,i,s){return this.setShadowColor(t).setShadowOffset(e,i).setShadowBlur(s),this}setBackgroundColor(t){return this.backgroundColor=Jt(t),this}get hasBackgroundColor(){return null!=this.backgroundColor}setBackgroundHeight(t){return this.backgroundHeight=t,this}setBackgroundBottomY(t){return this.backgroundBottomY=t,this}setOffsetX(t){return void 0===t&&(t=0),this.offsetX=t,this}setOffsetY(t){return void 0===t&&(t=0),this.offsetY=t,this}setOffset(t,e){return this.setOffsetX(t).setOffsetY(e),this}setLeftSpace(t){return void 0===t&&(t=0),this.leftSpace=t,this}setRightSpace(t){return void 0===t&&(t=0),this.rightSpace=t,this}setSpace(t,e){return this.setLeftSpace(t).setRightSpace(e),this}setAlign(t){return this.align=t,this}syncFont(t){return t.font=this.font,this}syncStyle(t){t.textBaseline="alphabetic";var e=this.hasFill,i=this.hasStroke;return t.fillStyle=e?this.color:"#000",t.strokeStyle=i?this.stroke:"#000",t.lineWidth=i?this.strokeThickness:0,t.lineCap="round",t.lineJoin="round",this}syncShadow(t){null!=t.shadowColor?(t.shadowColor=this.shadowColor,t.shadowOffsetX=this.shadowOffsetX,t.shadowOffsetY=this.shadowOffsetY,t.shadowBlur=this.shadowBlur):(t.shadowColor=0,t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowBlur=0)}getTextMetrics(t,e){return this.syncFont(t).syncStyle(t),t.measureText(e)}}const er=Phaser.Utils.Array.Remove,ir=Phaser.Utils.Array.Remove,sr="text",rr="image",nr="drawer",ar="space",or="command";var hr=function(t){return t.type===sr&&"\n"===t.text},lr=function(t){return t.type===sr&&"\f"===t.text},dr=function(t){return t.type===sr},cr=function(t){return t.type===or};class ur extends Ns{constructor(t,e,i){super(t,sr),this.updateTextFlag=!1,this.style=new tr(this,i),this.setText(e)}get autoRound(){return this.parent.autoRound}get offsetX(){return this.style.offsetX}set offsetX(t){this.style&&(this.style.offsetX=t)}get offsetY(){return this.style.offsetY}set offsetY(t){this.style&&(this.style.offsetY=t)}get leftSpace(){return this.style.leftSpace*this.scaleX}set leftSpace(t){this.style&&(this.style.leftSpace=t),super.leftSpace=t}get rightSpace(){return this.style.rightSpace*this.scaleX}set rightSpace(t){this.style&&(this.style.rightSpace=t),super.rightSpace=t}get align(){return this.style.align}set align(t){this.style&&(this.style.align=t)}modifyStyle(t){return this.setDirty(!0),this.style.modify(t),this.updateTextFlag&&this.updateTextSize(),this}modifyPorperties(t){return t?(this.modifyStyle(t),super.modifyPorperties(t),this):this}setText(t){return this.setDirty(this.text!=t),this.text=t,this.updateTextSize(),this}updateTextSize(){var t=this.text;if("\n"===t||"\f"===t||""===t)this.clearTextSize();else{var e,i,s=this.style.getTextMetrics(this.context,this.text);this.textWidth=s.width,"actualBoundingBoxAscent"in s?(e=s.actualBoundingBoxAscent,i=s.actualBoundingBoxDescent):(e=0,i=0),this.textHeight=e+i,this.ascent=e,this.descent=i}return this.updateTextFlag=!1,this}clearTextSize(){return this.textWidth=0,this.textHeight=0,this.ascent=0,this.descent=0,this}copyTextSize(t){return this.textWidth=t.textWidth,this.textHeight=t.textHeight,this.ascent=t.ascent,this.descent=t.descent,this}get width(){return this.textWidth*this.scaleX}set width(t){this.textWidth>0?this.scaleX=t/this.textWidth:this.scaleX=1}get height(){return this.textHeight*this.scaleY}set height(t){this.textHeight>0?this.scaleY=t/this.textHeight:this.scaleY=1}get willRender(){return 0!==this.textWidth&&super.willRender}renderContent(){var t=this.context,e=this.style;if(e.hasBackgroundColor){t.fillStyle=e.backgroundColor;var i=this.drawTLX,s=this.drawTRX-i+1,r=e.backgroundBottomY;null==r&&(r=this.drawBLY);var n=e.backgroundHeight;null==n&&(n=r-this.drawTLY);var a=r-n;t.fillRect(i,a,s,n)}var o=e.hasFill,h=e.hasStroke;(o||h)&&(e.syncFont(t).syncStyle(t),h&&(e.syncShadow(t),t.strokeText(this.text,0,0)),o&&(e.syncShadow(t),t.fillText(this.text,0,0)))}get drawTLX(){return-this.leftSpace}get drawTLY(){return-this.ascent}get drawBLX(){return-this.leftSpace}get drawBLY(){return this.descent}get drawTRX(){return this.textWidth+this.rightSpace}get drawTRY(){return-this.ascent}get drawBRX(){return this.textWidth+this.rightSpace}get drawBRY(){return this.descent}}var pr=function(t,e){var i=this.createCharChildren(t,e);return this.addChild(i),this};Phaser.Display.Canvas.CanvasPool;class gr extends Ns{constructor(t,e,i){super(t,rr),this.setTexture(e,i),this.color=void 0}get frameWidth(){return this.frameObj?this.frameObj.cutWidth:0}get frameHeight(){return this.frameObj?this.frameObj.cutHeight:0}get offsetY(){return-this.height}set offsetY(t){}get key(){return this._key}set key(t){this.setDirty(this._key!=t),this._key=t}get frame(){return this._frame}set frame(t){this.setDirty(this._frame!=t),this._frame=t}setTexture(t,e){return this.key=t,this.frame=e,this.frameObj=this.scene.sys.textures.getFrame(t,e),this}get width(){return this.frameWidth*this.scaleX}set width(t){this.setDirty(this.width!==t),this.scaleX=t/this.frameWidth}get height(){return this.frameHeight*this.scaleY}set height(t){this.setDirty(this.height!==t),this.scaleY=t/this.frameHeight}setHeight(t,e){return void 0===e&&(e=!1),this.height=t,e&&(this.scaleX=this.scaleY),this}setColor(t){return this.color=t,this}modifyPorperties(t){return t.hasOwnProperty("color")&&this.setColor(t.color),super.modifyPorperties(t),this}renderContent(){Pi(this.frameObj,this.canvas,0,0,this.frameWidth,this.frameHeight,this.color,!1)}get drawTLX(){return-this.leftSpace}get drawTLY(){return 0}get drawBLX(){return-this.leftSpace}get drawBLY(){return this.frameHeight}get drawTRX(){return this.frameWidth+this.rightSpace}get drawTRY(){return 0}get drawBRX(){return this.frameWidth+this.rightSpace}get drawBRY(){return this.frameHeight}}var vr=function(t,e,i){var s=this.createImageChild(t,e,i);return this.addChild(s),this};class fr extends Ns{constructor(t,e,i,s){super(t,nr),this.setRenderCallback(e),this.setDrawerSize(i,s)}setRenderCallback(t){return t?this.renderContent=t.bind(this):delete this.renderContent,this}setDrawerSize(t,e){return!0===t?(this.toLocalPosition=!1,t=void 0,e=void 0):this.toLocalPosition=!0,void 0===t&&(t=0),void 0===e&&(e=t),this.drawerWidth=t,this.drawerHeight=e,this}onFree(){super.onFree(),this.setRenderCallback()}get width(){return this.drawerWidth*this.scaleX}set width(t){this.setDirty(this.width!==t),this.scaleX=this.drawerWidth>0?t/this.drawerWidth:1}get height(){return this.drawerHeight*this.scaleY}set height(t){this.setDirty(this.height!==t),this.scaleY=this.drawerHeight>0?t/this.drawerHeight:1}get offsetY(){return-this.height}set offsetY(t){}get drawTLX(){return-this.leftSpace}get drawTLY(){return 0}get drawBLX(){return-this.leftSpace}get drawBLY(){return this.drawerHeight}get drawTRX(){return this.drawerWidth+this.rightSpace}get drawTRY(){return 0}get drawBRX(){return this.drawerWidth+this.rightSpace}get drawBRY(){return this.drawerHeight}}let mr=class extends Ns{constructor(t,e){super(t,ar),this.setSpaceWidth(e)}get width(){return this.spaceWidth*this.scaleX}set width(t){this.spaceWidth>0?this.scaleX=t/this.spaceWidth:this.scaleX=1}setSpaceWidth(t){return this.spaceWidth=t,this}};var yr=function(t){var e=this.createSpaceChild(t);return this.addChild(e),this};class br extends Os{constructor(t,e,i,s,r){super(t,or),this.setName(e).setParameter(s).setCallback(i,r)}setName(t){return this.name=t,this}setParameter(t){return this.param=t,this}setCallback(t,e){return this.callback=t,this.scope=e,this}exec(){return this.scope?this.callback.call(this.scope,this.param,this.name):this.callback(this.param,this.name)}onFree(){super.onFree(),this.setName().setCallback().setParameter()}}var xr=function(t,e,i,s){var r=this.createCommandChild(t,e,i,s);return this.addChild(r),this},Cr=function(t){var e={callback:void 0,start:0,isLastPage:!1,maxLines:void 0,padding:void 0,letterSpacing:void 0,hAlign:void 0,vAlign:void 0,children:[],lines:[],maxLineWidth:0,linesHeight:0,lineHeight:void 0,maxLineHeight:0,linesWidth:0,lineWidth:void 0};return Object.assign(e,t)};const kr={none:0,word:1,char:2,character:2,mix:3};var wr=function(t,e,i,s){void 0===s&&(s={word:[],width:0}),s.word.length=0;for(var r=2===i,n=3===i,a=!r&&!n,o=t.length,h=e,l=s.word,d=0,c=!1;h0&&!o){var h=this.fixedHeight-s;i>0?n=h/i:(n=(l=Or.call(this)).height,a=l.ascent,i=Math.floor((h-a)/n))}else{var l;n=(l=Or.call(this)).height,a=l.ascent}}else this.fixedHeight>0?void 0===(i=Er(t,"maxLines"))&&(h=this.fixedHeight-s,i=Math.floor(h/n)):i=Er(t,"maxLines",0);void 0===a&&(a=n);var d=0===i,c=Er(t,"wrapMode");void 0===c&&(c=Er(t,"charWrap",!1)?"char":"word"),"string"==typeof c&&(c=kr[c]);var u=Er(t,"wrapWidth",void 0);void 0===u&&(this.fixedWidth>0?u=this.fixedWidth-r:(u=1/0,c=0));for(var p=Er(t,"letterSpacing",0),g=Er(t,"hAlign",0),v=Er(t,"vAlign",0),f=Er(t,"justifyPercentage",.25),m=Cr({callback:"runWordWrap",start:e,padding:this.wrapPadding,letterSpacing:p,maxLines:i,hAlign:g,vAlign:v,justifyPercentage:f,ascent:a,lineHeight:n,wrapWidth:u,wrapMode:c}),y=this.children,b=0,x=y.length;b0&&(E.push({children:_,width:R}),L=Math.max(L,R)),m.start+=M.length,m.isLastPage=!B&&m.start===O,m.maxLineWidth=L,m.linesHeight=E.length*n;var Y=this.fixedWidth>0?this.fixedWidth:m.maxLineWidth+r,X=this.fixedHeight>0?this.fixedHeight:m.linesHeight+s;for(function(t,e,i){for(var s,r,n=t.hAlign,a=t.vAlign,o=t.justifyPercentage,h=t.lines,l=0,d=h.length;l0?(a=this.fixedWidth-r)/i:0;else if(this.fixedWidth>0){if(void 0===(i=Lr(t,"maxLines",void 0))){var a=this.fixedWidth-r;i=Math.floor(a/n)+1}}else i=Lr(t,"maxLines",0);var o=0===i,h=Lr(t,"fixedCharacterHeight",void 0);if(void 0===h){var l=Lr(t,"charPerLine",void 0);if(void 0!==l){var d=this.fixedHeight-s;h=Math.floor(d/l)}}var c=Lr(t,"wrapHeight",void 0);void 0===c&&(c=this.fixedHeight>0?this.fixedHeight-s:1/0);for(var u=Lr(t,"letterSpacing",0),p=Lr(t,"rtl",!0),g=Lr(t,"hAlign",p?2:0),v=Lr(t,"vAlign",0),f=Cr({callback:"runVerticalWrap",start:e,padding:this.wrapPadding,letterSpacing:u,maxLines:i,hAlign:g,vAlign:v,lineWidth:n,fixedCharacterHeight:h,wrapHeight:c,rtl:p}),m=this.children,y=0,b=m.length;y0&&(M.push({children:E,height:_}),R=Math.max(R,_)),f.start+=O.length,f.isLastPage=f.start===T,f.maxLineHeight=R,f.linesWidth=M.length*n;var A=this.fixedWidth>0?this.fixedWidth:f.linesWidth+r,z=this.fixedHeight>0?this.fixedHeight:f.maxLineHeight+s;for(function(t,e,i){var s,r,n=t.hAlign,a=t.vAlign,o=t.rtl,h=t.lines,l=t.lineWidth,d=t.linesWidth;switch(n){case 1:case"center":s=(e-d)/2;break;case 2:case"right":s=e-d;break;default:s=0}o&&(s+=l);for(var c=0,u=h.length;c0?t:this.width,e>0?e:this.height)),this},setPadding:function(t,e){var i=this.padding,s=i.left,r=i.right,n=i.top,a=i.bottom;return Ts(i,t,e),this.dirty=this.dirty||s!=i.left||r!=i.right||n!=i.top||a!=i.bottom,this},getPadding:function(t){return Ps(this.padding,t)},modifyTextStyle:function(t){return this.textStyle.modify(t),this},modifyDefaultTextStyle:function(t){return this.defaultTextStyle.modify(t),this},resetTextStyle:function(){return this.textStyle.copyFrom(this.defaultTextStyle),this},setTestString:function(t){return this.testString=t,this},removeChild:function(t){return this.poolManager.free(t),er(this.children,t),this.lastAppendedChildren.length=0,this.lastOverChild=null,this.dirty=!0,this},removeChildren:function(){return this.poolManager.freeMultiple(this.children),this.children.length=0,this.lastAppendedChildren.length=0,this.lastOverChild=null,this.dirty=!0,this},popChild:function(t){return ir(this.children,t),this.lastAppendedChildren.length=0,this.lastOverChild=null,this.dirty=!0,this},clearContent:function(){return this.setText(),this},addChild:function(t,e){var i=Array.isArray(t);return void 0===e||e===this.children.length?i?this.children.push(...t):this.children.push(t):i?this.children.splice(e,0,...t):this.children.splice(e,0,t),this.lastAppendedChildren.length=0,i?this.lastAppendedChildren.push(...t):this.lastAppendedChildren.push(t),this},createCharChild:function(t,e){e&&this.textStyle.modify(e);var i=this.poolManager.allocate(sr);return null===i?i=new ur(this,t,this.textStyle):i.setParent(this).setActive().modifyStyle(this.textStyle).setText(t),i},createCharChildren:function(t,e){e&&this.textStyle.modify(e);for(var i=[],s=0,r=t.length;se&&(s=e,r=t)})),r},getCharWorldPosition:function(t,e,i,s){return"number"==typeof t&&(t=this.getCharChild(t,!0)),Ws(this,t,e,i,s)},setToMinSize:function(){for(var t=this.children,e=0,i=0,s=0,r=t.length;s=i.length&&(t=i.length);for(var s=0,r=0;r>16&255},yn=function(t){return t>>8&255},bn=function(t){return 255&t};const xn=Phaser.Events.EventEmitter;var Cn=function(t,e,i,s,r,n){return void 0===n?n={}:!0===n&&(n=kn),"number"!=typeof i&&(i=0,s=0),n.x=r.x+r.width*t+i,n.y=r.y+r.height*e+s,n},kn={},wn=function(t,e,i,s,r,n,a){if(t.hasOwnProperty("vp"))return t;"function"==typeof i&&(a=i,i=void 0),"function"==typeof r&&(a=r,r=void 0),void 0===i&&(i=.5),void 0===s&&(s=.5),void 0===r&&(r=0),void 0===n&&(n=0),void 0===a&&(a=Cn),function(t){if(t.events)return t;var e=new xn,i=t.x;Object.defineProperty(t,"x",{get:function(){return i},set:function(s){i!==s&&(i=s,e.emit("update",t))}});var s=t.y;Object.defineProperty(t,"y",{get:function(){return s},set:function(i){s!==i&&(s=i,e.emit("update",t))}});var r=t.width;Object.defineProperty(t,"width",{get:function(){return r},set:function(i){r!==i&&(r=i,e.emit("update",t))}});var n=t.height;Object.defineProperty(t,"height",{get:function(){return n},set:function(i){n!==i&&(n=i,e.emit("update",t))}}),t.events=e}(e);var o=e.events;t.vp=e;var h=function(){a(i,s,r,n,e,t)};o.on("update",h),t.once("destroy",(function(){o.off("update",h),t.vp=void 0})),Object.defineProperty(t,"vpx",{get:function(){return i},set:function(t){i!==t&&(i=t,h())}}),Object.defineProperty(t,"vpy",{get:function(){return s},set:function(t){s!==t&&(s=t,h())}}),Object.defineProperty(t,"vpxOffset",{get:function(){return r},set:function(t){r!==t&&(r=t,h())}}),Object.defineProperty(t,"vpyOffset",{get:function(){return n},set:function(t){n!==t&&(n=t,h())}}),h()},Sn=function(t){return t.preFX?t.preFX:t.postFX?t.postFX:null},Pn=function(t,e){t._effectSwitchNames||(t._effectSwitchNames=[],t.clearAllEffects=function(){for(var e=t._effectSwitchNames,i=0,s=e.length;i0&&void 0!==t.setTint},useAlphaFadeEffect(t){return(void 0===this.fadeMode||1===this.fadeMode)&&this.fadeTime>0&&void 0!==t.setAlpha},useRevealEffect(t){return this.fadeMode>=2&&this.fadeMode<=5&&this.fadeTime>0&&(t.preFX||t.postFX)},fadeBob(t,e,i,s){var r=t.gameObject;if(this.useTintFadeEffect(r))void 0!==e&&t.setProperty("tintGray",255*e),t.easeProperty({property:"tintGray",value:Math.floor(255*i),duration:this.fadeTime,delay:0,ease:"Linear",repeat:0,yoyo:!1,from:!1,complete:s});else if(this.useAlphaFadeEffect(r))void 0!==e&&t.setProperty("alpha",e),t.easeProperty({property:"alpha",value:i,duration:this.fadeTime,delay:0,ease:"Linear",repeat:0,yoyo:!1,from:!1,complete:s});else if(this.useRevealEffect(r)){var n;switch(Mn(r,"reveal"),this.fadeMode){case 2:n="revealUp";break;case 3:n="revealDown";break;case 4:n="revealLeft";break;case 5:n="revealRight"}void 0===e&&(e=0),r[n]=e,t.easeProperty({property:n,value:i,duration:this.fadeTime,delay:0,ease:"Linear",repeat:0,yoyo:!1,from:!1,complete:s}),t.getTweenTask(n).once("complete",(function(){r[n]=null}))}else s&&s(r);return this}},An=function(t){return void 0!==t.displayWidth?t.displayWidth:t.width},zn=function(t){return void 0!==t.displayHeight?t.displayHeight:t.height};const Fn=Phaser.Geom.Rectangle,Yn=Phaser.Math.Vector2,Xn=Phaser.Math.RotateAround;var Wn=function(t,e){if(void 0===e?e=new Fn:!0===e&&(void 0===Vn&&(Vn=new Fn),e=Vn),t.getBounds)return t.getBounds(e);var i,s,r,n,a,o,h,l;if(t.parentContainer){var d=t.parentContainer.getBoundsTransformMatrix();Gn(t,e),d.transformPoint(e.x,e.y,e),i=e.x,s=e.y,Hn(t,e),d.transformPoint(e.x,e.y,e),r=e.x,n=e.y,Un(t,e),d.transformPoint(e.x,e.y,e),a=e.x,o=e.y,Nn(t,e),d.transformPoint(e.x,e.y,e),h=e.x,l=e.y}else Gn(t,e),i=e.x,s=e.y,Hn(t,e),r=e.x,n=e.y,Un(t,e),a=e.x,o=e.y,Nn(t,e),h=e.x,l=e.y;return e.x=Math.min(i,r,a,h),e.y=Math.min(s,n,o,l),e.width=Math.max(i,r,a,h)-e.x,e.height=Math.max(s,n,o,l)-e.y,e},Vn=void 0,Gn=function(t,e,i){return void 0===e?e=new Yn:!0===e&&(void 0===Kn&&(Kn=new Yn),e=Kn),t.getTopLeft?t.getTopLeft(e):(e.x=t.x-An(t)*t.originX,e.y=t.y-zn(t)*t.originY,Jn(t,e,i))},Hn=function(t,e,i){return void 0===e?e=new Yn:!0===e&&(void 0===Kn&&(Kn=new Yn),e=Kn),t.getTopRight?t.getTopRight(e):(e.x=t.x-An(t)*t.originX+An(t),e.y=t.y-zn(t)*t.originY,Jn(t,e,i))},Un=function(t,e,i){return void 0===e?e=new Yn:!0===e&&(void 0===Kn&&(Kn=new Yn),e=Kn),t.getBottomLeft?t.getBottomLeft(e):(e.x=t.x-An(t)*t.originX,e.y=t.y-zn(t)*t.originY+zn(t),Jn(t,e,i))},Nn=function(t,e,i){return void 0===e?e=new Yn:!0===e&&(void 0===Kn&&(Kn=new Yn),e=Kn),t.getBottomRight?t.getBottomRight(e):(e.x=t.x-An(t)*t.originX+An(t),e.y=t.y-zn(t)*t.originY+zn(t),Jn(t,e,i))},$n=function(t,e,i){void 0===e?e=new Yn:!0===e&&(void 0===Kn&&(Kn=new Yn),e=Kn);var s=An(t),r=zn(t);return e.x=t.x+s*(.5-t.originX),e.y=t.y+r*(.5-t.originY),Jn(t,e,i)},Kn=void 0,Jn=function(t,e,i){return void 0===i&&(i=!1),0!==t.rotation&&Xn(e,t.x,t.y,t.rotation),i&&t.parentContainer&&t.parentContainer.getBoundsTransformMatrix().transformPoint(e.x,e.y,e),e};const qn=Phaser.Utils.Objects.GetValue;var Zn=function(t,e,i){var s,r,n,a,o;if("number"==typeof i?s=i:(s=qn(i,"color"),r=qn(i,"lineWidth"),n=qn(i,"fillColor"),a=qn(i,"fillAlpha",1),o=qn(i,"padding",0)),Array.isArray(t))for(var h=0,l=t.length;h0?-this.delay:0,this.state=this.nowTime>=0?Va:Wa,this.repeatCounter=0,this}stop(){return this.state=Xa,this}update(t,e){this.state!==Xa&&this.state!==Ha&&0!==e&&0!==this.timeScale&&(this.nowTime+=e*this.timeScale,this.justRestart=!1,this.nowTime>=this.duration?-1===this.repeat||this.repeatCounter0&&(this.nowTime-=this.repeatDelay,this.state=Ga)):(this.nowTime=this.duration,this.state=Ha):this.nowTime>=0&&(this.state=Va))}get t(){var t;switch(this.state){case Xa:case Wa:case Ga:t=0;break;case Va:t=this.nowTime/this.duration;break;case Ha:t=1}return Fa(t,0,1)}set t(t){(t=Fa(t,-1,1))<0?(this.state=Wa,this.nowTime=-this.delay*t):(this.state=Va,this.nowTime=this.duration*t,1===t&&0!==this.repeat&&this.repeatCounter++)}setT(t){return this.t=t,this}get isIdle(){return this.state===Xa}get isDelay(){return this.state===Wa}get isCountDown(){return this.state===Va}get isRunning(){return this.state===Wa||this.state===Va}get isDone(){return this.state===Ha}get isOddIteration(){return!(1&~this.repeatCounter)}get isEvenIteration(){return!(1&this.repeatCounter)}};const Xa=0,Wa=1,Va=2,Ga=3,Ha=-1;class Ua extends ja{constructor(t,e){super(t,e),this.timer=new Ya}shutdown(t){this.isShutdown||(super.shutdown(t),this.timer.destroy(),this.timer=void 0)}start(){return this.timer.start(),super.start(),this}stop(){return this.timer.stop(),super.stop(),this}complete(){return this.timer.stop(),super.complete(),this}}const Na=Phaser.Utils.Objects.GetValue,$a=Phaser.Utils.Objects.GetAdvancedValue,Ka=Phaser.Tweens.Builders.GetEaseFunction;class Ja extends Ua{resetFromJSON(t){return this.timer.resetFromJSON(Na(t,"timer")),this.setEnable(Na(t,"enable",!0)),this.setTarget(Na(t,"target",this.parent)),this.setDelay($a(t,"delay",0)),this.setDuration($a(t,"duration",1e3)),this.setEase(Na(t,"ease","Linear")),this.setRepeat(Na(t,"repeat",0)),this}setEnable(t){return null==t&&(t=!0),this.enable=t,this}setTarget(t){return void 0===t&&(t=this.parent),this.target=t,this}setDelay(t){return this.delay=t,this}setDuration(t){return this.duration=t,this}setRepeat(t){return this.repeat=t,this}setRepeatDelay(t){return this.repeatDelay=t,this}setEase(t){return void 0===t&&(t="Linear"),this.ease=t,this.easeFn=Ka(t),this}start(){return this.timer.isRunning||super.start(),this}restart(){return this.timer.stop(),this.start.apply(this,arguments),this}stop(t){return void 0===t&&(t=!1),super.stop(),t&&(this.timer.setT(1),this.updateTarget(this.target,this.timer),this.complete()),this}update(t,e){if(!this.isRunning||!this.enable||this.parent.hasOwnProperty("active")&&!this.parent.active)return this;var i=this.target,s=this.timer;return s.update(t,e),s.isDelay||this.updateTarget(i,s),this.emit("update",i,this),s.isDone&&this.complete(),this}updateTarget(t,e){}}const qa=Phaser.Sound.BaseSound;var Za=function(t){return t instanceof qa};const Qa=Phaser.Utils.Objects.GetValue,to=Phaser.Utils.Objects.GetAdvancedValue,eo=Phaser.Math.Linear;let io=class extends Ja{constructor(t,e,i){Za(t)&&(i=e,e=t,t=void 0),e.active=!0,e.scene=t,e.game=e.manager.game,super(e,i),this.volume={},this.resetFromJSON(i)}resetFromJSON(t){return super.resetFromJSON(t),this.setMode(Qa(t,"mode",0)),this.setEnable(Qa(t,"enable",!0)),this.setVolumeRange(to(t,"volume.start",this.parent.volume),to(t,"volume.end",0)),this}setMode(t){return"string"==typeof t&&(t=so[t]),this.mode=t,this}setVolumeRange(t,e){return this.volume.start=t,this.volume.end=e,this}start(){return this.timer.isRunning||(this.parent.setVolume(this.volume.start),this.timer.setDelay(this.delay).setDuration(this.duration),super.start()),this}updateTarget(t,e){t.volume=eo(this.volume.start,this.volume.end,e.t)}complete(){switch(super.complete(),this.mode){case 1:this.parent.stop();break;case 2:this.parent.stop(),this.parent.destroy()}return this}};const so={stop:1,destroy:2};var ro=function(t,e,i,s,r){Za(t)&&(r=s,s=i,i=e,e=t,t=void 0),void 0===s&&(s=1),void 0===r&&(r=0);var n,a={mode:0,volume:{start:r,end:s},duration:i};return"string"==typeof e&&(e=t.sys.sound.add(e)),e.hasOwnProperty("_fade")?(n=e._fade).stop().resetFromJSON(a):(n=new io(t,e,a),e._fade=n),n.start(),e.isPlaying||e.setVolume(r).play(),e},no=function(t,e,i,s){Za(t)&&(s=i,i=e,e=t,t=void 0),void 0===s&&(s=!0);var r,n={mode:s?2:1,volume:{start:e.volume,end:0},duration:i};return e.hasOwnProperty("_fade")?(r=e._fade).stop().resetFromJSON(n):(r=new io(t,e,n),e._fade=r),r.start(),e.isPlaying||e.play(),e};const ao=Phaser.Utils.Objects.GetValue;var oo={setBackgroundMusicLoop(t){return void 0===t&&(t=!0),this.backgroundMusicLoop=t,this},setBackgroundMusicFadeTime(t){return this.backgroundMusicFadeTime=t,this},getBackgroundMusic(){return this.backgroundMusic},setCurrentBackgroundMusic(t){return this.backgroundMusic=t,t&&(t.once("complete",(function(){this.backgroundMusic===t&&(this.backgroundMusic.destroy(),this.backgroundMusic=void 0)}),this).once("destroy",(function(){this.backgroundMusic===t&&(this.backgroundMusic=void 0)}),this),t.isPlaying||t.play()),this},playBackgroundMusic(t,e){if(!this.hasAudio(t))return console.error(`[Sound manager] Audio key'${t}' is not existed`),this;if(this.backgroundMusic&&this.backgroundMusic.key===t)return this;this.stopBackgroundMusic();var i=this.sound.add(t,{loop:ao(e,"loop",this.backgroundMusicLoop),mute:ao(e,"mute",this.backgroundMusicMute),volume:ao(e,"volume",this.backgroundMusicVolume),detune:ao(e,"detune",0),rate:ao(e,"rate",1)});return this.setCurrentBackgroundMusic(i),this.backgroundMusicFadeTime>0&&this.fadeInBackgroundMusic(this.backgroundMusicFadeTime),this},pauseBackgroundMusic(){return this.backgroundMusic&&this.backgroundMusic.pause(),this},resumeBackgroundMusic(){return this.backgroundMusic&&this.backgroundMusic.resume(),this},stopBackgroundMusic(){return this.backgroundMusic&&(this.backgroundMusicFadeTime>0?this.fadeOutBackgroundMusic(this.backgroundMusicFadeTime,!0):(this.backgroundMusic.stop(),this.backgroundMusic.destroy(),this.backgroundMusic=void 0)),this},fadeInBackgroundMusic(t){return this.backgroundMusic&&ro(this.backgroundMusic,t,this.backgroundMusicVolume,0),this},fadeOutBackgroundMusic(t,e){return this.backgroundMusic&&no(this.backgroundMusic,t,e),this},crossFadeBackgroundMusic(t,e){if(!this.hasAudio(t))return console.error(`[Sound manager] Audio key'${t}' is not existed`),this;var i=this.backgroundMusicFadeTime;return this.backgroundMusicFadeTime=0,this.fadeOutBackgroundMusic(e,!0).playBackgroundMusic(t).fadeInBackgroundMusic(e),this.backgroundMusicFadeTime=i,this},setBackgroundMusicMute(t){return void 0===t&&(t=!0),this.backgroundMusicMute=t,this},setBackgroundMusicVolume(t){return this.backgroundMusicVolume=t,this},setBackgroundMusicRate(t){return this.backgroundMusic&&this.backgroundMusic.setRate(t),this},setBackgroundMusicDetune(t){return this.backgroundMusic&&this.backgroundMusic.setDetune(t),this}};const ho=Phaser.Utils.Objects.GetValue;var lo={setBackgroundMusic2Loop(t){return void 0===t&&(t=!0),this.backgroundMusic2Loop=t,this},setBackgroundMusic2FadeTime(t){return this.backgroundMusic2FadeTime=t,this},getBackgroundMusic2(){return this.backgroundMusic2},setCurrentBackgroundMusic2(t){return this.backgroundMusic2=t,t&&(t.once("complete",(function(){this.backgroundMusic2===t&&(this.backgroundMusic2.destroy(),this.backgroundMusic2=void 0)}),this).once("destroy",(function(){this.backgroundMusic2===t&&(this.backgroundMusic2=void 0)}),this),t.isPlaying||t.play()),this},playBackgroundMusic2(t,e){if(!this.hasAudio(t))return console.error(`[Sound manager] Audio key'${t}' is not existed`),this;if(this.backgroundMusic2&&this.backgroundMusic2.key===t)return this;this.stopBackgroundMusic2();var i=this.sound.add(t,{loop:ho(e,"loop",this.backgroundMusicLoop),mute:ho(e,"mute",this.backgroundMusic2Mute),volume:ho(e,"volume",this.backgroundMusic2Volume),detune:ho(e,"detune",0),rate:ho(e,"rate",1)});return this.setCurrentBackgroundMusic2(i),this.backgroundMusic2FadeTime>0&&this.fadeInBackgroundMusic2(this.backgroundMusic2FadeTime),this},pauseBackgroundMusic2(){return this.backgroundMusic2&&this.backgroundMusic2.pause(),this},resumeBackgroundMusic2(){return this.backgroundMusic2&&this.backgroundMusic2.resume(),this},stopBackgroundMusic2(){return this.backgroundMusic2&&(this.backgroundMusic2FadeTime>0?this.fadeOutBackgroundMusic2(this.backgroundMusic2FadeTime,!0):(this.backgroundMusic2.stop(),this.backgroundMusic2.destroy(),this.backgroundMusic2=void 0)),this},fadeInBackgroundMusic2(t){return this.backgroundMusic2&&ro(this.backgroundMusic2,t,this.backgroundMusic2Volume,0),this},fadeOutBackgroundMusic2(t,e){return this.backgroundMusic2&&no(this.backgroundMusic2,t,e),this},crossFadeBackgroundMusic2(t,e){if(!this.hasAudio(t))return console.error(`[Sound manager] Audio key'${t}' is not existed`),this;var i=this.backgroundMusic2FadeTime;return this.backgroundMusic2FadeTime=0,this.fadeOutBackgroundMusic2(e,!0).playBackgroundMusic2(t).fadeInBackgroundMusic2(e),this.backgroundMusic2FadeTime=i,this},setBackgroundMusic2Mute(t){return void 0===t&&(t=!0),this.backgroundMusic2Mute=t,this},setBackgroundMusic2Volume(t){return this.backgroundMusic2Volume=t,this},setBackgroundMusic2Rate(t){return this.backgroundMusic2&&this.backgroundMusic2.setRate(t),this},setBackgroundMusic2Detune(t){return this.backgroundMusic2&&this.backgroundMusic2.setDetune(t),this}};const co=Phaser.Utils.Array.Remove,uo=Phaser.Utils.Objects.GetValue;var po={getSoundEffects(){return this.soundEffects},getLastSoundEffect(){return this.soundEffects[this.soundEffects.length-1]},playSoundEffect(t,e){if(!this.hasAudio(t))return console.error(`[Sound manager] Audio key'${t}' is not existed`),this;var i=this.sound.add(t,{mute:uo(e,"mute",this.soundEffectsMute),volume:uo(e,"volume",this.soundEffectsVolume),detune:uo(e,"detune",0),rate:uo(e,"rate",1)});return this.soundEffects.push(i),i.once("complete",(function(){i.destroy(),this.sound&&co(this.soundEffects,i)}),this).once("destroy",(function(){this.sound&&co(this.soundEffects,i)}),this).play(),this},stopAllSoundEffects(){for(var t=this.soundEffects.length-1;t>=0;t--){var e=this.soundEffects[t];e.stop(),e.destroy()}return this},fadeInSoundEffect(t){var e=this.getLastSoundEffect();return e&&ro(e,t,this.soundEffectsVolume,0),this},fadeOutSoundEffect(t,e){var i=this.getLastSoundEffect();return i&&no(i,t,e),this},fadeOutAllSoundEffects(t,e){for(var i=this.soundEffects.length-1;i>=0;i--)no(this.soundEffects[i],t,e);return this},setSoundEffectMute(t,e){if(void 0===t&&(t=!0),void 0===e&&(e=!1),e){var i=this.getLastSoundEffect();i&&i.setMute(t)}else this.soundEffectsMute=t;return this},setSoundEffectVolume(t,e){if(void 0===e&&(e=!1),e){var i=this.getLastSoundEffect();i&&i.setVolume(t)}else this.soundEffectsVolume=t;return this},setSoundEffectDetune(t,e){var i;void 0===e&&(e=!1);for(var s=0,r=(i=e?[this.getLastSoundEffect()]:this.soundEffects).length;s=0;t--){var e=this.soundEffects[t];e.stop(),e.destroy()}return this},fadeInSoundEffect2(t){var e=this.getLastSoundEffect2();return e&&ro(e,t,this.soundEffects2Volume,0),this},fadeOutSoundEffect2(t,e){var i=this.getLastSoundEffect2();return i&&no(i,t,e),this},fadeOutAllSoundEffects2(t,e){for(var i=this.soundEffects2.length-1;i>=0;i--)no(this.soundEffects2[i],t,e);return this},setSoundEffect2Mute(t,e){if(void 0===t&&(t=!0),void 0===e&&(e=!1),e){var i=this.getLastSoundEffect2();i&&i.setMute(t)}else this.soundEffects2Mute=t;return this},setSoundEffect2Volume(t,e){if(void 0===e&&(e=!1),e){var i=this.getLastSoundEffect2();i&&i.setVolume(t)}else this.soundEffects2Volume=t;return this},setSoundEffect2Detune(t,e){var i;void 0===e&&(e=!1);for(var s=0,r=(i=e?[this.getLastSoundEffect2()]:this.soundEffects2).length;s=0;t--)this.soundEffects[t].destroy();if(this.soundEffects.length=0,this.soundEffects2.length)for(t=this.soundEffects2.length-1;t>=0;t--)this.soundEffects2[t].destroy();return this.soundEffects2.length=0,this.sound=void 0,this}get backgroundMusicMute(){return this._backgroundMusicMute}set backgroundMusicMute(t){this._backgroundMusicMute=t,this.backgroundMusic&&this.backgroundMusic.setMute(mute)}get backgroundMusicVolume(){return this._backgroundMusicVolume}set backgroundMusicVolume(t){this._backgroundMusicVolume=t,this.backgroundMusic&&this.backgroundMusic.setVolume(t)}get backgroundMusic2Mute(){return this._backgroundMusic2Mute}set backgroundMusic2Mute(t){this._backgroundMusic2Mute=t,this.backgroundMusic2&&this.backgroundMusic2.setMute(mute)}get backgroundMusic2Volume(){return this._backgroundMusic2Volume}set backgroundMusic2Volume(t){this._backgroundMusic2Volume=t,this.backgroundMusic2&&this.backgroundMusic2.setVolume(t)}get soundEffectsMute(){return this._soundEffectsMute}set soundEffectsMute(t){this._soundEffectsMute=t;for(var e=this.soundEffects,i=0,s=e.length;i");this.setDelimiters(e[0],e[1]),this.setTranslateTagNameCallback(J(t,"translateTagNameCallback")),this.isRunning=!1,this.isPaused=!1,this.skipEventFlag=!1,this.justCompleted=!1,this.lastTagStart=null,this.lastTagEnd=null,this.lastContent=null}shutdown(){this.destroyEventEmitter()}destroy(){this.shutdown()}setMultipleLinesTagEnable(t){return void 0===t&&(t=!0),this.multipleLinesTagEnable=t,this}setDelimiters(t,e){void 0===e&&(e=t[1],t=t[0]),this.delimiterLeft=t,this.delimiterRight=e,t=qi(this.delimiterLeft),e=qi(this.delimiterRight);var i=this.multipleLinesTagEnable?"gs":"gi";return this.reSplit=RegExp(`${t}(.+?)${e}`,i),this}setTranslateTagNameCallback(t){return this.translateTagNameCallback=t,this}setValueConverter(t){return!0===t?t=qo:t||(t=Qo),this.valueConverter=t,this}setLoopEnable(t){return void 0===t&&(t=!0),this.loopEnable=t,this}setSource(t){return this.source=t,this}resetIndex(t){return void 0===t&&(t=0),this.progressIndex=t,this.reSplit.lastIndex=t,this.lastTagStart=null,this.lastTagEnd=null,this.lastContent=null,this.justCompleted=!1,this.isRunning=!1,this}start(t){return this.setSource(t).restart(),this}restart(){this.resetIndex().next()}next(){if(this.isPaused&&this.onResume(),this.isRunning)return this;if(this.isRunning=!0,this.justCompleted)return this.isRunning=!1,this;0===this.reSplit.lastIndex&&this.onStart();var t=this.source,e=t.length;for(this.reSplit.lastIndex=this.progressIndex;;){var i=this.reSplit.exec(t);if(!i){if(this.progressIndex");this.setDelimiters(e[0],e[1])}setTagExpression(t){return t||(t=eh),this.tagExpression=t,this}setValueExpression(t){return t||(t=eh),this.valueExpression=t,this}setDelimiters(t,e){super.setDelimiters(t,e);var i=`(${this.tagExpression})(=(${this.valueExpression}))?`;if(this.reTag=RegExp(i,"i"),this.tagExpression!==eh||this.valueExpression!==eh){var s=`${this.tagExpression}(=${this.valueExpression})?`,r=`/${this.tagExpression}`;t=qi(this.delimiterLeft),e=qi(this.delimiterRight);var n=this.multipleLinesTagEnable?"gs":"gi";this.reSplit=RegExp(`${t}((${s})|(${r}))${e}`,n)}return this}onTag(t){var e=t.match(this.reTag),i=e[1],s="/"===i.charAt(0);if(s&&(i=i.substring(1,i.length)),this.translateTagNameCallback&&(i=this.translateTagNameCallback(i)),this.skipEventFlag=!1,s)this.emit(`-${i}`),this.skipEventFlag||this.emit("-",i),this.lastTagEnd=i;else{var r=function(t,e,i){if(null==t)return[];void 0===e&&(e=qo),void 0===i&&(i=",");for(var s=t.split(i),r=0,n=s.length;r0){var n=this.timeline.addTimer({name:al,target:s,duration:r.duration,yoyo:r.yoyo,onStart:r.onStart,onProgress:r.onProgress,onComplete:r.onComplete});this.skipTypingAnimation&&n.seek(1)}else r.onStart&&r.onStart(s,0);this.minSizeEnable&&this.textPlayer.setToMinSize(),this.textPlayer.emit("typing",s);var a=this.nextChild;if(a)if(this.skipSpaceEnable&&(e=a).type===sr&&" "===e.text);else if(i+=this.speed+t,t=0,i>0){this.typingTimer=this.timeline.addTimer({name:"delay",target:this,duration:i,onComplete:function(t,e,i){t.typingTimer=void 0,ol.call(t,i.remainder)}});break}}else cr(s)&&s.exec()}this.minSizeEnable&&this.textPlayer.setToMinSize(),this.inTypingProcessLoop=!1},hl=function(t){switch(t){case"camera.fadein":case"camera.fadeout":case"camera.flash":case"camera.shake":case"camera.zoom":case"camera.rotate":case"camera.scroll":return!0;default:return!1}},ll=function(t,e){var i=e.split(".");return t.gameObjectManagers.hasOwnProperty(i[0])},dl=function(t,e,i,s){var r=t.waitEventManager,n=e.split("."),a=n[0],o=t.getGameObjectManager(a),h=`wait.${a}`;switch(n.length){case 1:return r.waitGameObjectManagerEmpty(a),void t.emit(h);case 2:var l=n[1];return r.waitGameObjectDestroy(a,l),void t.emit(h,l);case 3:l=n[1];var d=n[2];if("number"==typeof o.getProperty(l,d))return r.waitGameObjectTweenComplete(a,l,d),void t.emit(h,l,d);var c=d,u=c.startsWith("!");return u&&(c=c.substring(1)),o.hasData(l,c)?(r.waitGameObjectDataFlag(a,l,c,!u),void t.emit(h,l,c)):void r.waitTime(0)}};const cl=Phaser.Input.Keyboard.KeyCodes;var ul=function(t,e,i,s){var r=t.waitEventManager;r.clearWaitCompleteCallbacks().addWaitCompleteCallback(i,s);for(var n=0,a=(e="string"==typeof e&&e.length>1&&-1!==e.indexOf("|")?e.split("|"):[e]).length;n0&&n.chainAnimation(i,s)},Ol=function(t){var e,i;[e,...i]=t,this.getGameObjectManager(e).stopAnimation(...i)},Ml=function(t){var e,i;[e,...i]=t,this.getGameObjectManager(e).pauseAnimation(...i)},El=function(t){var e,i;[e,...i]=t,this.getGameObjectManager(e).chainAnimation(...i)};const _l=[function(t,e,i){var s=i.name;e.on("+",(function(i,...r){if(!e.skipEventFlag){var n,a=i.split(".");Pl(a,s)&&(n=a[1],xr.call(t,`${s}.play`,Tl,[s,n,r],t),e.skipEvent())}})).on("+",(function(i){if(!e.skipEventFlag){var r,n=i.split(".");(function(t,e){return 3===t.length&&t[0]===e&&"stop"===t[2]})(n,s)&&(r=n[1],xr.call(t,`${s}.stop`,Ol,[s,r],t),e.skipEvent())}})).on("-",(function(i){if(!e.skipEventFlag){var r,n=i.split(".");Pl(n,s)&&(r=n[1],xr.call(t,`${s}.stop`,Ol,[s,r],t),e.skipEvent())}}))},function(t,e,i){var s=i.name;e.on("+",(function(i){if(!e.skipEventFlag){var r,n=i.split(".");(function(t,e){return 3===t.length&&t[0]===e&&"pause"===t[2]})(n,s)&&(r=n[1],xr.call(t,`${s}.pause`,Ml,[s,r],t),e.skipEvent())}}))},function(t,e,i){var s=i.name;e.on("+",(function(i){if(!e.skipEventFlag){var r,n=i.split(".");if(function(t,e){return 3===t.length&&t[0]===e&&"chain"===t[2]}(n,s)){r=n[1];var a=Array.prototype.slice.call(arguments,1);xr.call(t,`${s}.chain`,El,[s,r,a],t),e.skipEvent()}}}))}];var Rl=function(t){void 0===t&&(t={}),t.name="sprite",t.parseCallbacks=_l,t.createGameObject=Cl(t.createGameObject),this.addGameObjectManager(t,Sl)},Ll=function(t,e){return 2===t.length&&t[0]===e},Bl=function(t){var e,i;[e,...i]=t,this.getGameObjectManager(e).add(...i)},Il=function(t){var e,i;[e,...i]=t,this.getGameObjectManager(e).remove(...i)},Dl=function(t){this.getGameObjectManager(t).removeAll()},jl=function(t){var e,i,s,r;[e,i,s,...r]=t;var n=`${e}.${s}`;if(this.emit(n,i,...r),!(this.listenerCount(n)>0)){var a=this.getGameObjectManager(e);a.hasMethod(i,s)?a.call(i,s,...r):a.setProperty(i,s,r[0])}},Al={to:!0,yoyo:!0,from:!0,toLeft:!0,toRight:!0,toUp:!0,toDown:!0,yoyoLeft:!0,yoyoRight:!0,yoyoUp:!0,yoyoDown:!0,fromLeft:!0,fromRight:!0,fromUp:!0,fromDown:!0},zl=function(t){var e,i,s,r,n,a,o,h;[e,i,s,r,n,a,o,h]=t;var l=this.getGameObjectManager(e),d=l.getProperty(i,s);if("number"==typeof d){h.endsWith("Left")||h.endsWith("Up")?h.startsWith("to")||h.startsWith("yoyo")?r=d-r:h.startsWith("from")&&(l.setProperty(i,s,d-r),r=d):h.endsWith("Right")||h.endsWith("Down")?h.startsWith("to")||h.startsWith("yoyo")?r=d+r:h.startsWith("from")&&(l.setProperty(i,s,d+r),r=d):"from"===h&&(l.setProperty(i,s,r),r=d);var c=h.startsWith("yoyo");l.easeProperty(i,{property:s,value:r,duration:n,ease:a,repeat:o,yoyo:c})}};const Fl=[function(t,e,i){var s=i.name;e.on("+",(function(i,...r){if(!e.skipEventFlag){var n,a=i.split(".");Ll(a,s)&&(n=a[1],xr.call(t,`${s}.add`,Bl,[s,n,...r],t),e.skipEvent())}})).on("-",(function(i){if(!e.skipEventFlag){var r,n=i.split(".");Ll(n,s)&&(r=n[1],xr.call(t,`${s}.remove`,Il,[s,r],t),e.skipEvent())}}))},function(t,e,i){var s=i.name;e.on("-",(function(i){e.skipEventFlag||i===s&&(xr.call(t,`${s}.removeall`,Dl,s,t),e.skipEvent())}))},function(t,e,i){var s=i.name;e.on("+",(function(i,...r){if(!e.skipEventFlag){var n,a,o=i.split(".");(function(t,e){return 3===t.length&&t[0]===e})(o,s)&&(n=o[1],a=o[2],xr.call(t,`${s}.call`,jl,[s,n,a,...r],t),e.skipEvent())}}))},function(t,e,i){var s=i.name;t.getGameObjectManager(s),e.on("+",(function(i,r,n,a,o){if(!e.skipEventFlag){var h,l,d,c=i.split(".");(function(t,e){return 4===t.length&&t[0]===e&&Al[t[3]]})(c,s)&&(h=c[1],l=c[2],d=c[3],"number"==typeof a&&(o=a,a=void 0),xr.call(t,`${s}.ease`,zl,[s,h,l,r,n,a,o,d],t),e.skipEvent())}}))}],Yl=Wo.addGameObjectManager;var Xl={addGameObjectManager(t,e){(t=t?Ve(t):{}).name||console.warn("[TextPlayer] Parameter 'name' is required in addGameObjectManager(config) method");var i=t.defaultLayer,s=t.createGameObject,r=this.layerManager;t.createGameObject=function(t,...e){var n=s.call(this,t,...e);return i&&r&&r.addToLayer(i,n),n},Yl.call(this,t,e);for(var n=t.parseCallbacks,a=0,o=(n=n?[...n,...Fl]:Fl).length;a0)return nd.length=0,!0;return nd.length=0,!1},nd=[],ad=void 0;const od=Phaser.Utils.Objects.GetValue;var hd=function(t,e,i){var s,r;for(var n in void 0===i&&(i={}),t)s=t[n],void 0!==(r=od(e,n,s[1]))&&(i[s[0]]=r);return i},ld=function(t){t.addEventListener("touchstart",dd,!1),t.addEventListener("touchmove",dd,!1),t.addEventListener("touchend",dd,!1),t.addEventListener("mousedown",dd,!1),t.addEventListener("mouseup",dd,!1),t.addEventListener("mousemove",dd,!1)},dd=function(t){t.stopPropagation()},cd=function(){return this.close(),this.emit("keydown-ENTER",this.parent,this),this},ud=function(){this.isOpened=!0,this.initText(),this.enterCloseEnable&&this.scene.input.keyboard.once("keydown-ENTER",cd,this),this.scene.sys.events.on("postupdate",this.updateText,this),this.clickOutSideTarget?(xa.call(this.clickOutSideTarget,this.parent),ba.call(this.clickOutSideTarget,this.parent),this.clickOutSideTarget.setInteractive().on("pointerdown",this.onClickOutside,this)):this.scene.input.on("pointerdown",this.onClickOutside,this),this.onOpenCallback&&this.onOpenCallback(this.parent,this),this.emit("open",this)},pd=function(){this.isOpened=!1,this.updateText(),this.enterCloseEnable&&this.scene.input.keyboard.off("keydown-ENTER",cd,this),this.scene.sys.events.off("postupdate",this.updateText,this),this.clickOutSideTarget?this.clickOutSideTarget.disableInteractive().off("pointerdown",this.onClickOutside,this):this.scene.input.off("pointerdown",this.onClickOutside,this),this.onCloseCallback&&this.onCloseCallback(this.parent,this),function(t){if(t){var e=t.parentElement;e&&e.removeChild(t)}}(this.node),this.node=void 0,this.emit("close",this)};const gd=Phaser.Utils.Objects.GetValue;var vd=function(t,e){var i,s=gd(e,"inputType",void 0);void 0===s&&(s=gd(e,"type","text")),"textarea"===s?(i=document.createElement("textarea")).style.resize="none":(i=document.createElement("input")).type=s;var r=gd(e,"style",void 0),n=i.style;hd(ed,r,n),n.position="absolute",n.opacity=0,n.pointerEvents="none",n.zIndex=0,n.transform="scale(0)",hd(td,e,i),ld(i);var a=t.scene.sys.scale;return(a.isFullscreen?a.fullscreenTarget:document.body).appendChild(i),i.addEventListener("focus",(function(e){ud.call(t)})),i.addEventListener("blur",(function(e){pd.call(t)})),i},fd={open:function(){return this.isOpened||this.readOnly||((t=this)!==ad&&(void 0!==ad&&ad.close(),ad=t),this.node||(this.node=vd(this,this.nodeConfig)),this.setFocus()),this;var t},close:function(){return this.isOpened?(this===ad&&(ad=void 0),this.setBlur(),this):this}};const md=Phaser.Utils.Objects.GetValue;class yd extends Ra{constructor(t,e){super(t);var i=md(e,"inputType",void 0);void 0===i&&(i=md(e,"type","text")),this.setEnterCloseEnable(md(e,"enterClose","textarea"!==i));var s=md(e,"onOpen",void 0);s||(s=md(e,"onFocus",void 0)),this.onOpenCallback=s,this.clickOutSideTarget=md(e,"clickOutSideTarget",void 0);var r=md(e,"onClose",void 0);r||(r=md(e,"onBlur",void 0)),this.onCloseCallback=r,this.onUpdateCallback=md(e,"onUpdate",void 0),this.isOpened=!1,t.on("pointerdown",(function(){this.open()}),this).setInteractive(),this.nodeConfig=function(t){void 0===t&&(t={});var e={};return id(t,e,"inputType"),id(t,e,"type"),id(t,e,"style"),id(t,e,ed),id(t,e,td),e}(e),this.node=void 0}destroy(){this.close(),this.clickOutSideTarget&&this.clickOutSideTarget.destroy(),super.destroy()}onClickOutside(t){sd(this.parent,t)||this.close()}setEnterCloseEnable(t){return void 0===t&&(t=!0),this.enterCloseEnable=t,this}initText(){}updateText(){}get text(){return this.node?this.node.value:""}set text(t){this.node&&(this.node.value=t)}setText(t){return this.text=t,this}get maxLength(){return this.nodeConfig.maxLength}set maxLength(t){this.nodeConfig.maxLength=t,this.node&&(this.node.maxLength=t)}setMaxLength(t){return this.maxLength=t,this}get minLength(){return this.nodeConfig.minLength}set minLength(t){this.nodeConfig.minLength=t,this.node&&(this.node.minLength=t)}setMinLength(t){return this.minLength=t,this}get placeholder(){return this.node.placeholder}set placeholder(t){this.node&&(this.node.placeholder=t)}setPlaceholder(t){return this.placeholder=t,this}selectText(t,e){return this.node?(void 0===t?this.node.select():this.node.setSelectionRange(t,e),this):this}selectAll(){return this.selectText(),this}get selectionStart(){return this.node?this.node.selectionStart:0}get selectionEnd(){return this.node?this.node.selectionEnd:0}get selectedText(){if(!this.node)return"";var t=this.node;return t.value.substring(t.selectionStart,t.selectionEnd)}get cursorPosition(){return this.node?this.node.selectionStart:0}set cursorPosition(t){this.node&&this.node.setSelectionRange(t,t)}setCursorPosition(t){return void 0===t?t=this.text.length:t<0&&(t=this.text.length+t),this.cursorPosition=t,this}get tooltip(){return this.node?this.node.title:""}set tooltip(t){if(!this.node)return this;this.node.title=t}setTooltip(t){return this.tooltip=t,this}setTextChangedCallback(t){return this.onTextChanged=t,this}get readOnly(){return this.nodeConfig.readOnly}set readOnly(t){this.nodeConfig.readOnly=t,this.node&&(this.node.readOnly=t)}setReadOnly(t){return void 0===t&&(t=!0),this.readOnly=t,this}get spellCheck(){return this.node?this.node.spellcheck:""}set spellCheck(t){this.node&&(this.node.spellcheck=t)}setSpellCheck(t){return this.spellCheck=t,this}get fontColor(){if(this.node)return this.node.style.color}set fontColor(t){this.node&&(this.node.style.color=t)}setFontColor(t){return this.fontColor=t,this}setStyle(t,e){return this.node?(this.node.style[t]=e,this):this}getStyle(t){if(this.node)return this.node.style[t]}scrollToBottom(){return this.node?(this.node.scrollTop=this.node.scrollHeight,this):this}setEnabled(t){return this.node?(void 0===t&&(t=!0),this.node.disabled=!t,this):this}setBlur(){return this.node?(this.node.blur(),this):this}setFocus(){return this.node?(this.node.focus(),this):this}get isFocused(){return this.isOpened}}Object.assign(yd.prototype,fd);var bd=function(t,e,i){t=t.replace(" ","");var s=i.previousText;if(t===s)return t;if(isNaN(t)){i.emit("nan",t,i),t=s;var r=i.cursorPosition-1;i.setText(t),i.setCursorPosition(r)}else i.previousText=t;return t},xd=function(t){var e=t.prevSelectionStart;if(null!==e){for(var i=t.prevSelectionEnd,s=t.parent,r=e;r=r&&h=i&&hi.length&&(t.prevCursorPosition=null),null!==t.prevCursorPosition&&(s=e.getCharChild(t.prevCursorPosition))&&("\n"===s.text&&s.clearTextSize(),e.emit("cursorout",s,t.prevCursorPosition,e)),null!=r&&(s=e.getCharChild(r))&&("\n"===s.text&&s.copyTextSize(e.lastInsertCursor),function(t){var e,i,s=t.parent,r=s.width,n=s.height,a=t.drawX,o=t.drawY,h=a+t.drawTLX,l=a+t.drawTRX,d=o+t.drawTLY,c=o+t.drawBLY;e=h<0?0-h:l>r?r-l:0,i=d<0?0-d:c>n?n-c:0,s._textOX+=e,s._textOY+=i}(s),e.emit("cursorin",s,r,e)),e.emit("movecursor",r,t.prevCursorPosition,e),t.prevCursorPosition=r)}(this)):(xd(this),Cd(this)),this}setNumberInput(){return this.onUpdateCallback=bd,this}setSelectAllWhenFocusEnable(t){return void 0===t&&(t=!0),this.selectAllWhenFocus=t,this}setRequestCursorPosition(t){return this.isOpened?(this.requestCursorPosition=t,this):this}};const Sd=Phaser.Utils.Objects.GetValue,Pd=["inputType","onOpen","clickOutSideTarget","onFocus","onClose","onBlur","onUpdate","enterClose","readOnly","maxLength","minLength","selectAll"];var Td=function(t,e){if(t&&"number"!=typeof t){if(t.hasOwnProperty(e))return!0;if(-1!==e.indexOf(".")){for(var i=e.split("."),s=t,r=0;r0))return e;return null}(e);if(i){e.setScrollFactor(0).setOrigin(.5);var s=t.sys.scale.gameSize,r=s.width,n=s.height,a=1/i.zoom,o=r/2,h=n/2,l=r*a,d=n*a;e.x===o&&e.y===h||e.setPosition(o,h),e.width===l&&e.height===d||e.setSize(l,d)}}}const Ed=Phaser.GameObjects.Zone;let _d=class extends Ed{constructor(t){super(t,0,0,2,2),this.fullWindow=new Md(this)}};var Rd=function(t,e,i,s){if(void 0===i&&(i="."),void 0===s&&(s={}),!t)return s;if(e in t)return Object.assign(s,t[e]);for(var r in e+=i,t)r.startsWith(e)&&(s[r.replace(e,"")]=t[r]);return s},Ld=function(){var t=this.scene.input.keyboard;this.textEdit.on("open",(function(){t.on("keydown-UP",this.cursorMoveUp,this).on("keydown-DOWN",this.cursorMoveDown,this)}),this).on("close",(function(){t.off("keydown-UP",this.cursorMoveUp,this).off("keydown-DOWN",this.cursorMoveDown,this)}),this)},Bd=function(t,e,i){if(void 0===i&&(i={}),Array.isArray(e))for(var s=0,r=e.length;st.length?i:t})),a.value=t.join(e)}else a.value=t.join(i.slice(o,o+a.count));o+=a.count,a.added||(h+=a.count)}}let l=e[a-1];return a>1&&"string"==typeof l.value&&(l.added||l.removed)&&t.equals("",l.value)&&(e[a-2].value+=l.value,e.pop()),e}Ad.prototype={diff(t,e,i={}){let s=i.callback;"function"==typeof i&&(s=i,i={}),this.options=i;let r=this;function n(t){return s?(setTimeout((function(){s(void 0,t)}),0),!0):t}t=this.castInput(t),e=this.castInput(e),t=this.removeEmpty(this.tokenize(t));let a=(e=this.removeEmpty(this.tokenize(e))).length,o=t.length,h=1,l=a+o;i.maxEditLength&&(l=Math.min(l,i.maxEditLength));let d=[{newPos:-1,components:[]}],c=this.extractCommon(d[0],e,t,0);if(d[0].newPos+1>=a&&c+1>=o)return n([{value:this.join(e),count:e.length}]);function u(){for(let s=-1*h;s<=h;s+=2){let h,l=d[s-1],c=d[s+1],u=(c?c.newPos:0)-s;l&&(d[s-1]=void 0);let p=l&&l.newPos+1=a&&u+1>=o)return n(zd(r,h.components,e,t,r.useLongestToken));d[s]=h}else d[s]=void 0}var i;h++}if(s)!function t(){setTimeout((function(){if(h>l)return s();u()||t()}),0)}();else for(;h<=l;){let t=u();if(t)return t}},pushComponent(t,e,i){let s=t[t.length-1];s&&s.added===e&&s.removed===i?t[t.length-1]={count:s.count+1,added:e,removed:i}:t.push({count:1,added:e,removed:i})},extractCommon(t,e,i,s){let r=e.length,n=i.length,a=t.newPos,o=a-s,h=0;for(;a+1t,tokenize:t=>t.split(""),join:t=>t.join("")};const Fd=new Ad,Yd=/^[a-zA-Z\u{C0}-\u{FF}\u{D8}-\u{F6}\u{F8}-\u{2C6}\u{2C8}-\u{2D7}\u{2DE}-\u{2FF}\u{1E00}-\u{1EFF}]+$/u,Xd=/\S/,Wd=new Ad;Wd.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!Xd.test(t)&&!Xd.test(e)},Wd.tokenize=function(t){let e=t.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/);for(let t=0;tvoid 0===i?e:i}=this.options;return"string"==typeof t?t:JSON.stringify(Ud(t,null,null,i),i," ")},Hd.equals=function(t,e){return Ad.prototype.equals.call(Hd,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};const Nd=new Ad;Nd.tokenize=function(t){return t.slice()},Nd.join=Nd.removeEmpty=function(t){return t};const $d=Phaser.Utils.Array.Remove;var Kd=function(t,e){var i=t.text;if(e!==i){if(null==i&&(i=""),$d(t.children,t.lastInsertCursor),""===e)t.removeChildren();else for(var s=(h=i,l=e,Fd.diff(h,l,d)),r=0,n=0,a=s.length;nr)i+=a;else{if(s!==r)break;i+=Math.min(e.position,a)}}return i},tc={cursorMoveLeft(){if(!this.isOpened)return this;var t=qd(this.cursorPosition-1,0,this.inputText.length);return this.setCursorPosition(t),this},cursorMoveRight(){if(!this.isOpened)return this;var t=qd(this.cursorPosition+1,0,this.inputText.length);return this.setCursorPosition(t),this},cursorMoveUp(){if(!this.isOpened)return this;var t=Zd(this.characterCountOfLines,this.cursorPosition);t.lineIndex-=1;var e=qd(Qd(this.characterCountOfLines,t),0,this.inputText.length);return this.setCursorPosition(e),this},cursorMoveDown(){if(!this.isOpened)return this;var t=Zd(this.characterCountOfLines,this.cursorPosition);t.lineIndex+=1;var e=qd(Qd(this.characterCountOfLines,t),0,this.inputText.length);return this.setCursorPosition(e),this}};const ec=Phaser.Utils.Objects.IsPlainObject;class ic extends hn{constructor(t,e,i,s,r,n){ec(e)?n=e:ec(s)&&(n=s),void 0===n&&(n={}),function(t,e){var i=!e.textArea;if(Td(e,"wrap.vAlign")||P(e,"wrap.vAlign",s=i?"center":"top"),Td(e,"wrap.wrapMode")||P(e,"wrap.wrapMode","char"),Td(e,"wrap.maxLines")||P(e,"wrap.maxLines",s=i?1:void 0),i&&P(e,"wrap.wrapWidth",1/0),Td(e,"wrap.useDefaultTextHeight")||P(e,"wrap.useDefaultTextHeight",!0),e.edit||(e.edit={}),!Td(e.edit,"inputType")){var s=i?"text":"textarea";P(e.edit,"inputType",s)}if(!0===e.clickOutSideTarget){var r=new _d(t);t.add.existing(r),e.clickOutSideTarget=r}}(t,n);var a=n.text;a&&delete n.text;var o=Rd(n.background,"focus"),h=Rd(n.style,"cursor");super(t,e,i,s,r,n),this.type="rexCanvasInput",this.contentWidth=void 0,this.contentHeight=void 0,this.lineHeight=void 0,this.linesCount=void 0,this.characterCountOfLines=[],this._text,this.textEdit=function(t,e){var i=Sd(e,"edit");return void 0===i&&(i={}),id(e,i,Pd),new wd(t,i)}(this,n),Ld.call(this),n.focusStyle&&Object.assign(o,n.focusStyle),jd.call(this,o),n.cursorStyle&&Object.assign(h,n.cursorStyle),Dd.call(this,h);var l=n.onAddChar;l&&this.on("addchar",l);var d=n.onCursorOut;d&&this.on("cursorout",d);var c=n.onCursorIn;c&&this.on("cursorin",c);var u,p=n.onMoveCursor;p&&this.on("movecursor",p),this.setParseTextCallback(n.parseTextCallback),this.lastInsertCursor=((u=this.createCharChild("|")).text="",u),a||(a=""),this.setText(a)}addChild(t,e){if(super.addChild(t,e),Array.isArray(t))for(var i=t,s=0,r=i.length;s0,a=0,o=e.length;a0;this.dirty=this.dirty||this._radiusTL!==t||this._convexTL!==e,this._convexTL=e,this._radiusTL=Math.abs(t)}get radiusTR(){return this._radiusTR}set radiusTR(t){var e=t>0;this.dirty=this.dirty||this._radiusTR!==t||this._convexTR!==e,this._convexTR=e,this._radiusTR=Math.abs(t)}get radiusBL(){return this._radiusBL}set radiusBL(t){var e=t>0;this.dirty=this.dirty||this._radiusBL!==t||this._convexBL!==e,this._convexBL=e,this._radiusBL=Math.abs(t)}get radiusBR(){return this._radiusBR}set radiusBR(t){var e=t>0;this.dirty=this.dirty||this._radiusBR!==t||this._convexBR!==e,this._convexBR=e,this._radiusBR=Math.abs(t)}get radius(){return Math.max(this.radiusTL,this.radiusTR,this.radiusBL,this.radiusBR)}set radius(t){"number"==typeof t?(this.radiusTL=t,this.radiusTR=t,this.radiusBL=t,this.radiusBR=t):(this.radiusTL=$c(t,"tl",0),this.radiusTR=$c(t,"tr",0),this.radiusBL=$c(t,"bl",0),this.radiusBR=$c(t,"br",0))}setRadius(t){return void 0===t&&(t=0),this.radius=t,this}get iterations(){return this._iterations}set iterations(t){this.dirty=this.dirty||this._iterations!==t,this._iterations=t}setIterations(t){return this.iterations=t,this}updateData(){var t=this.pathData;t.length=0;var e,i=this.width,s=this.height,r=this.iterations+1;return(e=this.radiusTL)>0?this._convexTL?Rt(e,e,e,e,180,270,!1,r,t):Rt(0,0,e,e,90,0,!0,r,t):Et(0,0,t),(e=this.radiusTR)>0?this._convexTR?Rt(i-e,e,e,e,270,360,!1,r,t):Rt(i,0,e,e,180,90,!0,r,t):Et(i,0,t),(e=this.radiusBR)>0?this._convexBR?Rt(i-e,s-e,e,e,0,90,!1,r,t):Rt(i,s,e,e,270,180,!0,r,t):Et(i,s,t),(e=this.radiusBL)>0?this._convexBL?Rt(e,s-e,e,e,90,180,!1,r,t):Rt(0,s,e,e,360,270,!0,r,t):Et(0,s,t),t.push(t[0],t[1]),Ec(this.x,this.y,t),super.updateData(),this}}const Jc=Phaser.Renderer.WebGL.Utils.getTintAppendFloatAlpha;var qc={buildShapes(){this.addShape((new Kc).setName("box")).addShape((new Uc).setName("checker"))},updateShapes(){var t=this.width/2,e=this.height/2,i=Math.min(t,e),s=2*i,r=t-i,n=e-i,a=this.boxLineWidth,o=Math.max(s/10,2),h=this.getShape("box"),l=this.getShape("checker");if(this.isSizeChanged){var d=s*(1-this.boxSize)/2,c=a/2,u=s*this.boxSize-a;h.setTopLeftPosition(r+c+d,n+c+d).setSize(u,u),this.isCircleShape?h.setRadius(u/2):h.setRadius(0),d=s*(1-this.checkerSize)/2;var p=s*this.checkerSize/4,g=1*p,v=2*p,f=3*p;l.startAt(g,v).lineTo(v,f).lineTo(f,g).offset(r+d,n+d).end()}this.checked?(h.fillStyle(this.boxFillColor,this.boxFillAlpha).lineStyle(a,this.boxStrokeColor,this.boxStrokeAlpha),l.lineStyle(o,this.checkerColor)):(h.fillStyle(this.uncheckedBoxFillColor,this.uncheckedBoxFillAlpha).lineStyle(a,this.uncheckedBoxStrokeColor,this.uncheckedBoxStrokeAlpha),l.lineStyle()),this.checked&&l.setDisplayPathSegment(this.checkerAnimProgress)}};const Zc=Phaser.Utils.Objects.GetValue,Qc=Phaser.Math.Linear;class tu extends Ja{constructor(t,e){super(t,e),this.resetFromJSON(),this.boot()}start(t){if(this.timer.isRunning)return this;var e=this.target;this.propertyKey=Zc(t,"key","value");var i=e[this.propertyKey];return this.fromValue=Zc(t,"from",i),this.toValue=Zc(t,"to",i),this.setEase(Zc(t,"ease",this.ease)),this.setDuration(Zc(t,"duration",this.duration)),this.setRepeat(Zc(t,"repeat",0)),this.setDelay(Zc(t,"delay",0)),this.setRepeatDelay(Zc(t,"repeatDelay",0)),this.timer.setDuration(this.duration).setRepeat(this.repeat).setDelay(this.delay).setRepeatDelay(this.repeatDelay),e[this.propertyKey]=this.fromValue,super.start(),this}updateTarget(t,e){var i=e.t;i=this.easeFn(i),t[this.propertyKey]=Qc(this.fromValue,this.toValue,i)}}var eu={setCheckerAnimationDuration(t){return void 0===t&&(t=0),this.checkerAnimDuration=t,this},playCheckerAnimation(){return void 0===this.checkerAnimProgressTask&&(this.checkerAnimProgressTask=new tu(this,{eventEmitter:null})),this.checkerAnimProgressTask.restart({key:"checkerAnimProgress",from:0,to:1,duration:this.checkerAnimDuration}),this},stopCheckerAnimation(){return void 0===this.checkerAnimProgressTask||this.checkerAnimProgressTask.stop(),this}},iu={};Object.assign(iu,gc,vc,qc,eu);const su=23730,ru=Phaser.Utils.Objects.GetValue,nu=Phaser.Utils.Objects.IsPlainObject;class au extends pc{constructor(t,e,i,s,r,n,a){nu(e)?(e=ru(a=e,"x",0),i=ru(a,"y",0),s=ru(a,"width",2),r=ru(a,"height",2),n=ru(a,"color",su)):nu(n)&&(n=ru(a=n,"color",su)),super(t,e,i,s,r),this.type="rexCheckbox",void 0===n&&(n=su),this.setBoxShape(ru(a,"circleBox",!1)),this.setBoxFillStyle(n,ru(a,"boxFillAlpha",1)),this.setUncheckedBoxFillStyle(ru(a,"uncheckedColor",null),ru(a,"uncheckedBoxFillAlpha",1)),this.setBoxStrokeStyle(ru(a,"boxLineWidth",4),ru(a,"boxStrokeColor",n),ru(a,"boxStrokeAlpha",1)),this.setUncheckedBoxStrokeStyle(this.boxLineWidth,ru(a,"uncheckedBoxStrokeColor",this.boxStrokeColor),ru(a,"uncheckedBoxStrokeAlpha",this.boxStrokeAlpha)),this.setCheckerStyle(ru(a,"checkerColor",16777215),ru(a,"checkerAlpha",1)),this.setBoxSize(ru(a,"boxSize",1)),this.setCheckerSize(ru(a,"checkerSize",1)),this.setCheckerAnimationDuration(ru(a,"animationDuration",150)),this.buildShapes();var o=ru(a,"checked");void 0===o&&(o=ru(a,"value",!1)),this.setValue(o)}get value(){return this._value}set value(t){t=!!t,this._value!==t&&(this.dirty=!0,this._value=t,t?this.playCheckerAnimation():this.stopCheckerAnimation(),this.emit("valuechange",t))}setValue(t){return this.value=t,this}toggleValue(){return this.setValue(!this.value),this}get checked(){return this.value}set checked(t){this.value=t}setChecked(t){return void 0===t&&(t=!0),this.setValue(t),this}toggleChecked(){return this.toggleValue(),this}get checkerAnimProgress(){return this._checkerAnimProgress}set checkerAnimProgress(t){this._checkerAnimProgress!==t&&(this._checkerAnimProgress=t,this.dirty=!0)}}Object.assign(au.prototype,iu);const ou=Phaser.Utils.Objects.GetValue;class hu extends Ra{constructor(t,e){super(t,e),this._enable=void 0,t.setInteractive(ou(e,"inputConfig",void 0)),this.resetFromJSON(e),this.boot()}resetFromJSON(t){return this.pointer=void 0,this.lastClickTime=void 0,this.isDown=!1,this.isOver=!1,this.setEnable(ou(t,"enable",!0)),this.setMode(ou(t,"mode",1)),this.setClickInterval(ou(t,"clickInterval",100)),this.setDragThreshold(ou(t,"threshold",void 0)),this}boot(){var t=this.parent;t.on("pointerdown",this.onPress,this),t.on("pointerup",this.onRelease,this),t.on("pointerout",this.onPointOut,this),t.on("pointermove",this.onMove,this),t.on("pointerover",this.onOver,this),t.on("pointerout",this.onOut,this)}shutdown(t){this.isShutdown||(this.pointer=null,super.shutdown(t))}get enable(){return this._enable}set enable(t){if(this._enable!==t){t||this.cancel(),this._enable=t;var e=t?"enable":"disable";this.emit(e,this,this.parent)}}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}toggleEnable(){return this.setEnable(!this.enable),this}setMode(t){return"string"==typeof t&&(t=lu[t]),this.mode=t,this}setClickInterval(t){return this.clickInterval=t,this}setDragThreshold(t){return this.dragThreshold=t,this}onPress(t,e,i,s){void 0===this.pointer&&(this.pointer=t,this.isDown=!0,this.emit("down",this,this.parent,t,s),0===this.mode&&this.click(t.downTime,t,s))}onRelease(t,e,i,s){this.pointer===t&&(this.isDown=!1,this.emit("up",this,this.parent,t,s),1===this.mode&&this.click(t.upTime,t,s),this.pointer=void 0)}onPointOut(t,e){this.pointer===t&&this.cancel()}onMove(t,e,i,s){this.pointer===t&&void 0!==this.dragThreshold&&1===this.mode&&t.getDistance()>=this.dragThreshold&&this.cancel()}onOver(t,e,i,s){return this.enable?(this.isOver=!0,this.emit("over",this,this.parent,t,s),this):this}onOut(t,e){return this.enable?(this.isOver=!1,this.emit("out",this,this.parent,t,e),this):this}click(t,e,i){if(!this.enable)return this;if(void 0===t)return this.emit("click",this,this.parent,e,i),this;this.pointer=void 0;var s=this.lastClickTime;return void 0!==s&&t-s<=this.clickInterval||(this.lastClickTime=t,this.emit("click",this,this.parent,e,i)),this}cancel(){return this.pointer=void 0,this}}const lu={press:0,pointerdown:0,release:1,pointerup:1},du=Phaser.Utils.Objects.GetValue,cu=Phaser.Utils.Objects.IsPlainObject;class uu extends au{constructor(t,e,i,s,r,n,a){cu(e)?(e=du(a=e,"x",0),i=du(a,"y",0),s=du(a,"width",2),r=du(a,"height",2),n=du(a,"color",su)):cu(n)&&(n=du(a=n,"color",su)),super(t,e,i,s,r,n,a),this._click=new hu(this,du(a,"click")),this._click.on("click",(function(){this.toggleValue()}),this),this.setReadOnly(du(a,"readOnly",!1))}get readOnly(){return!this._click.enable}set readOnly(t){this._click.enable=!t}setReadOnly(t){return void 0===t&&(t=!0),this.readOnly=t,this}}t.register("checkbox",(function(t,e,i,s,r,n){var a=new uu(this.scene,t,e,i,s,r,n);return this.scene.add.existing(a),a})),P(window,"RexPlugins.UI.Checkbox",uu);var pu={setTrackFillStyle(t,e){return void 0===e&&(e=1),this.dirty=this.dirty||this.trackFillColor!==t||this.trackFillAlpha!==e,this.trackFillColor=t,this.trackFillAlpha=e,this},setFalseValueTrackFillStyle(t,e){return void 0===e&&(e=1),this.dirty=this.dirty||this.falseValueTrackColor!==t||this.uncheckedTrackFillAlpha!==e,this.falseValueTrackColor=t,this.falseValueTrackFillAlpha=e,this},setThumbStyle(t,e){return void 0===e&&(e=1),this.dirty=this.dirty||this.thumbColor!==t||this.checkAlpha!==e,this.thumbColor=t,this.thumbAlpha=e,this}},gu={setTrackSize(t,e){return this.dirty=this.dirty||this.trackWidth!==t||this.trackHeight!==e,this.trackWidth=t,this.trackHeight=e,this},setTrackRadius(t){return this.dirty=this.dirty||this.trackRadius!==t,this.trackRadius=t,this},setThumbSize(t,e){return void 0===e&&(e=t),this.dirty=this.dirty||this.thumbWidth!==t||this.thumbHeight!==e,this.thumbWidth=t,this.thumbHeight=e,this},setThumbRadius(t){return this.dirty=this.dirty||this.thumbRadius!==t,this.thumbRadius=t,this}},vu={setThumbPosition(t,e){return void 0===e&&(e=1-t),this.thumbLeftX=t,this.thumbRightX=e,this},setRTL(t){return void 0===t&&(t=!0),this.rtl=t,this}},fu=function(t,e,i){return(e-t)*i+t};const mu=Phaser.Math.Linear;var yu={buildShapes(){this.addShape((new Kc).setName("track")).addShape((new Kc).setName("thumb"))},updateShapes(){var t=this.width,e=this.height,i=this.value?this.toggleAnimProgress:1-this.toggleAnimProgress,s=this.getShape("track");if(this.isSizeChanged){var r=t*this.trackWidth,n=e*this.trackHeight,a=(t-r)/2,o=(e-n)/2,h=e*this.trackRadius;s.setTopLeftPosition(a,o).setSize(r,n).setRadius(h)}var l,d,c,u=(l=this.falseValueTrackColor,d=this.trackFillColor,c=i,(255&fu(mn(l),mn(d),c))<<16|(255&fu(yn(l),yn(d),c))<<8|255&fu(bn(l),bn(d),c)),p=mu(this.falseValueTrackFillAlpha,this.trackFillAlpha,i);s.fillStyle(u,p);var g=this.getShape("thumb");if(this.isSizeChanged){var v=t*this.thumbWidth,f=e*this.thumbHeight,m=e*this.thumbRadius;g.setSize(v,f).setRadius(m)}var y=mu(this.thumbLeftX,this.thumbRightX,i)*t;this.rtl&&(y=t-y);var b=e/2;g.setCenterPosition(y,b),g.fillStyle(this.thumbColor,this.thumbAlpha)}},bu={setToggleAnimationDuration(t){return void 0===t&&(t=0),this.toggleAnimDuration=t,this},playToggleAnimation(){return void 0===this.toggleAnimProgressTask&&(this.toggleAnimProgressTask=new tu(this,{eventEmitter:null})),this.toggleAnimProgressTask.restart({key:"toggleAnimProgress",from:0,to:1,duration:this.toggleAnimDuration}),this},stopToggleAnimation(){return void 0===this.toggleAnimProgressTask||this.toggleAnimProgressTask.stop(),this}},xu={};Object.assign(xu,pu,gu,vu,yu,bu);const Cu=Phaser.Utils.Objects.GetValue,ku=Phaser.Utils.Objects.IsPlainObject,wu=23730;class Su extends pc{constructor(t,e,i,s,r,n,a){ku(e)?(e=Cu(a=e,"x",0),i=Cu(a,"y",0),s=Cu(a,"width",2),r=Cu(a,"height",2),n=Cu(a,"color",wu)):ku(n)&&(n=Cu(a=n,"color",wu)),super(t,e,i,s,r),this.type="rexToggleSwitch",void 0===n&&(n=wu),this.setTrackFillStyle(n,Cu(a,"trackFillAlpha",1)),this.setFalseValueTrackFillStyle(Cu(a,"falseValueTrackColor",function(t){var e=.3*mn(t)+.59*yn(t)+.11*bn(t);return(255&e)<<16|(255&e)<<8|255&e}(n)),Cu(a,"falseValueTrackFillAlpha",1)),this.setThumbStyle(Cu(a,"thumbColor",16777215),Cu(a,"thumbAlpha",1)),this.setTrackSize(Cu(a,"trackWidth",.9),Cu(a,"trackHeight",.5)),this.setTrackRadius(Cu(a,"trackRadius",.5*this.trackHeight));var o=Cu(a,"thumbHeight",void 0),h=Cu(a,"thumbWidth",o);void 0===h&&(h=.9*this.trackHeight),this.setThumbSize(h,o),this.setThumbRadius(Cu(a,"thumbRadius",.5*this.thumbHeight)),this.setThumbPosition(Cu(a,"thumbLeft",.3),Cu(a,"thumbRight",void 0)),this.setRTL(Cu(a,"rtl",!1)),this.setToggleAnimationDuration(Cu(a,"animationDuration",150)),this.buildShapes(),this.setValue(Cu(a,"value",!1),0)}get value(){return this._value}set value(t){t=!!t,this._value!==t&&(this.dirty=!0,this._value=t,this.playToggleAnimation(),this.emit("valuechange",t))}setValue(t,e){void 0===e&&(e=this.toggleAnimDuration);var i=this.toggleAnimDuration;return this.toggleAnimDuration=e,this.value=t,this.toggleAnimDuration=i,this}toggleValue(t){return this.setValue(!this.value,t),this}get toggleAnimProgress(){return this._toggleAnimProgress}set toggleAnimProgress(t){this._toggleAnimProgress!==t&&(this._toggleAnimProgress=t,this.dirty=!0)}}Object.assign(Su.prototype,xu);const Pu=Phaser.Utils.Objects.GetValue;class Tu extends Su{constructor(t,e,i,s,r,n,a){super(t,e,i,s,r,n,a),this._click=new hu(this,Pu(a,"click")),this._click.on("click",(function(){this.toggleValue()}),this),this.setReadOnly(Pu(a,"readOnly",!1))}get readOnly(){return!this._click.enable}set readOnly(t){this._click.enable=!t}setReadOnly(t){return void 0===t&&(t=!0),this.readOnly=t,this}}t.register("toggleSwitch",(function(t,e,i,s,r,n){var a=new Tu(this.scene,t,e,i,s,r,n);return this.scene.add.existing(a),a})),P(window,"RexPlugins.UI.ToggleSwitch",Tu);var Ou={loadFromURL(t,e){var i=this,s=new Image;return s.onload=function(){i.width!==s.width||i.height!==s.height?i.resize(s.width,s.height):i.clear(),i.context.drawImage(s,0,0),i.updateTexture(),e&&e(),s.onload=null,s.src="",s.remove()},s.src=t,this},loadFromURLPromise(t){var e=this;return new Promise((function(i,s){e.loadFromURL(t,i)}))},loadFromFile(t,e){var i=URL.createObjectURL(t);return this.loadFromURL(i,(function(){URL.revokeObjectURL(i),e&&e()})),this},loadFromFilePromise(t){var e=this;return new Promise((function(i,s){e.loadFromFile(t,i)}))}};class Mu extends Nt{}Object.assign(Mu.prototype,Ou),t.register("canvas",(function(t,e,i,s){var r=new Mu(this.scene,t,e,i,s);return this.scene.add.existing(r),r})),P(window,"RexPlugins.UI.Canvas",Mu);const Eu=Phaser.Utils.Objects.GetValue;class _u extends Nt{constructor(t,e,i,s,r,n){super(t,e,i),this.type="rexCircleMaskImage",this.setTexture(s,r,n)}setTexture(t,e,i){"object"==typeof e&&(i=e,e=void 0),"string"==typeof i&&(i={maskType:i});var s=Eu(i,"maskType",0),r=Eu(i,"backgroundColor",void 0),n=Eu(i,"strokeColor",void 0),a=Eu(i,"strokeWidth",null!=n?10:0);if(void 0===s?s=0:"string"==typeof s&&(s=Ru[s]),this._textureKey=t,this._frameName=e,null===s)return this.loadTexture(t,e),this.dirty=!0,this;var o=this.scene.sys.textures.getFrame(t,e);if(!o)return this;o.cutWidth!==this.width||o.cutHeight!==this.height?this.setCanvasSize(o.cutWidth,o.cutHeight):this.clear();var h=this.canvas,l=this.context,d=h.width,c=h.height;null!=r&&(l.fillStyle=r,l.fillRect(0,0,d,c)),l.save(),l.beginPath();var u=a/2;switch(s){case 1:var p=(m=Math.floor(d/2))-u,g=(y=Math.floor(c/2))-u;l.ellipse(m,y,p,g,0,0,2*Math.PI);break;case 2:var v=Eu(i,"radius",0),f=Eu(i,"iteration",void 0);Zt(l,u,u,d-a,c-a,v,f);break;default:var m=Math.floor(d/2),y=Math.floor(c/2),b=Math.min(m,y)-u;l.arc(m,y,b,0,2*Math.PI)}return null!=n&&(l.strokeStyle=n,l.lineWidth=a,l.stroke()),l.clip(),this.loadTexture(t,e),l.restore(),this.dirty=!0,this}resize(t,e){return this.setDisplaySize(t,e),this}}const Ru={circle:0,ellipse:1,roundRectangle:2};t.register("circleMaskImage",(function(t,e,i,s,r){var n=new _u(this.scene,t,e,i,s,r);return this.scene.add.existing(n),n})),P(window,"RexPlugins.UI.CircleMaskImage",_u);const Lu=Phaser.Utils.Objects.GetValue;class Bu extends Nt{constructor(t,e,i,s,r,n){super(t,e,i),this.type="rexAlphaMaskImage",this.maskFrame=null,this.setTexture(s,r,n)}setTexture(t,e,i){"object"==typeof e&&(i=e,e=void 0),"string"==typeof i&&(i={mask:{key:i}});var s=Lu(i,"mask.key"),r=Lu(i,"mask.frame"),n=Lu(i,"mask.invertAlpha",!1),a=Lu(i,"mask.scale"),o=Lu(i,"backgroundColor");if(s){this._maskKey=s,this._maskFrame=r,this._maskScale=a;var h=s?this.scene.sys.textures.get(s):null;this.maskFrame=h?h.get(r):null}this._textureKey=t,this._frameName=e;var l=this.maskFrame;if(null===l)return this.loadTexture(t,e),this.dirty=!0,this;var d=null!=o;this.loadTexture(t,e);var c,u,p=this.canvas,g=this.context,v=p.width,f=p.height;g.save(),g.globalCompositeOperation=n?"destination-out":"destination-in",null!=this._maskScale?(c=l.cutWidth*this._maskScale,u=l.cutHeight*this._maskScale):(c=v,u=f);var m=(v-c)/2,y=(f-u)/2;return this.drawFrame(this._maskKey,this._maskFrame,m,y,c,u),g.restore(),d&&(g.save(),g.globalCompositeOperation="destination-over",g.fillStyle=o,g.fillRect(0,0,v,f),g.restore()),this.dirty=!0,this}resize(t,e){return this.setDisplaySize(t,e),this}}t.register("alphaMaskImage",(function(t,e,i,s,r){var n=new Bu(this.scene,t,e,i,s,r);return this.scene.add.existing(n),n})),P(window,"RexPlugins.UI.AlphaMaskImage",Bu);const Iu=Phaser.Math.Linear,Du=Phaser.Math.Percent;var ju={setValue(t,e,i){return null==t||(void 0!==e&&(t=Du(t,e,i)),this.value=t),this},addValue(t,e,i){return void 0!==e&&(t=Du(t,e,i)),this.value+=t,this},getValue(t,e){var i=this.value;return void 0!==t&&(i=Iu(t,e,i)),i}};const Au=Phaser.Math.Percent;var zu={setEaseValuePropName:function(t){return this.easeValuePropName=t,this},setEaseValueDuration:function(t){return this.easeValueDuration=t,this},setEaseValueFunction:function(t){return this.easeFunction=t,this},stopEaseValue:function(){return this.easeValueTask&&this.easeValueTask.stop(),this},easeValueTo:function(t,e,i){return null==t||(void 0!==e&&(t=Au(t,e,i)),void 0===this.easeValueTask&&(this.easeValueTask=new tu(this,{eventEmitter:null})),this.easeValueTask.restart({key:this.easeValuePropName,to:t,duration:this.easeValueDuration,ease:this.easeFunction})),this},easeValueRepeat:function(t,e,i,s){return void 0===i&&(i=-1),void 0===s&&(s=0),void 0===this.easeValueTask&&(this.easeValueTask=new tu(this,{eventEmitter:null})),this.easeValueTask.restart({key:this.easeValuePropName,from:t,to:e,duration:this.easeValueDuration,ease:this.easeFunction,repeat:i,repeatDelay:s}),this}};const Fu=Phaser.Utils.Objects.GetValue,Yu=Phaser.Math.Clamp;function Xu(t){class e extends t{bootProgressBase(t){this.eventEmitter=Fu(t,"eventEmitter",this);var e=Fu(t,"valuechangeCallback",null);if(null!==e){var i=Fu(t,"valuechangeCallbackScope",void 0);this.eventEmitter.on("valuechange",e,i)}return this.setEaseValuePropName("value").setEaseValueDuration(Fu(t,"easeValue.duration",0)).setEaseValueFunction(Fu(t,"easeValue.ease","Linear")),this}get value(){return this._value}set value(t){t=Yu(t,0,1);var e=this._value,i=e!=t;this.dirty=this.dirty||i,this._value=t,i&&this.eventEmitter.emit("valuechange",this._value,e,this.eventEmitter)}}return Object.assign(e.prototype,ju,zu),e}const Wu=Phaser.Math.RadToDeg,Vu=Phaser.Math.DegToRad;var Gu=function(t,e,i,s,r,n,a,o){var h=360===Math.abs(a-n),l=Vu(n),d=Vu(a),c=Math.cos(l),u=Math.sin(l),p=Math.cos(d),g=Math.sin(d);return t.startAt(e+c*s,i+u*s),t.arc(e,i,s,n,a,o),h&&0===r||(t.lineTo(e+p*r,i+g*r),r>0&&t.arc(e,i,r,a,n,!o)),t.close(),t},Hu={buildShapes(){var t=this.iterations;this.addShape((new Uc).setIterations(t).setName("track")).addShape((new Uc).setIterations(t).setName("bar")).addShape((new kc).setIterations(t).setName("center"))},updateShapes(){var t=this.radius,e=this.thickness*this.radius,i=this.radius,s=i-e,r=this.getShape("track");null!=this.trackColor&&this.thickness>0?(r.fillStyle(this.trackColor),Gu(r,t,t,i,s,0,360,!1)):r.reset();var n,a,o,h=this.getShape("bar");null!=this.barColor&&this.thickness>0?(1===this.value?(n=!1,a=0,o=360):(n=this.anticlockwise,a=Wu(this.startAngle),o=360*(n?1-this.value:this.value)+a),h.fillStyle(this.barColor),Gu(h,t,t,i+1,s-1,a,o,!1)):h.reset();var l=this.getShape("center");this.centerColor&&s>0?l.setCenterPosition(t,t).setRadius(s).fillStyle(this.centerColor):l.reset()}};const Uu=Phaser.Utils.Objects.GetValue,Nu=Phaser.Utils.Objects.IsPlainObject,$u=Phaser.Math.Clamp,Ku=Phaser.Math.DegToRad(270);let Ju=class extends(Xu(pc)){constructor(t,e,i,s,r,n,a){Nu(e)&&(e=Uu(a=e,"x",0),i=Uu(a,"y",0),s=Uu(a,"radius",1),r=Uu(a,"barColor",void 0),n=Uu(a,"value",0)),void 0===s&&(s=1);var o=2*s;super(t,e,i,o,o),this.type="rexCircularProgress",this.bootProgressBase(a),this.setRadius(s),this.setTrackColor(Uu(a,"trackColor",void 0)),this.setBarColor(r),this.setCenterColor(Uu(a,"centerColor",void 0)),this.setThickness(Uu(a,"thickness",.2)),this.setStartAngle(Uu(a,"startAngle",Ku)),this.setAnticlockwise(Uu(a,"anticlockwise",!1)),this.iterations=Uu(a,"iterations",128),this.buildShapes(),this.setValue(n)}resize(t,e){return(t=Math.floor(Math.min(t,e)))===this.width||(super.resize(t,t),this.setRadius(t/2)),this}get radius(){return this._radius}set radius(t){this.dirty=this.dirty||this._radius!=t,this._radius=t;var e=2*t;this.resize(e,e)}setRadius(t){return this.radius=t,this}get trackColor(){return this._trackColor}set trackColor(t){this.dirty=this.dirty||this._trackColor!=t,this._trackColor=t}setTrackColor(t){return this.trackColor=t,this}get barColor(){return this._barColor}set barColor(t){this.dirty=this.dirty||this._barColor!=t,this._barColor=t}setBarColor(t){return this.barColor=t,this}get startAngle(){return this._startAngle}set startAngle(t){this.dirty=this.dirty||this._startAngle!=t,this._startAngle=t}setStartAngle(t){return this.startAngle=t,this}get anticlockwise(){return this._anticlockwise}set anticlockwise(t){this.dirty=this.dirty||this._anticlockwise!=t,this._anticlockwise=t}setAnticlockwise(t){return void 0===t&&(t=!0),this.anticlockwise=t,this}get thickness(){return this._thickness}set thickness(t){t=$u(t,0,1),this.dirty=this.dirty||this._thickness!=t,this._thickness=t}setThickness(t){return this.thickness=t,this}get centerColor(){return this._centerColor}set centerColor(t){this.dirty=this.dirty||this._centerColor!=t,this._centerColor=t}setCenterColor(t){return this.centerColor=t,this}};Object.assign(Ju.prototype,Hu),t.register("circularProgress",(function(t,e,i,s,r,n){var a=new Ju(this.scene,t,e,i,s,r,n);return this.scene.add.existing(a),a})),P(window,"RexPlugins.UI.CircularProgress",Ju);var qu=function(t,e,i,s,r,n,a,o,h,l,d,c){void 0===l&&(l=0),void 0===d&&(d=2*Math.PI),void 0===c&&(c=!1),e.beginPath(),e.ellipse(i,s,r,n,0,l,d,c),null!=a&&(e.fillStyle=a,e.fill()),null!=o&&(e.strokeStyle=o,e.lineWidth=h,e.stroke())};const Zu=Phaser.Math.PI2;var Qu=function(){var t,e=this.radius,i=this.thickness*this.radius,s=this.radius-i/2,r=this.radius-i,n=(this.canvas,this.context),a=this.anticlockwise,o=this.startAngle,h=this.endAngle,l=this._deltaAngle;if(this.trackColor&&i>0&&(n.save(),qu(0,n,e,e,s,s,void 0,this.trackColor,i,o,h,a),n.restore()),this.barColor&&s>0){var d,c;if(d=this.value>=1?h:a?(o-l*this.value+Zu)%Zu:(o+l*this.value)%Zu,n.save(),this.barColor2){var u=e+s*Math.cos(o),p=e+s*Math.sin(o),g=e+s*Math.cos(d),v=e+s*Math.sin(d),f=n.createLinearGradient(u,p,g,v);f.addColorStop(0,this.barColor2),f.addColorStop(1,this.barColor),c=f}else c=this.barColor;qu(0,n,e,e,s,s,void 0,c,i,o,d,a),n.restore()}this.centerColor&&r>0&&(this.centerColor2?((t=this.context.createRadialGradient(e,e,0,e,e,r)).addColorStop(0,this.centerColor),t.addColorStop(1,this.centerColor2)):t=this.centerColor,n.save(),qu(0,n,e,e,r,r,t),n.restore()),this.textFormatCallback&&(this.textColor||this.textStrokeColor)&&(n.save(),function(t,e,i,s,r,n,a,o,h,l,d){void 0===h&&null!=o&&(h=2),void 0===l&&(l="start"),void 0===d&&(d="alphabetic"),e.font=n,e.textAlign=l,e.textBaseline=d,e.fillStyle=a,e.strokeStyle=o,e.lineWidth=h,e.lineCap="round",e.lineJoin="round",null!=o&&"none"!==o&&h>0&&e.strokeText(r,i,s),null!=a&&"none"!==a&&e.fillText(r,i,s)}(0,n,e,e,this.getFormatText(),this.textFont,this.textColor,this.textStrokeColor,this.textStrokeThickness,"center","middle"),n.restore())};const tp=Phaser.Utils.Objects.GetValue,ep=Phaser.Utils.Objects.IsPlainObject,ip=Phaser.Math.Clamp,sp=Phaser.Math.DegToRad(270),rp=Phaser.Math.PI2;class np extends(Xu(Nt)){constructor(t,e,i,s,r,n,a){ep(e)&&(e=tp(a=e,"x",0),i=tp(a,"y",0),s=tp(a,"radius",1),r=tp(a,"barColor",void 0),n=tp(a,"value",0));var o=2*s;super(t,e,i,o,o,tp(a,"resolution",1)),this.type="rexCircularProgressCanvas",this.bootProgressBase(a),this.setRadius(s),this.setTrackColor(tp(a,"trackColor",void 0)),this.setBarColor(r),this.setBarColor2(tp(a,"barColor2",void 0)),this.setCenterColor(tp(a,"centerColor",void 0)),this.setThickness(tp(a,"thickness",.2)),this.setStartAngle(tp(a,"startAngle",sp)),this.setEndAngle(tp(a,"endAngle",this.startAngle+rp)),this.setAnticlockwise(tp(a,"anticlockwise",!1)),this.setTextColor(tp(a,"textColor",void 0)),this.setTextStrokeColor(tp(a,"textStrokeColor",void 0),tp(a,"textStrokeThickness",void 0));var h=tp(a,"textFont",void 0);h?this.setTextFont(h):this.setTextFont(tp(a,"textSize","16px"),tp(a,"textFamily","Courier"),tp(a,"textStyle","")),this.setTextFormatCallback(tp(a,"textFormatCallback",void 0),tp(a,"textFormatCallbackScope",void 0)),this.setValue(n)}resize(t,e){return(t=Math.floor(Math.min(t,e)))===this.width||(super.resize(t,t),this.setRadius(t/2)),this}get radius(){return this._radius}set radius(t){this.dirty=this.dirty||this._radius!=t,this._radius=t;var e=2*t;this.resize(e,e)}setRadius(t){return this.radius=t,this}get trackColor(){return this._trackColor}set trackColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._trackColor!=t,this._trackColor=t}setTrackColor(t){return this.trackColor=t,this}get barColor(){return this._barColor}set barColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._barColor!=t,this._barColor=t}setBarColor(t){return this.barColor=t,this}get barColor2(){return this._barColor2}set barColor2(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._barColor2!=t,this._barColor2=t}setBarColor2(t){return this.barColor2=t,this}get startAngle(){return this._startAngle}set startAngle(t){this.dirty=this.dirty||this._startAngle!=t,this._startAngle=t,this._deltaAngle=ap(this._startAngle,this._endAngle,this._anticlockwise)}setStartAngle(t){return this.startAngle=t,this}get endAngle(){return this._endAngle}set endAngle(t){this.dirty=this.dirty||this._endAngle!=t,this._endAngle=t,this._deltaAngle=ap(this._startAngle,this._endAngle,this._anticlockwise)}setEndAngle(t){return this.endAngle=t,this}get anticlockwise(){return this._anticlockwise}set anticlockwise(t){this.dirty=this.dirty||this._anticlockwise!=t,this._anticlockwise=t,this._deltaAngle=ap(this._startAngle,this._endAngle,this._anticlockwise)}setAnticlockwise(t){return void 0===t&&(t=!0),this.anticlockwise=t,this}get thickness(){return this._thickness}set thickness(t){t=ip(t,0,1),this.dirty=this.dirty||this._thickness!=t,this._thickness=t}setThickness(t){return this.thickness=t,this}get centerColor(){return this._centerColor}set centerColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._centerColor!=t,this._centerColor=t}get centerColor2(){return this._centerColor2}set centerColor2(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._centerColor2!=t,this._centerColor2=t}setCenterColor(t,e){return this.centerColor=t,this.centerColor2=e,this}get textColor(){return this._textColor}set textColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._textColor!=t,this._textColor=t}setTextColor(t){return this.textColor=t,this}get textStrokeColor(){return this._textStrokeColor}set textStrokeColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._textStrokeColor!=t,this._textStrokeColor=t}get textStrokeThickness(){return this._textStrokeThickness}set textStrokeThickness(t){this.dirty=this.dirty||this._textStrokeThickness!=t,this._textStrokeThickness=t}setTextStrokeColor(t,e){return void 0===e&&(e=2),this.textStrokeColor=t,this.textStrokeThickness=e,this}get textFont(){return this._textFont}set textFont(t){this.dirty=this.dirty||this._textFont!=t,this._textFont=t}setTextFont(t,e,i){var s;return s=void 0===e?t:i+" "+t+" "+e,this.textFont=s,this}setTextFormatCallback(t,e){return this.textFormatCallback=t,this.textFormatCallbackScope=e,this}updateTexture(){return super.updateTexture((function(){this.clear(),Qu.call(this)}),this),this}getFormatText(t){return void 0===t&&(t=this.value),this.textFormatCallbackScope?this.textFormatCallback(t):this.textFormatCallback.call(this.textFormatCallbackScope,t)}}var ap=function(t,e,i){return i?t<=e?rp+t-e:t-e:t>=e?rp+e-t:e-t};t.register("circularProgressCanvas",(function(t,e,i,s,r,n){var a=new np(this.scene,t,e,i,s,r,n);return this.scene.add.existing(a),a})),P(window,"RexPlugins.UI.CircularProgressCanvas",np);var op=function(t,e,i,s,r,n){var a=(e+s)/2;return n>=0?t.startAt(a+n,i).lineTo(s+n,i).lineTo(s,r).lineTo(e,r).lineTo(e+n,i).lineTo(a+n,i):t.startAt(a,i).lineTo(s,i).lineTo(s-n,r).lineTo(e-n,r).lineTo(e,i).lineTo(a,i),t};const hp=Phaser.Utils.Objects.GetValue,lp=Phaser.Utils.Objects.IsPlainObject;let dp=class extends(Xu(pc)){constructor(t,e,i,s,r,n,a,o){lp(e)?(e=hp(o=e,"x",0),i=hp(o,"y",0),s=hp(o,"width",2),r=hp(o,"height",2),n=hp(o,"barColor",void 0),a=hp(o,"value",0)):lp(s)?(s=hp(o=s,"width",2),r=hp(o,"height",2),n=hp(o,"barColor",void 0),a=hp(o,"value",0)):lp(n)&&(n=hp(o=n,"barColor",void 0),a=hp(o,"value",0)),super(t,e,i,s,r,o),this.type="rexLineProgress",this.bootProgressBase(o),this.addShape((new Uc).setName("trackFill")).addShape((new Uc).setName("bar")).addShape((new Uc).setName("trackStroke")),this.setTrackColor(hp(o,"trackColor",void 0)),this.setBarColor(n),this.setTrackStroke(hp(o,"trackStrokeThickness",2),hp(o,"trackStrokeColor",void 0)),this.setSkewX(hp(o,"skewX",0)),this.setRTL(hp(o,"rtl",!1)),this.setValue(a)}get trackColor(){return this._trackColor}set trackColor(t){this.dirty=this.dirty||this._trackColor!=t,this._trackColor=t}setTrackColor(t){return this.trackColor=t,this}get trackStrokeColor(){return this._trackStrokeColor}set trackStrokeColor(t){this.dirty=this.dirty||this._trackStrokeColor!=t,this._trackStrokeColor=t}get trackStrokeThickness(){return this._trackStrokeThickness}set trackStrokeThickness(t){this.dirty=this.dirty||this._trackStrokeThickness!=t,this._trackStrokeThickness=t}setTrackStroke(t,e){return this.trackStrokeThickness=t,this.trackStrokeColor=e,this}get barColor(){return this._barColor}set barColor(t){this.dirty=this.dirty||this._barColor!=t,this._barColor=t}setBarColor(t){return this.barColor=t,this}get skewX(){return this._skewX}set skewX(t){this.dirty=this.dirty||this._skewX!=t,this._skewX=t}setSkewX(t){return this.skewX=t,this}get rtl(){return this._rtl}set rtl(t){t=!!t,this.dirty=this.dirty||this._rtl!=t,this._rtl=t}setRTL(t){return void 0===t&&(t=!0),this.rtl=t,this}};var cp={updateShapes:function(){var t=this.skewX,e=this.width-Math.abs(t),i=this.height,s=this.getShape("trackFill");s.fillStyle(this.trackColor),s.isFilled&&op(s,0,0,e,i,t).close();var r,n,a=this.getShape("bar");a.fillStyle(this.barColor),a.isFilled&&(this.rtl?(r=e*(1-this.value),n=e):(r=0,n=e*this.value),op(a,r,0,n,i,t).close());var o=this.getShape("trackStroke");o.lineStyle(this.trackStrokeThickness,this.trackStrokeColor),o.isStroked&&op(o,0,0,e,i,t).end()}};Object.assign(dp.prototype,cp),t.register("lineProgress",(function(t,e,i,s,r,n,a){var o=new dp(this.scene,t,e,i,s,r,n,a);return this.scene.add.existing(o),o})),P(window,"RexPlugins.UI.LineProgress",dp);var up=function(t,e,i,s,r,n,a){void 0===a&&(a="round"),function(t,e){t.save(),t.beginPath();var i=e[0];t.moveTo(i.x,i.y);for(var s=1,r=e.length;s0&&(n.save(),up(0,n,this.trackPoints,void 0,this.trackStrokeColor,this.trackStrokeThickness),n.restore())},gp=function(t,e,i,s,r,n){void 0===n&&(n=[]),n.length=4;for(var a=0;a<4;a++)n[a]||(n[a]={});var o;return r>=0?((o=n[0]).x=t+r,o.y=e,(o=n[1]).x=i+r,o.y=e,(o=n[2]).x=i,o.y=s,(o=n[3]).x=t,o.y=s):((o=n[0]).x=t,o.y=e,(o=n[1]).x=i,o.y=e,(o=n[2]).x=i-r,o.y=s,(o=n[3]).x=t-r,o.y=s),n};const vp=Phaser.Utils.Objects.GetValue,fp=Phaser.Utils.Objects.IsPlainObject;class mp extends(Xu(Nt)){constructor(t,e,i,s,r,n,a,o){fp(e)?(e=vp(o=e,"x",0),i=vp(o,"y",0),s=vp(o,"width",2),r=vp(o,"height",2),n=vp(o,"barColor",void 0),a=vp(o,"value",0)):fp(s)?(s=vp(o=s,"width",2),r=vp(o,"height",2),n=vp(o,"barColor",void 0),a=vp(o,"value",0)):fp(n)&&(n=vp(o=n,"barColor",void 0),a=vp(o,"value",0)),super(t,e,i,s,r,vp(o,"resolution",1)),this.type="rexLineProgressCanvas",this.trackPoints=[],this.barPoints=[],this.bootProgressBase(o),this.setTrackColor(vp(o,"trackColor",void 0)),this.setBarColor(n,vp(o,"barColor2",void 0),vp(o,"isHorizontalGradient",void 0)),this.setTrackStroke(vp(o,"trackStrokeThickness",2),vp(o,"trackStrokeColor",void 0)),this.setSkewX(vp(o,"skewX",0)),this.setRTL(vp(o,"rtl",!1)),this.setValue(a)}get trackColor(){return this._trackColor}set trackColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._trackColor!=t,this._trackColor=t}setTrackColor(t){return this.trackColor=t,this}get trackStrokeColor(){return this._trackStrokeColor}set trackStrokeColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._trackStrokeColor!=t,this._trackStrokeColor=t}get trackStrokeThickness(){return this._trackStrokeThickness}set trackStrokeThickness(t){this.dirty=this.dirty||this._trackStrokeThickness!=t,this._trackStrokeThickness=t}setTrackStroke(t,e){return this.trackStrokeThickness=t,this.trackStrokeColor=e,this}get barColor(){return this._barColor}set barColor(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._barColor!=t,this._barColor=t}get barColor2(){return this._barColor2}set barColor2(t){t=Jt(t,this.canvas,this.context),this.dirty=this.dirty||this._barColor2!=t,this._barColor2=t}get isHorizontalGradient(){return this._isHorizontalGradient}set isHorizontalGradient(t){this.dirty|=this._isHorizontalGradient!=t,this._isHorizontalGradient=t}setBarColor(t,e,i){return void 0===i&&(i=!0),this.barColor=t,this.barColor2=e,this.isHorizontalGradient=i,this}get skewX(){return this._skewX}set skewX(t){this.dirty=this.dirty||this._skewX!=t,this._skewX=t}setSkewX(t){return this.skewX=t,this}get rtl(){return this._rtl}set rtl(t){t=!!t,this.dirty=this.dirty||this._rtl!=t,this._rtl=t}setRTL(t){return void 0===t&&(t=!0),this.rtl=t,this}updateTexture(){return super.updateTexture((function(){this.clear(),pp.call(this)}),this),this}}t.register("circularProgressCanvas",(function(t,e,i,s,r,n,a){var o=new mp(this.scene,t,e,i,s,r,n,a);return this.scene.add.existing(o),o})),P(window,"RexPlugins.UI.LineProgressCanvas",mp),Phaser.Math.Wrap;const yp=Phaser.Math.Linear;var bp=function(){var t,e,i,s,r,n,a=this.getShape("triangle"),o=this.padding,h=this.width-o.right,l=0+o.left,d=this.height-o.bottom,c=0+o.top,u=(l+h)/2,p=(c+d)/2,g={0:{a:{x:l,y:c},b:{x:h,y:p},c:{x:l,y:d}},1:{a:{x:l,y:c},b:{x:u,y:d},c:{x:h,y:c}},2:{a:{x:h,y:c},b:{x:l,y:p},c:{x:h,y:d}},3:{a:{x:l,y:d},b:{x:u,y:c},c:{x:h,y:d}}};if(void 0===this.previousDirection){var v=g[this.direction],f=v.a,m=v.b,y=v.c;t=f.x,e=f.y,i=m.x,s=m.y,r=y.x,n=y.y}else{var b=g[this.previousDirection],x=g[this.direction],C=this.easeDirectionProgress;t=yp(b.a.x,x.a.x,C),e=yp(b.a.y,x.a.y,C),i=yp(b.b.x,x.b.x,C),s=yp(b.b.y,x.b.y,C),r=yp(b.c.x,x.c.x,C),n=yp(b.c.y,x.c.y,C)}a.startAt(t,e).lineTo(i,s).lineTo(r,n),this.arrowOnly?a.end():a.close()};const xp=(0,Phaser.Math.DegToRad)(120);var Cp=function(t){t=this.getShape("triangle");var e=this.width/2,i=this.height/2,s=Math.min(e,i)*this.radius,r=this.verticeRotation;t.startAt(e+s*Math.cos(r+xp),i+s*Math.sin(r+xp)).lineTo(e+s*Math.cos(r),i+s*Math.sin(r)).lineTo(e+s*Math.cos(r-xp),i+s*Math.sin(r-xp)),this.arrowOnly?t.end():t.close()},kp={buildShapes(){this.addShape((new Uc).setName("triangle"))},updateShapes(){var t=this.getShape("triangle");this.arrowOnly?t.fillStyle().lineStyle(this.lineWidth,this.strokeColor,this.strokeAlpha):t.fillStyle(this.fillColor,this.fillAlpha).lineStyle(this.lineWidth,this.strokeColor,this.strokeAlpha),0===this.shapeMode?bp.call(this):Cp.call(this)}},wp={setEaseDuration(t){return void 0===t&&(t=0),this.easeDuration=t,this},playEaseDirectionation(){return void 0===this.easeDirectionProgressTask&&(this.easeDirectionProgressTask=new tu(this,{eventEmitter:null})),this.easeDirectionProgressTask.restart({key:"easeDirectionProgress",from:0,to:1,duration:this.easeDuration}),this},stopEaseDirection(){return void 0===this.easeDirectionProgressTask||this.easeDirectionProgressTask.stop(),this}};const Sp=Phaser.Utils.Objects.GetValue,Pp=Phaser.Utils.Objects.IsPlainObject,Tp=Phaser.Math.DegToRad,Op=Phaser.Math.RadToDeg;class Mp extends pc{constructor(t,e,i,s,r,n,a){var o,h,l,d,c,u,p,g;if(Pp(e)){var v=e;e=v.x,i=v.y,s=v.width,r=v.height,n=v.color,a=v.alpha,o=v.strokeColor,h=v.strokeAlpha,l=v.strokeWidth,d=v.arrowOnly,c=v.direction,u=v.easeDuration,p=v.padding,g=v.radius}void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=1),void 0===r&&(r=s),void 0===d&&(d=!1),void 0===c&&(c=0),void 0===u&&(u=0),void 0===p&&(p=0),void 0===g&&(g=void 0),super(t,e,i,s,r),this.type="rexTriangle",this.setFillStyle(n,a),void 0!==o&&void 0===l&&(l=2),this.setStrokeStyle(l,o,h),this.setArrowOnly(d),this.setDirection(c,u),this.setPadding(p),this.setRadius(g),this.buildShapes()}get arrowOnly(){return this._arrowOnly}set arrowOnly(t){this.dirty=this.dirty||this._arrowOnly!=t,this._arrowOnly=t}setArrowOnly(t){return void 0===t&&(t=!0),this.arrowOnly=t,this}get direction(){return this._direction}set direction(t){t=_p(t),this._direction!==t&&(this.easeDuration>0&&void 0!==this._direction?this.previousDirection=this._direction:this.previousDirection=void 0,this._direction=t,this.verticeAngle=90*t,this.dirty=!0,void 0!==this.previousDirection?this.playEaseDirectionation():this.stopEaseDirection())}setDirection(t,e){return void 0!==e&&this.setEaseDuration(e),this.direction=t,this}toggleDirection(t){return this.setDirection(this.direction+2,t),this}get easeDirectionProgress(){return this._easeDirectionProgress}set easeDirectionProgress(t){this._easeDirectionProgress!==t&&(this._easeDirectionProgress=t,this.dirty=!0)}setPadding(t,e,i,s){if("object"==typeof t){var r=t,n=Sp(r,"x",null);null!==n?(t=n,i=n):(t=Sp(r,"left",0),i=Sp(r,"right",t));var a=Sp(r,"y",null);null!==a?(e=a,s=a):(e=Sp(r,"top",0),s=Sp(r,"bottom",e))}else void 0===t&&(t=0),void 0===e&&(e=t),void 0===i&&(i=t),void 0===s&&(s=e);return void 0===this.padding&&(this.padding={}),this.dirty=this.dirty||this.padding.left!=t||this.padding.top!=e||this.padding.right!=i||this.padding.bottom!=s,this.padding.left=t,this.padding.top=e,this.padding.right=i,this.padding.bottom=s,this.setRadius(),this}get radius(){return this._radius}set radius(t){this.dirty=this.dirty||this._radius!=t,this._radius=t}setRadius(t){return this.radius=t,this.shapeMode=null==t?0:1,this}get verticeRotation(){return this._verticeRotation}set verticeRotation(t){this.dirty=this.dirty||this._verticeRotation!=t,this._verticeRotation=t}setVerticeRotation(t){return this.verticeRotation=t,this}get verticeAngle(){return Op(this.verticeRotation)}set verticeAngle(t){this.verticeRotation=Tp(t)}setVerticeAngle(t){return this.verticeAngle=t,this}}const Ep={right:0,down:1,left:2,up:3};var _p=function(t){return"string"==typeof t&&(t=Ep[t]),t%=4};Object.assign(Mp.prototype,kp,wp),t.register("triangle",(function(t,e,i,s,r,n){var a=new Mp(this.scene,t,e,i,s,r,n);return this.scene.add.existing(a),a})),P(window,"RexPlugins.UI.Triangle",Mp),F();const Rp=Phaser.GameObjects.Zone,Lp=Phaser.Utils.Array.Add,Bp=Phaser.Utils.Array.Remove;let Ip=class extends Rp{constructor(t,e,i,s,r){void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=1),void 0===r&&(r=1),super(t,e,i,s,r),this.children=[]}destroy(t){if(this.scene&&!this.ignoreDestroy){if(t)for(var e,i=this.children.length-1;i>=0;i--)(e=this.children[i]).parentContainer||e.displayList||e.destroy(t);this.clear(!t),super.destroy(t)}}contains(t){return-1!==this.children.indexOf(t)}add(t){var e=this;return Lp(this.children,t,0,(function(t){t.once("destroy",e.onChildDestroy,e)}),this),this}remove(t,e){var i=this;return Bp(this.children,t,(function(t){t.off("destroy",i.onChildDestroy,i),e&&t.destroy()})),this}onChildDestroy(t,e){this.remove(t,!1)}clear(t){for(var e,i=0,s=this.children.length;iYp(t),resetChildState(t){return this.resetChildPositionState(t).resetChildVisibleState(t).resetChildAlphaState(t).resetChildActiveState(t),this},resetChildrenState(t){for(var e=0,i=t.length;eYp(t).x,getChildLocalY:t=>Yp(t).y};const ig=Phaser.Math.DegToRad;var sg={updateChildRotation(t){var e=Yp(t),i=e.parent;return e.syncRotation&&(t.rotation=i.rotation+e.rotation),this},syncRotation(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildRotation,this),this},resetChildRotationState(t){var e=Yp(t),i=e.parent;return e.rotation=t.rotation-i.rotation,this},setChildRotation(t,e){return t.rotation=e,this.resetChildRotationState(t),this},setChildAngle(t,e){return t.angle=e,this.resetChildRotationState(t),this},setChildLocalRotation(t,e){return Yp(t).rotation=e,this.updateChildRotation(t),this},setChildLocalAngle(t,e){return Yp(t).rotation=ig(e),this.updateChildRotation(t),this},resetLocalRotationState(){var t=Yp(this).parent;return t&&t.resetChildRotationState(this),this},getChildLocalRotation:t=>Yp(t).rotation},rg={updateChildScale(t){var e=Yp(t),i=e.parent;return e.syncScale&&(t.scaleX=i.scaleX*e.scaleX,t.scaleY=i.scaleY*e.scaleY),this},syncScale(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildScale,this),this},resetChildScaleState(t){var e=Yp(t),i=e.parent;return e.scaleX=tg(t.scaleX,i.scaleX),e.scaleY=tg(t.scaleY,i.scaleY),this},setChildScale(t,e,i){return void 0===i&&(i=e),t.scaleX=e,t.scaleY=i,this.resetChildScaleState(t),this},setChildLocalScale(t,e,i){void 0===i&&(i=e);var s=Yp(t);return s.scaleX=e,s.scaleY=i,this.updateChildScale(t),this},setChildDisplaySize(t,e,i){return t.setDisplaySize(e,i),this.resetChildScaleState(t),this},resetLocalScaleState(){var t=Yp(this).parent;return t&&t.resetChildScaleState(this),this},getChildLocalScaleX:t=>Yp(t).scaleX,getChildLocalScaleY:t=>Yp(t).scaleY},ng={updateChildVisible(t){var e=Yp(t),i=e.parent,s=!e.hasOwnProperty("maskVisible")||e.maskVisible,r=!i||i.visible;return t.visible=r&&e.visible&&s,this},syncVisible(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildVisible,this),this},resetChildVisibleState(t){var e=Yp(t);return e.hasOwnProperty("maskVisible")&&delete e.maskVisible,e.visible=t.visible,this},setChildVisible(t,e){return this.setChildLocalVisible(t,e),this},setChildLocalVisible(t,e){return void 0===e&&(e=!0),Yp(t).visible=e,this.updateChildVisible(t),this},setChildMaskVisible(t,e){return void 0===e&&(e=!0),Yp(t).maskVisible=e,this.updateChildVisible(t),this},resetLocalVisibleState(){var t=Yp(this).parent;return t&&t.resetChildVisibleState(this),this},getChildLocalVisible:t=>Yp(t).visible},ag={updateChildAlpha(t){var e=Yp(t),i=e.parent;return e.syncAlpha&&(t.alpha=i.alpha*e.alpha),this},syncAlpha(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildAlpha,this),this},resetChildAlphaState(t){var e=Yp(t),i=e.parent;return e.alpha=tg(t.alpha,i.alpha),this},setChildAlpha(t,e){return t.alpha=e,this.resetChildAlphaState(t),this},setChildLocalAlpha(t,e){return Yp(t).alpha=e,this.updateChildAlpha(t),this},resetLocalAlphaState(){var t=Yp(this).parent;return t&&t.resetChildAlphaState(this),this},getChildLocalAlpha:t=>Yp(t).alpha},og={updateChildActive(t){var e=Yp(t),i=e.parent;return t.active=i.active&&e.active,this},syncActive(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildActive,this),this},resetChildActiveState(t){return Yp(t).active=t.active,this},setChildActive(t,e){return t.active=e,this.resetChildActiveState(t),this},setChildLocalActive(t,e){return void 0===e&&(e=!0),Yp(t).active=e,this.updateChildActive(t),this},resetLocalActiveState(){var t=Yp(this).parent;return t&&t.resetChildActiveState(this),this},getChildLocalActive:t=>Yp(t).active},hg={updateChildScrollFactor(t){var e=Yp(t),i=e.parent;return e.syncScrollFactor&&(t.scrollFactorX=i.scrollFactorX,t.scrollFactorY=i.scrollFactorY),this},syncScrollFactor(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildScrollFactor,this),this}},lg={updateCameraFilter(t){var e=Yp(t),i=e.parent;return e.syncCameraFilter&&(t.cameraFilter=i.cameraFilter),this},syncCameraFilter(){return this.syncChildrenEnable&&this.children.forEach(this.updateCameraFilter,this),this}},dg={updateChildMask(t){return null==this.mask||(this.mask.hasOwnProperty("geometryMask")?this.mask.geometryMask:this.mask.bitmapMask)!==t&&(t.mask=this.mask),this},syncMask(){return this.syncChildrenEnable&&this.children.forEach(this.updateChildMask,this),this},setMask(t){return this.mask=t,this},clearMask(t){void 0===t&&(t=!1);var e=this;return this._mask=null,this.setChildMaskVisible(this),this.children.forEach((function(t){t.clearMask&&t.clearMask(!1),t.hasOwnProperty("isRexContainerLite")||e.setChildMaskVisible(t)})),t&&this.mask&&this.mask.destroy(),this}},cg=function(t){return t.filter((function(t){return!!t.displayList||!!t.parentContainer||void 0}))},ug={setDepth(t,e){if(this.depth=t,!e&&this.children)for(var i=this.getAllChildren(),s=0,r=i.length;s=0;r--){var n=e[r];s!==n&&(n!==this&&s.displayList!==n.displayList||(s.displayList.moveBelow(n,s),s=n))}return this}},pg=function(t,e){if(!e(t)&&t.isRexContainerLite)for(var i=t.children,s=0,r=i.length;s0;){var s=i.shift();!e(s)&&s.isRexContainerLite&&i.push(...s.children)}};const vg=Phaser.Utils.Array;var fg={getChildren(t){if(t)for(var e=0,i=this.children.length;e=0;e--)this.remove(this.backgroundChildren[e],t);return this}},Ov=function(t,e){if("string"==typeof t)this.childrenMap[t]=e;else{var i=t;for(t in i)this.childrenMap[t]=i[t]}return this};const Mv=/(\S+)\[(\d+)\]/i;var Ev={getInnerPadding(t){return Ps(this.space,t)},setInnerPadding(t,e){return Ts(this.space,t,e),this},getOuterPadding(t){return Ps(this.getSizerConfig(this).padding,t)},setOuterPadding(t,e){return Ts(this.getSizerConfig(this).padding,t,e),this},getChildOuterPadding(t,e){return"string"==typeof t&&(t=this.getElement(t)),Ps(this.getSizerConfig(t).padding,e)},setChildOuterPadding(t,e,i){return"string"==typeof t&&(t=this.getElement(t)),Ts(this.getSizerConfig(t).padding,e,i),this}},_v=function(t){var e=this.childrenWidth;if(void 0!==e){var i=void 0!==this.minWidth?this.minWidth*this.scaleX:0;return void 0===t?(t=Math.max(i,e),this.layoutWarnEnable&&i>0&&e>i&&console.warn(`Layout width warn: ${this.constructor.name}'s minWidth (${i}) < childrenWidth (${e})`)):this.layoutWarnEnable&&(i>t||e>t)&&console.warn(`Layout width warn: ${this.constructor.name}'s minWidth (${i}) or childrenWidth (${e} > targetWidth ${t})`),t}},Rv=function(){var t;for(var e in this.sizerChildren)if(!(!(t=this.sizerChildren[e])||t.isRexSizer&&t.ignoreLayout)&&t.runWidthWrap&&(!t.hasWidthWrap||t.hasWidthWrap()))return!0;return!1},Lv=function(t){var e,i,s;for(var r in this.sizerChildren)!(e=this.sizerChildren[r])||e.isRexSizer&&e.ignoreLayout||!e.runWidthWrap||(i=this.getExpandedChildWidth(e,t),e.isRexSizer?void 0===(s=e.resolveWidth(i))&&(s=i):s=i,e.runWidthWrap(s));return this},Bv=function(t){var e=this.childrenHeight;if(void 0!==e){var i=void 0!==this.minHeight?this.minHeight*this.scaleY:0;return void 0===t?(t=Math.max(i,e),this.layoutWarnEnable&&i>0&&e>i&&console.warn(`Layout height warn: ${this.constructor.name}'s minHeight (${i}) < childrenHeight (${e})`)):this.layoutWarnEnable&&(i>t||e>t)&&console.warn(`Layout height warn: ${this.constructor.name}'s minHeight (${i}) or childrenHeight (${e}) > targetHeight (${t})`),t}},Iv=function(){var t;for(var e in this.sizerChildren)if(!(!(t=this.sizerChildren[e])||t.isRexSizer&&t.ignoreLayout)&&t.runHeightWrap&&(!t.hasHeightWrap||t.hasHeightWrap()))return!0;return!1},Dv=function(t){var e,i,s;for(var r in this.sizerChildren)!(e=this.sizerChildren[r])||e.isRexSizer&&e.ignoreLayout||!e.runHeightWrap||(i=this.getExpandedChildHeight(e,t),e.isRexSizer?void 0===(s=e.resolveHeight(i))&&(s=i):s=i,e.runHeightWrap(s));return this},jv={getShownChildren(t){void 0===t&&(t=[]);for(var e,i=this.children,s=0,r=i.length;s0;){var i=e.shift();i.rexSizer&&i.rexSizer.hidden||(i!==this&&t.push(i),i.isRexContainerLite&&e.push(...i.children))}return t}},Av=function(){this._childrenWidth=void 0,this._childrenHeight=void 0;for(var t,e=this.getChildrenSizers(),i=0,s=e.length;i0){var e=t.runTransitionInCallback();t.delayCall(e,this.next,this)}else this.next()}exit_TRANS_OPNE(){this.parent.removeDelayCall()}next_OPEN(){return"TRANS_CLOSE"}enter_OPEN(){this.parent.onOpen()}exit_OPEN(){this.parent.removeDelayCall()}next_TRANS_CLOSE(){return"CLOSE"}enter_TRANS_CLOSE(){var t=this.parent;if(t.transitOutTime>0){var e=t.runTransitionOutCallback();t.delayCall(e,this.next,this)}else this.next()}exit_TRANS_CLOSE(){this.parent.removeDelayCall()}next_CLOSE(){return"TRANS_OPNE"}enter_CLOSE(){this.parent.onClose()}exit_CLOSE(){}canOpen(){return"IDLE"===this.state||"CLOSE"===this.state}canClose(){return"IDLE"===this.state||"OPEN"===this.state}};var Jf={delayCall(t,e,i){return this.delayCallTimer=function(t,e,i,s,r){var n=Ea(t);return n.time.delayedCall(e,(function(){n.game.events.once("poststep",(function(){i.call(s,r)}))}))}(this,t,e,i),this},removeDelayCall(){return this.delayCallTimer&&(this.delayCallTimer.remove(!1),this.delayCallTimer=void 0),this}},qf={setTransitInTime(t){return this.transitInTime=t,this},setTransitOutTime(t){return this.transitOutTime=t,this},setTransitInCallback(t){return t||(t=h),this.transitInCallback=t,this},setTransitOutCallback(t){return t||(t=h),this.transitOutCallback=t,this}},Zf={runTransitionInCallback(){return this.transitInCallback(this.parent,this.transitInTime),this.transitInTime},onOpen(){},requestOpen(t,e){if(!this._state.canOpen())return this;this.openEventData=arguments.length>0?t:this.parent;var i=this.transitInTime;return void 0!==e&&(this.transitInTime=e),this._state.goto("TRANS_OPNE"),this.transitInTime=i,this}},Qf={runTransitionOutCallback(){return this.transitOutCallback(this.parent,this.transitOutTime),this.transitOutTime},onClose(){this.oneShotMode&&this.parent.destroy()},requestClose(t,e){if(!this._state.canClose)return this;this.closeEventData=arguments.length>0?t:this.parent;var i=this.transitOutTime;return void 0!==e&&(this.transitOutTime=e),this._state.goto("TRANS_CLOSE"),this.transitOutTime=i,this}},tm={};Object.assign(tm,Jf,qf,Zf,Qf);const em=Phaser.Utils.Objects.GetValue;class im extends Ra{constructor(t,e){super(t,e),this.setTransitInTime(em(e,"duration.in",200)),this.setTransitOutTime(em(e,"duration.out",200)),this.setTransitInCallback(em(e,"transitIn")),this.setTransitOutCallback(em(e,"transitOut")),this.oneShotMode=em(e,"destroy",!1),this.delayCallTimer=void 0,this._state=new Kf(this,{eventEmitter:!1,initState:em(e,"initState","IDLE")}),this.openEventData=void 0,this.closeEventData=void 0}get state(){return this._state.state}shutdown(t){this.isShutdown||(this.transitInCallback=void 0,this.transitOutCallback=void 0,this.openEventData=void 0,this.closeEventData=void 0,this.removeDelayCall(),super.shutdown(t))}}Object.assign(im.prototype,tm);const sm=Phaser.GameObjects.Rectangle;class rm extends sm{constructor(t,e,i){super(t,0,0,2,2,e,1),this.fullWindow=new Md(this),this.setAlpha(i)}get tint(){return this.fillColor}set tint(t){this.setFillStyle(t,this.fillAlpha)}}const nm=Phaser.Utils.Objects.GetValue;class am extends Ra{constructor(t,e){super(t,{eventEmitter:!1}),this.resetFromJSON(e),this.boot()}resetFromJSON(t){return this.setHitAreaMode(nm(t,"hitAreaMode",0)),this.setEnable(nm(t,"enable",!0)),this.setStopMode(nm(t,"stopAllLevels",!0)),this}boot(){this.parent.on("pointerdown",(function(t,e,i,s){this.stopAllLevels&&s.stopPropagation()}),this).on("pointerup",(function(t,e,i,s){this.stopAllLevels&&s.stopPropagation()}),this).on("pointermove",(function(t,e,i,s){this.stopAllLevels&&s.stopPropagation()}),this).on("pointerover",(function(t,e,i,s){this.stopAllLevels&&s.stopPropagation()}),this).on("pointerout",(function(t,e){this.stopAllLevels&&e.stopPropagation()}),this)}setHitAreaMode(t){"string"==typeof t&&(t=om[t]);var e=this.parent;return e.input&&e.removeInteractive(),0===t?e.setInteractive():e.setInteractive({hitArea:{},hitAreaCallback:function(){return!0}}),this}setEnable(t){return void 0===t&&(t=!0),t?this.parent.setInteractive():this.parent.disableInteractive(),this.enable=t,this}setStopMode(t){return void 0===t&&(t=!0),this.stopAllLevels=t,this}toggleEnable(){return this.setEnable(!this.enable),this}}var om={default:0,fullWindow:1};const hm=Phaser.Utils.Objects.GetValue;class lm extends rm{constructor(t,e){super(t,hm(e,"color",0),hm(e,"alpha",.8)),this.touchEventStop=new am(this,{hitAreaMode:1})}}var dm={popUp(t,e){void 0!==t._modalScaleSave?(t.scaleX=t._modalScaleSave,t.scaleY=t._modalScaleSave):t._modalScaleSave=t.scaleX,Zv(t,e)},scaleDown(t,e){Qv(t,e,void 0,void 0,!1)},fadeIn(t,e){void 0!==t._modalAlphaSave?t.alpha=t._modalAlphaSave:t._modalAlphaSave=t.alpha,df(t,e)},fadeOut(t,e){cf(t,e,!1)}},cm=function(t,e){void 0!==t._modalAlphaSave?t.alpha=t._modalAlphaSave:t._modalAlphaSave=t.alpha,df(t,e,t.alpha)},um=function(t,e){cf(t,e,!1)},pm=function(t,e,i,s,r){return!(!t||s&&!s(t,e,i)||!Wn(t,!0).contains(e,i)||r&&!r(t,e,i))};const gm=Phaser.Utils.Objects.GetValue;let vm=class extends im{constructor(t,e){void 0===e&&(e={}),null==e.transitIn&&(e.transitIn=fm.popUp),null==e.transitOut&&(e.transitOut=fm.scaleDown),e.destroy=gm(e,"destroy",!0),super(t,e);var i=gm(e,"cover");this.cover=!1!==i?function(t,e){var i=t.scene,s=new lm(i,e);return i.add.existing(s),t.isRexContainerLite?(t.pin(s,{syncPosition:!1,syncRotation:!1,syncScale:!1,syncAlpha:!1,syncScrollFactor:!1}),t.moveDepthBelow(s)):i.children.moveBelow(s,t),s}(t,i):void 0,this.cover&&(this.setCoverTransitInCallback(gm(i,"transitIn",cm)),this.setCoverTransitOutCallback(gm(i,"transitOut",um)));var s=gm(e,"touchOutsideClose",!1),r=gm(e,"duration.hold",-1),n=gm(e,"timeOutClose",r>=0),a=gm(e,"anyTouchClose",!1);gm(e,"manualClose",!1)&&(s=!1,a=!1,n=!1),a&&(s=!1),n?this.setDisplayTime(r):this.setDisplayTime(-1),a?this.once("open",this.anyTouchClose,this):s&&this.once("open",this.touchOutsideClose,this),gm(e,"openOnStart",!0)&&this.delayCall(0,this.requestOpen,this)}shutdown(t){this.isShutdown||(this.cover||this.scene.input.off("pointerup",this.touchCloseCallback,this),this.cover&&!t&&(this.cover.destroy(),this.cover=void 0),super.shutdown(t))}touchOutsideClose(){return this.cover?this.cover.on("pointerup",this.touchCloseCallback,this):this.scene.input.on("pointerup",this.touchCloseCallback,this),this.clickOutsideTest=!0,this}anyTouchClose(){return this.cover?this.cover.once("pointerup",this.touchCloseCallback,this):this.scene.input.once("pointerup",this.touchCloseCallback,this),this}touchCloseCallback(t){this.clickOutsideTest&&pm(this.parent,t.worldX,t.worldY)||this.requestClose()}runTransitionInCallback(){var t=super.runTransitionInCallback(),e=this.cover;return e&&this.coverTransitInCallback&&this.coverTransitInCallback(e,t),t}runTransitionOutCallback(){var t=super.runTransitionOutCallback(),e=this.cover;return e&&this.coverTransitOutCallback&&this.coverTransitOutCallback(e,t),t}onOpen(){var t=this.displayTime;t>=0&&this.delayCall(t,this.requestClose,this),this.emit("open",this.parent,this),super.onOpen()}onClose(){this.emit("close",this.closeEventData),super.onClose()}setDisplayTime(t){return this.displayTime=t,this}setTransitInCallback(t){switch("string"==typeof t&&(t=fm[t]),t){case fm.popUp:t=dm.popUp;break;case fm.fadeIn:t=dm.fadeIn}return super.setTransitInCallback(t),this}setTransitOutCallback(t){switch("string"==typeof t&&(t=fm[t]),t){case fm.scaleDown:t=dm.scaleDown;break;case fm.fadeOut:t=dm.fadeOut}return super.setTransitOutCallback(t),this}setCoverTransitInCallback(t){return this.coverTransitInCallback=t,this}setCoverTransitOutCallback(t){return this.coverTransitOutCallback=t,this}};const fm={popUp:0,fadeIn:1,scaleDown:0,fadeOut:1};var mm=function(t,e){var i=new vm(t,e);return i.on("open",(function(){t.emit("modal.open",i)})),i.on("close",(function(e){t.emit("modal.close",e,i)})),t.on("modal.requestClose",i.requestClose,i),i},ym=function(t,e){t.emit("modal.requestClose",e)},bm=function(t){return t&&"function"==typeof t},xm={modal(t,e){return bm(t)&&(e=t,t=void 0),void 0===this._modalBehavior&&(this.onCreateModalBehavior&&this.onCreateModalBehavior(this,t),this._modalBehavior=mm(this,t)),e&&this._modalBehavior.once("close",e),this._modalBehavior.requestOpen(),this},modalPromise(t){var e=this;return new Promise((function(i,s){e.modal(t,i)}))},modalClose(t){return ym(this,t),this}},Cm=function(t,e,i,s,r){bm(e)&&(r=s,s=i,i=e,e=this);var n=this.scene.events;return this.bindEvent(e,n,t,i,s,r),this},km={bindEvent(t,e,i,s,r,n){return"string"==typeof e&&(n=r,r=s,s=i,i=e,e=t,t=this),function(t,e,i,s,r,n){void 0===n&&(n=!1),e[n?"once":"on"](i,s,r),t.once("destroy",(function(){e.off(i,s,r)}))}(t,e,i,s,r,n),this},bindScenePreupdateEvent(t,e,i,s){return Cm.call(this,"preupdate",t,e,i,s),this},bindSceneUpdateEvent(t,e,i,s){return Cm.call(this,"update",t,e,i,s),this},bindScenePostupdateEvent(t,e,i,s){return Cm.call(this,"postupdate",t,e,i,s),this},bindSceneRenderEvent(t,e,i,s){return Cm.call(this,"render",t,e,i,s),this},bindScenePauseEvent(t,e,i,s){return Cm.call(this,"pause",t,e,i,s),this},bindSceneResumeEvent(t,e,i,s){return Cm.call(this,"resume",t,e,i,s),this},bindSceneSleepEvent(t,e,i,s){return Cm.call(this,"sleep",t,e,i,s),this},bindSceneWakeEvent(t,e,i,s){return Cm.call(this,"wake",t,e,i,s),this},bindSceneShutdownEvent(t,e,i,s){return Cm.call(this,"shutdown",t,e,i,s),this}},wm=function(t,e,i){var s=t.camera;return s?(void 0===i?i={}:!0===i&&(i=Sm),s===e?(i.x=t.worldX,i.y=t.worldY):s.getWorldPoint(t.x,t.y,i),i):null},Sm={},Pm=function(t,e,i,s){var r,n=t.scene.sys.cameras.main,a=0===t.scrollFactorX&&0===t.scrollFactorY;if(e)return a?pm(t,e.x,e.y,i,s):!!(r=wm(e,n,!0))&&pm(t,r.x,r.y,i,s);for(var o=t.scene.input.manager,h=o.pointersTotal,l=o.pointers,d=0;d=this.dragThreshold||this.isPointerInside(t))&&this.cancel()}click(t,e){if(!this.enable)return this;if(void 0===t)return this.emit("clickoutside",this,this.parent,e),this;this.pointer=void 0;var i=this.lastClickTime;return void 0!==i&&t-i<=this.clickInterval||(this.lastClickTime=t,this.emit("clickoutside",this,this.parent,e)),this}cancel(){return this.pointer=void 0,this}}const zm={press:0,pointerdown:0,release:1,pointerup:1};var Fm={onClickOutside(t,e,i,s){return t?("function"==typeof t&&(s=i,i=e,e=t,t=this),void 0===t._clickOutside&&(t._clickOutside=new Am(t,s)),t._clickOutside.on("clickoutside",e,i),this):this},offClickOutside(t,e,i){return"function"==typeof t&&(i=e,e=t,t=this),void 0===t._clickOutside||t._clickOutside.off("clickoutside",e,i),this},enableClickOutside(t,e){return"boolean"==typeof t&&(e=t,t=void 0),void 0===t&&(t=this),void 0===t._clickOutside||t._clickOutside.setEnable(e),this},disableClickOutside(t){return void 0===t&&(t=this),void 0===t._clickOutside||t._clickOutside.setEnable(!1),this}};class Ym extends $f{constructor(){super({eventEmitter:!1}),this.goto("IDLE")}setCooldownTime(t){return this.cooldownTime=t,this.cooldownMode=void 0!==t,this}request(){return this.runMethod("request")}update_IDLE(){this.compensationTime=0}request_IDLE(){return this.next(),!0}next_IDLE(){if(this.cooldownMode)return"COOLDOWN"}enter_COOLDOWN(){this.remainderTime=this.cooldownTime+this.compensationTime}update_COOLDOWN(t,e){this.remainderTime-=e,this.remainderTime<0&&(this.compensationTime=this.cooldownTime>e?-this.remainderTime:0,this.goto("IDLE"))}request_COOLDOWN(){return!1}}const Xm=Phaser.Utils.Objects.GetValue;class Wm extends Ra{constructor(t,e){super(t,e),this._enable=void 0,this.cooldown=new Ym,this.parent.setInteractive(Xm(e,"inputConfig",void 0)),this.resetFromJSON(e),this.boot()}resetFromJSON(t){return this.pointer=void 0,this.prevIsInTouch=!1,this.isInTouching=!1,this.setEnable(Xm(t,"enable",!0)),this.setCooldown(Xm(t,"cooldown",void 0)),this}boot(){var t=this.parent;t.on("pointerdown",this.onPointIn,this),t.on("pointerover",this.onPointIn,this),t.on("pointerup",this.onPointOut,this),t.on("pointerout",this.onPointOut,this),this.scene.sys.events.on("preupdate",this.preupdate,this)}shutdown(t){this.isShutdown||(this.scene.sys.events.off("preupdate",this.preupdate,this),this.pointer=void 0,super.shutdown(t))}get enable(){return this._enable}set enable(t){if(this._enable!==t)return t||(this.prevIsInTouch=!1,this.isInTouching=!1,this.pointer=void 0),this._enable=t,this}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}get cooldownTime(){return this.cooldown.cooldownTime}set cooldownTime(t){this.cooldown.setCooldownTime(t)}setCooldown(t){return this.cooldownTime=t,this}toggleEnable(){return this.setEnable(!this.enable),this}onPointIn(t,e,i){this.enable&&t.isDown&&void 0===this.pointer&&(this.pointer=t,this.isInTouching=!0)}onPointOut(t){this.enable&&this.pointer===t&&(this.pointer=void 0,this.isInTouching=!1)}preupdate(t,e){this.cooldown.update(t,e),!this.prevIsInTouch&&this.isInTouching&&this.emit("touchstart",this,this.parent),this.isInTouching&&this.cooldown.request()&&this.emit("intouch",this,this.parent,this.pointer),this.prevIsInTouch&&!this.isInTouching&&this.emit("touchend",this,this.parent),this.prevIsInTouch=this.isInTouching}}var Vm={isPointerInBounds(t){return void 0===t?t=this:"string"==typeof t&&(t=this.getElement(t)),!!t&&Pm(t)},onTouching(t,e,i,s){return t?("function"==typeof t&&(s=i,i=e,e=t,t=this),void 0===t._inTouching&&(t._inTouching=new Wm(t,s)),t._inTouching.on("intouch",e,i),this):this},offTouching(t,e,i){return"function"==typeof t&&(i=e,e=t,t=this),void 0===t._inTouching||t._inTouching.off("intouch",e,i),this},onTouchingEnd(t,e,i,s){return t?("function"==typeof t&&(s=i,i=e,e=t,t=this),void 0===t._inTouching&&(t._inTouching=new Wm(t,s)),t._inTouching.on("touchend",e,i),this):this},offTouchingEnd(t,e,i){return"function"==typeof t&&(i=e,e=t,t=this),void 0===t._inTouching||t._inTouching.off("touchend",e,i),this},enableTouching(t,e){return"boolean"==typeof t&&(e=t,t=void 0),void 0===t&&(t=this),void 0===t._inTouching||t._inTouching.setEnable(e),this},disableTouching(t){return void 0===t&&(t=this),void 0===t._inTouching||t._inTouching.setEnable(!1),this}},Gm={onOver(t,e,i){return t?("function"==typeof t&&(i=e,e=t,t=this),t.setInteractive().on("pointerover",e,i),this):this},onOut(t,e,i){return t?("function"==typeof t&&(i=e,e=t,t=this),t.setInteractive().on("pointerout",e,i),this):this}},Hm=function(t,e,i){for(var s,r=0,n=t.length;r0),this.onDragStart())}onPointerUp(t){this.enable&&(!this.bounds||this.bounds.contains(t.x,t.y))&&this.pointer===t&&(this.pointer=void 0,this.pointerCamera=void 0,this.movedState=!1,this.tracerState=oy,this.onDragEnd())}onPointerMove(t){if(this.enable&&t.isDown){var e=!this.bounds||this.bounds.contains(t.x,t.y),i=this.pointer===t;!i&&e||(i&&!e?this.onPointerUp(t):(this.movedState||(this.movedState=t.x!==t.downX||t.y!==t.downY),this.movedState&&this.onDrag()))}}dragCancel(){return this.tracerState===hy&&this.onDragEnd(),this.pointer=void 0,this.tracerState=oy,this}onDragStart(){this.emit("dragstart",this)}onDragEnd(){this.emit("dragend",this)}onDrag(){this.emit("drag",this)}preUpdate(t,e){}postUpdate(t,e){}startTicking(){super.startTicking(),this.scene.sys.events.on("preupdate",this.preUpdate,this),this.scene.sys.events.on("postupdate",this.postUpdate,this)}stopTicking(){super.stopTicking(),this.scene&&(this.scene.sys.events.off("preupdate",this.preUpdate,this),this.scene.sys.events.off("postupdate",this.postUpdate,this))}setRecongizedStateObject(t){return this.recongizedState=t,this}get state(){return this.recongizedState.state}set state(t){this.recongizedState.state=t}cancel(){return this.state=ly,this}isPointerInGameObject(t,e,i){var s=this.lastPointer;return!!s&&Pm(t,s,e,i)}}const oy=0,hy=1,ly="IDLE",dy=Phaser.Utils.Objects.GetValue,cy=Phaser.Math.Distance.Between;class uy extends ay{constructor(t,e){super(t,e);var i=this,s={states:{IDLE:{enter:function(){i.stop(),i.tapsCount=0,i.x=0,i.y=0,i.worldX=0,i.worldY=0,i.lastPointer=void 0},exit:function(){var t=i.lastPointer;i.x=t.x,i.y=t.y,i.worldX=t.worldX,i.worldY=t.worldY}},BEGIN:{enter:function(){i.start(),i.tapsCount=0,i.emit("tappingstart",i,i.gameObject,i.lastPointer)}},RECOGNIZED:{enter:function(){i.start(),i.emit("tap",i,i.gameObject,i.lastPointer),i.emit(`${i.tapsCount}tap`,i,i.gameObject,i.lastPointer)}}},init:function(){this.state=py},eventEmitter:!1};this.setRecongizedStateObject(new $f(s))}resetFromJSON(t){super.resetFromJSON(t),this.setHoldTime(dy(t,"time",250)),this.setTapInterval(dy(t,"tapInterval",200)),this.setDragThreshold(dy(t,"threshold",9)),this.setTapOffset(dy(t,"tapOffset",10));var e=dy(t,"taps",void 0);return void 0!==e?this.setTaps(e):(this.setMaxTaps(dy(t,"maxTaps",void 0)),this.setMinTaps(dy(t,"minTaps",void 0))),this}onDragStart(){switch(this.state){case py:this.state=gy;break;case gy:var t=this.lastPointer;cy(t.upX,t.upY,t.x,t.y)>this.tapOffset&&(this.state=vy,this.state=gy);break;case vy:this.state=gy}}onDragEnd(){this.state===gy&&(this.tapsCount++,this.emit("tapping",this,this.gameObject,this.lastPointer),void 0!==this.maxTaps&&this.tapsCount===this.maxTaps&&(this.state=vy))}onDrag(){this.state!==py&&this.pointer.getDistance()>this.dragThreshold&&(this.state=py)}preUpdate(t,e){if(this.isRunning&&this.enable&&this.state===gy){var i=this.lastPointer;i.isDown?t-i.downTime>this.holdTime&&(this.state=py):t-i.upTime>this.tapInterval&&(void 0===this.minTaps||this.tapsCount>=this.minTaps?this.state=vy:this.state=py)}}postUpdate(t,e){this.isRunning&&this.enable&&this.state===vy&&(this.state=py)}get isTapped(){return this.state===vy}setHoldTime(t){return this.holdTime=t,this}setTapInterval(t){return this.tapInterval=t,this}setDragThreshold(t){return this.dragThreshold=t,this}setTapOffset(t){return this.tapOffset=t,this}setMaxTaps(t){return this.maxTaps=t,this}setMinTaps(t){return this.minTaps=t,this}setTaps(t,e){return void 0===e&&(e=t),this.setMinTaps(t).setMaxTaps(e),this}}const py="IDLE",gy="BEGIN",vy="RECOGNIZED",fy=Phaser.Utils.Objects.GetValue;class my extends ay{constructor(t,e){super(t,e);var i=this,s={states:{IDLE:{enter:function(){i.x=0,i.y=0,i.worldX=0,i.worldY=0,i.lastPointer=void 0},exit:function(){var t=i.lastPointer;i.x=t.x,i.y=t.y,i.worldX=t.worldX,i.worldY=t.worldY}},BEGIN:{enter:function(){i.start()},exit:function(){i.stop()}},RECOGNIZED:{enter:function(){i.emit("pressstart",i,i.gameObject,i.lastPointer)},exit:function(){i.emit("pressend",i,i.gameObject,i.lastPointer)}}},init:function(){this.state=yy},eventEmitter:!1};this.setRecongizedStateObject(new $f(s))}resetFromJSON(t){return super.resetFromJSON(t),this.setDragThreshold(fy(t,"threshold",9)),this.setHoldTime(fy(t,"time",251)),this}onDragStart(){this.state=by,0===this.holdTime&&(this.state=xy)}onDragEnd(){this.state=yy}onDrag(){this.state!==yy&&this.pointer.getDistance()>this.dragThreshold&&(this.state=yy)}preUpdate(t,e){this.isRunning&&this.enable&&this.state===by&&t-this.pointer.downTime>=this.holdTime&&(this.state=xy)}get isPressed(){return this.state===xy}setHoldTime(t){return this.holdTime=t,this}setDragThreshold(t){return this.dragThreshold=t,this}}const yy="IDLE",by="BEGIN",xy="RECOGNIZED",Cy=Phaser.Utils.Objects.GetValue;class ky extends ay{constructor(t,e){super(t,e);var i=this,s={states:{IDLE:{},BEGIN:{enter:function(){var t=i.pointer;i.startX=t.x,i.startY=t.y,i.startWorldX=t.worldX,i.startWorldY=t.worldY}},RECOGNIZED:{enter:function(){i.emit("panstart",i,i.gameObject,i.lastPointer)},exit:function(){var t=i.lastPointer;i.endX=t.x,i.endY=t.y;var e=wm(t,i.pointerCamera,!0);i.endWorldX=e.x,i.endWorldY=e.y,i.emit("panend",i,i.gameObject,i.lastPointer)}}},init:function(){this.state=wy},eventEmitter:!1};this.setRecongizedStateObject(new $f(s))}resetFromJSON(t){return super.resetFromJSON(t),this.setDragThreshold(Cy(t,"threshold",10)),this}onDragStart(){this.state=Sy,0===this.dragThreshold&&(this.state=Py)}onDragEnd(){this.state=wy}onDrag(){switch(this.state){case Sy:if(this.pointer.getDistance()>=this.dragThreshold){this.state=Py,this.dx=0,this.dy=0,this.dWorldX=0,this.dWorldY=0;var t=this.pointer;this.x=t.x,this.y=t.y,this.worldX=t.worldX,this.worldY=t.worldY}break;case Py:var e=this.pointerCamera,i=this.pointer.position,s=this.pointer.prevPosition;this.dx=i.x-s.x,this.dy=i.y-s.y,this.dWorldX=this.dx/e.zoom,this.dWorldY=this.dy/e.zoom,t=this.pointer,this.x=t.x,this.y=t.y;var r=wm(t,e,!0);this.worldX=r.x,this.worldY=r.y,this.emit("pan",this,this.gameObject,this.lastPointer)}}get isPanned(){return this.state===Py}setDragThreshold(t){return this.dragThreshold=t,this}}const wy="IDLE",Sy="BEGIN",Py="RECOGNIZED",Ty=Phaser.Math.Distance.Between,Oy=Phaser.Math.Angle.Between;var My={getDt:function(){return rc(this.scene)},getVelocity:function(){var t=this.pointer.position,e=this.pointer.prevPosition;return Ty(e.x,e.y,t.x,t.y)/(.001*this.getDt())},getVelocityX:function(){var t=this.pointer.position,e=this.pointer.prevPosition;return Math.abs(t.x-e.x)/(.001*this.getDt())},getVelocityY:function(){var t=this.pointer.position,e=this.pointer.prevPosition;return Math.abs(t.y-e.y)/(.001*this.getDt())},getVelocityAngle:function(){var t=this.pointer.position,e=this.pointer.prevPosition;return Oy(e.x,e.y,t.x,t.y)}},Ey={"up&down":0,"left&right":1,"4dir":2,"8dir":3},_y={};const Ry=Phaser.Utils.Objects.GetValue,Ly=Phaser.Math.RadToDeg;class By extends ay{constructor(t,e){super(t,e);var i=this,s={states:{IDLE:{enter:function(){i.x=0,i.y=0,i.worldX=0,i.worldY=0},exit:function(){var t=i.lastPointer;i.x=t.x,i.y=t.y,i.worldX=t.worldX,i.worldY=t.worldY}},BEGIN:{enter:function(){i.validDrag=!1}},RECOGNIZED:{enter:function(){i.start(),i.updateDirectionStates(),i.emit("swipe",i,i.gameObject,i.lastPointer)},exit:function(){i.stop(),i.clearDirectionStates()}}},init:function(){this.state=Iy},eventEmitter:!1};this.setRecongizedStateObject(new $f(s)),this.clearDirectionStates()}resetFromJSON(t){return super.resetFromJSON(t),this.setDragThreshold(Ry(t,"threshold",10)),this.setVelocityThreshold(Ry(t,"velocityThreshold",1e3)),this.setDirectionMode(Ry(t,"dir","8dir")),this}onDragStart(){this.state=Dy}onDragEnd(){this.state=Iy}onDrag(){this.state===Dy&&(this.validDrag||(this.validDrag=0===this.dragThreshold||this.pointer.getDistance()>=this.dragThreshold),this.validDrag&&this.dragVelocity>this.velocityThreshold&&(this.state=jy))}postUpdate(t,e){this.isRunning&&this.enable&&this.state===jy&&(this.state=Iy)}get isSwiped(){return this.state===jy}get dragVelocity(){var t;switch(this.dirMode){case 0:t=this.getVelocityY();break;case 1:t=this.getVelocityX();break;default:t=this.getVelocity()}return t}setDragThreshold(t){return this.dragThreshold=t,this}setVelocityThreshold(t){return this.velocityThreshold=t,this}setDirectionMode(t){return"string"==typeof t&&(t=Ey[t]),this.dirMode=t,this}updateDirectionStates(){return function(t,e,i){switch(void 0===i?i={}:!0===i&&(i=_y),i.left=!1,i.right=!1,i.up=!1,i.down=!1,t=(t+360)%360,e){case 0:t<180?i.down=!0:i.up=!0;break;case 1:t>90&&t<=270?i.left=!0:i.right=!0;break;case 2:t>45&&t<=135?i.down=!0:t>135&&t<=225?i.left=!0:t>225&&t<=315?i.up=!0:i.right=!0;break;case 3:t>22.5&&t<=67.5?(i.down=!0,i.right=!0):t>67.5&&t<=112.5?i.down=!0:t>112.5&&t<=157.5?(i.down=!0,i.left=!0):t>157.5&&t<=202.5?i.left=!0:t>202.5&&t<=247.5?(i.left=!0,i.up=!0):t>247.5&&t<=292.5?i.up=!0:t>292.5&&t<=337.5?(i.up=!0,i.right=!0):i.right=!0}}(Ly(this.getVelocityAngle()),this.dirMode,this),this}clearDirectionStates(){return this.left=!1,this.right=!1,this.up=!1,this.down=!1,this}}Object.assign(By.prototype,My);const Iy="IDLE",Dy="BEGIN",jy="RECOGNIZED",Ay=Phaser.Utils.Objects.GetValue,zy=Phaser.Utils.Array.SpliceOne,Fy=Phaser.Math.Distance.Between,Yy=Phaser.Math.Angle.Between;class Xy{constructor(t,e){var i=Ea(t);i===t&&(t=void 0);var s=i.input.manager.pointersTotal-1;s<2&&i.input.addPointer(2-s),this.scene=i,this.gameObject=t,t&&t.setInteractive(Ay(e,"inputConfig",void 0)),this.setEventEmitter(Ay(e,"eventEmitter",void 0)),this._enable=void 0,this.pointers=[],this.movedState={},this.resetFromJSON(e),this.boot()}resetFromJSON(t){return this.setEnable(Ay(t,"enable",!0)),this.bounds=Ay(t,"bounds",void 0),this.tracerState=Vy,this.pointers.length=0,q(this.movedState),this}boot(){this.gameObject?this.gameObject.on("pointerdown",this.onPointerDown,this):this.scene.input.on("pointerdown",this.onPointerDown,this),this.scene.input.on("pointerup",this.onPointerUp,this),this.scene.input.on("gameout",this.dragCancel,this),this.scene.input.on("pointermove",this.onPointerMove,this),this.scene.sys.events.once("shutdown",this.destroy,this)}shutdown(){this.scene&&(this.destroyEventEmitter(),this.pointers.length=0,q(this.movedState),this.gameObject||this.scene.input.off("pointerdown",this.onPointerDown,this),this.scene.input.off("pointerup",this.onPointerUp,this),this.scene.input.off("gameout",this.dragCancel,this),this.scene.input.off("pointermove",this.onPointerMove,this),this.scene.sys.events.off("shutdown",this.destroy,this),this.scene=void 0,this.gameObject=void 0)}destroy(){this.shutdown()}get enable(){return this._enable}set enable(t){if(this._enable!==t)return t||this.dragCancel(),this._enable=t,this}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}toggleEnable(){return this.setEnable(!this.enable),this}onPointerDown(t){if(this.enable&&2!==this.pointers.length&&(!this.bounds||this.bounds.contains(t.x,t.y))&&-1===this.pointers.indexOf(t))switch(this.movedState[t.id]=!1,this.pointers.push(t),this.pointerCamera=t.camera,this.tracerState){case Vy:this.tracerState=Gy,this.onDrag1Start();break;case Gy:this.tracerState=Hy,this.onDrag2Start()}}onPointerUp(t){if(this.enable&&(!this.bounds||this.bounds.contains(t.x,t.y))){var e=this.pointers.indexOf(t);if(-1!==e)switch(delete this.movedState[t.id],zy(this.pointers,e),this.tracerState){case Gy:this.tracerState=Vy,this.onDrag1End();break;case Hy:this.tracerState=Gy,this.onDrag2End(),this.onDrag1Start()}}}onPointerMove(t){if(this.enable&&t.isDown){var e=!this.bounds||this.bounds.contains(t.x,t.y),i=-1!==this.pointers.indexOf(t);if(!i&&e);else if(i&&!e)this.onPointerUp(t);else if(this.movedState[t.id]||(this.movedState[t.id]=t.x!==t.downX||t.y!==t.downY),this.movedState[t.id])switch(this.tracerState){case Gy:this.onDrag1();break;case Hy:this.onDrag2()}}}dragCancel(){return this.tracerState===Hy&&this.onDrag2End(),this.pointers.length=0,q(this.movedState),this.tracerState=Vy,this}onDrag1Start(){this.emit("drag1start",this)}onDrag1End(){this.emit("drag1end",this)}onDrag1(){this.emit("drag1",this)}onDrag2Start(){this.emit("drag2start",this)}onDrag2End(){this.emit("drag2end",this)}onDrag2(){this.emit("drag2",this)}get distanceBetween(){if(this.tracerState!==Hy)return 0;var t=this.pointers[0],e=this.pointers[1];return Fy(t.x,t.y,e.x,e.y)}get angleBetween(){if(this.tracerState!==Hy)return 0;var t=this.pointers[0],e=this.pointers[1];return Yy(t.x,t.y,e.x,e.y)}get drag1Vector(){var t=this.pointers[0];if(t&&this.movedState[t.id]){var e=t.position,i=t.prevPosition;Wy.x=e.x-i.x,Wy.y=e.y-i.y}else Wy.x=0,Wy.y=0;return Wy}get centerX(){if(this.tracerState!==Hy)return 0;var t=this.pointers[0].position,e=this.pointers[1].position;return(t.x+e.x)/2}get centerY(){if(this.tracerState!==Hy)return 0;var t=this.pointers[0].position,e=this.pointers[1].position;return(t.y+e.y)/2}get prevCenterX(){if(this.tracerState!==Hy)return 0;var t=this.movedState[this.pointers[0].id]?this.pointers[0].prevPosition:this.pointers[0].position,e=this.movedState[this.pointers[1].id]?this.pointers[1].prevPosition:this.pointers[1].position;return(t.x+e.x)/2}get prevCenterY(){if(this.tracerState!==Hy)return 0;var t=this.movedState[this.pointers[0].id]?this.pointers[0].prevPosition:this.pointers[0].position,e=this.movedState[this.pointers[1].id]?this.pointers[1].prevPosition:this.pointers[1].position;return(t.y+e.y)/2}get movementCenterX(){return this.centerX-this.prevCenterX}get movementCenterY(){return this.centerY-this.prevCenterY}setRecongizedStateObject(t){return this.recongizedState=t,this}get state(){return this.recongizedState.state}set state(t){this.recongizedState.state=t}cancel(){return this.state=Uy,this}isPointer0InGameObject(t,e,i){var s=this.pointers[0];return!!s&&Pm(t,s,e,i)}isPointer1InGameObject(t,e,i){var s=this.pointers[1];return!!s&&Pm(t,s,e,i)}}Object.assign(Xy.prototype,ln);var Wy={};const Vy=0,Gy=1,Hy=2,Uy="IDLE",Ny=Phaser.Utils.Objects.GetValue;class $y extends Xy{constructor(t,e){super(t,e);var i=this,s={states:{IDLE:{enter:function(){i.prevDistance=void 0,i.scaleFactor=1}},BEGIN:{},RECOGNIZED:{enter:function(){i.emit("pinchstart",i)},exit:function(){i.emit("pinchend",i)}}},init:function(){this.state=Ky},eventEmitter:!1};this.setRecongizedStateObject(new $f(s))}resetFromJSON(t){return super.resetFromJSON(t),this.setDragThreshold(Ny(t,"threshold",0)),this}onDrag2Start(){this.scaleFactor=1,this.prevDistance=this.distanceBetween,this.state=Jy,0===this.dragThreshold&&(this.state=qy)}onDrag2End(){this.state=Ky}onDrag2(){switch(this.state){case Jy:if(this.pointers[0].getDistance()>=this.dragThreshold&&this.pointers[1].getDistance()>=this.dragThreshold){var t=this.distanceBetween;this.scaleFactor=t/this.prevDistance,this.prevDistance=t,this.state=qy}break;case qy:t=this.distanceBetween,this.scaleFactor=t/this.prevDistance,this.emit("pinch",this),this.prevDistance=t}}get isPinched(){return this.state===qy}setDragThreshold(t){return this.dragThreshold=t,this}}const Ky="IDLE",Jy="BEGIN",qy="RECOGNIZED",Zy=Phaser.Math.RotateAround;var Qy=function(t,e,i,s){return Zy(t,e,i,s),t.rotation+=s,t},tb={};const eb=Phaser.Utils.Objects.GetValue,ib=Phaser.Math.Angle.WrapDegrees,sb=Phaser.Math.Angle.ShortestBetween,rb=Phaser.Math.RadToDeg,nb=Phaser.Math.DegToRad;class ab extends Xy{constructor(t,e){super(t,e);var i=this,s={states:{IDLE:{enter:function(){i.prevAngle=void 0,i.angle=0}},BEGIN:{},RECOGNIZED:{enter:function(){i.emit("rotatestart",i)},exit:function(){i.emit("rotateend",i)}}},init:function(){this.state=hb},eventEmitter:!1};this.setRecongizedStateObject(new $f(s))}resetFromJSON(t){return super.resetFromJSON(t),this.setDragThreshold(eb(t,"threshold",0)),this}onDrag2Start(){this.prevAngle=ib(rb(this.angleBetween)),this.state=lb,0===this.dragThreshold&&(this.state=db)}onDrag2End(){this.state=hb}onDrag2(){switch(this.state){case lb:if(this.pointers[0].getDistance()>=this.dragThreshold&&this.pointers[1].getDistance()>=this.dragThreshold){var t=ib(rb(this.angleBetween));this.angle=sb(this.prevAngle,t),this.prevAngle=t,this.state=db}break;case db:t=ib(rb(this.angleBetween)),this.angle=sb(this.prevAngle,t),this.prevAngle=t,this.emit("rotate",this)}}get isRotated(){return this.state===db}get rotation(){return nb(this.angle)}setDragThreshold(t){return this.dragThreshold=t,this}}var ob={spinObject:function(t,e){if(!this.isRotation)return this;void 0===e&&(e=this.pointers[0].camera);var i=this.movementCenterX,s=this.movementCenterY,r=function(t,e,i,s){return void 0===s?s={}:!0===s&&(s=tb),i.getWorldPoint(t,e,s),s}(this.centerX,this.centerY,e,!0),n=r.x,a=r.y,o=this.rotation;if(Array.isArray(t))for(var h=t,l=0,d=h.length;l0&&(r=!0,void 0===n&&(n=0),void 0===a&&(a=0)),(d=this.getSizerConfig(t)).align=i,d.padding=gv(s),Mb(r)?(d.expandWidth=Eb(r,"width",!1),d.expandHeight=Eb(r,"height",!1)):(d.expandWidth=r,d.expandHeight=r),t.isRexSizer||(d.expandWidth&&(t.minWidth=void 0===n?An(t):n),d.expandHeight&&(t.minHeight=void 0===a?zn(t):a)),d.alignOffsetX=o,d.alignOffsetY=h,d.aspectRatio=l,this.sizerChildren.hasOwnProperty(e)&&this.sizerChildren[e].destroy(),this.sizerChildren[e]=t,c&&this.addChildrenMap(e,t),this}};const Bb=Dg.prototype.clear;var Ib=function(t){this.backgroundChildren&&(this.backgroundChildren.length=0);var e,i=!t&&this.sizerEventsEnable;if(i&&(e=this.getChildren([])),Bb.call(this,t),i)for(var s,r=0,n=e.length;r0&&(Tb.width=e.aspectRatio,Tb.height=1,Ob.width=o,Ob.height=h,o=(l=kb(Tb,Ob,"FIT",!0)).width,h=l.height),t.isRexSizer?(t.runLayout(this,o,h),Pb(t,this)):Yv(t,o,h),s=d+i.left*this.scaleX,n=u-(i.left+i.right)*this.scaleX,r=c+i.top*this.scaleY,a=p-(i.top+i.bottom)*this.scaleY,Lm.call(this,t,s,r,n,a,e.align,e.alignOffsetX,e.alignOffsetY))}};Object.assign(jb,Lb,Db);var Ab=function(t,e){if(Array.isArray(t))return t.indexOf(e);for(var i in t)if(t[i]===e)return i;return null};const zb=Phaser.Utils.Objects.IsPlainObject,Fb=Phaser.Utils.Objects.GetValue;class Yb extends Cb{constructor(t,e,i,s,r,n){zb(e)?(e=Fb(n=e,"x",0),i=Fb(n,"y",0),s=Fb(n,"width",void 0),r=Fb(n,"height",void 0)):zb(s)&&(s=Fb(n=s,"width",void 0),r=Fb(n,"height",void 0)),super(t,e,i,s,r,n),this.type="rexOverlapSizer",this.sizerChildren={},this.addChildrenMap("items",this.sizerChildren)}childToKey(t){if("string"!=typeof t)return Ab(this.sizerChildren,t);var e=t;return this.sizerChildren.hasOwnPropery(e)?e:null}}Object.assign(Yb.prototype,jb);var Xb=Phaser.Math.Distance.Between,Wb=function(t,e,i){var s=t.width/2;return Xb(s,s,e,i)<=s};const Vb=Phaser.Math.Angle.Between,Gb=Phaser.Math.Angle.Normalize;var Hb=function(t,e,i){if(this.enable&&t.isDown){var s=this.sizerChildren.knob;if(Wb(s,e,i)){var r=s.width/2,n=s.startAngle,a=Vb(r,r,e,i),o=s.anticlockwise?n-a:a-n,h=Gb(o)/(2*Math.PI);this.stopEaseValue(),0===this.easeValueDuration||Math.abs(this.value-h)<.1?this.value=h:this.easeValueTo(h)}}},Ub=function(){this.sizerChildren.knob.on("pointerdown",Hb,this).on("pointermove",Hb,this).setInteractive()};const Nb=Phaser.Math.Angle.Between,$b=Phaser.Math.Angle.Wrap;var Kb=function(t,e,i){if(this.enable&&!this.panPointer){var s=this.sizerChildren.knob;Wb(s,e,i)&&Zb.call(this,t)}},Jb=function(t,e,i){if(this.enable&&t.isDown){var s=this.sizerChildren.knob;switch(this.panState){case ex:Wb(s,e,i)&&Zb.call(this,t);break;case ix:Wb(s,e,i)?tx.call(this):Qb.call(this)}}},qb=function(t,e,i){this.enable&&this.panPointer===t&&Qb.call(this)},Zb=function(t){this.panPointer=t,this.panState=ix},Qb=function(){this.panPointer=void 0,this.panState=ex},tx=function(){var t=this.panPointer.prevPosition,e=this.panPointer.position,i=this.sizerChildren.knob,s=Nb(i.x,i.y,t.x,t.y),r=Nb(i.x,i.y,e.x,e.y),n=i.anticlockwise?s-r:r-s,a=$b(n)/(2*Math.PI);this.stopEaseValue(),this.value+=a};const ex=0,ix=1;var sx=function(){this.sizerChildren.knob.on("pointerdown",Kb,this).on("pointermove",Jb,this).on("pointerup",qb,this).setInteractive(),this.panPointer=void 0,this.panState=ex},rx=function(t){return void 0===t&&(t=this.value),this.textFormatCallbackScope?this.textFormatCallback(t):this.textFormatCallback.call(this.textFormatCallbackScope,t)},nx={setTextFormatCallback:function(t,e){return this.textFormatCallback=t,this.textFormatCallbackScope=e,this},getFormatText:rx,updateText:function(t){var e=this.sizerChildren.text;return e&&this.textFormatCallback&&(e.setText(rx.call(this,t)),e.layout&&e.layout()),this}};const ax=Phaser.Utils.Objects.GetValue,ox=Phaser.Math.Snap.To;class hx extends(Xu(Yb)){constructor(t,e){void 0===e&&(e={}),super(t,e),this.type="rexKnob",this.bootProgressBase(e);var i=ax(e,"background",void 0),s=ax(e,"text",void 0);i&&this.addBackground(i),s&&(e.textColor=void 0,e.textStrokeColor=void 0,this.setTextFormatCallback(ax(e,"textFormatCallback",void 0),ax(e,"textFormatCallbackScope",void 0)),e.textFormatCallback=void 0,e.textFormatCallbackScope=void 0);var r=new np(t,e);r.setDepth(ax(e,"knobDepth",0)),r._value=-1,t.add.existing(r),this.add(r,"knob"),s&&(this.add(s,"text","center",0,!1),t.children.moveBelow(r,s)),this.addChildrenMap("background",i),this.addChildrenMap("knob",r),this.addChildrenMap("text",s),this.setEnable(ax(e,"enable",void 0)),this.setGap(ax(e,"gap",void 0)),this.setValue(ax(e,"value",0),ax(e,"min",void 0),ax(e,"max",void 0));var n=ax(e,"input",0);switch("string"==typeof n&&(n=lx[n]),n){case 0:sx.call(this);break;case 1:Ub.call(this)}}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}setGap(t){return this.gap=t,this}get value(){return this.sizerChildren.knob.value}set value(t){void 0!==this.gap&&(t=ox(t,this.gap));var e=this.value;this.sizerChildren.knob.value=t;var i=this.value;e!==i&&(this.updateText(),this.eventEmitter.emit("valuechange",i,e,this.eventEmitter))}}const lx={pan:0,drag:0,click:1,none:-1};Object.assign(hx.prototype,nx),t.register("knob",(function(t){var e=new hx(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.Knob",hx);const dx={arc:Cc,circle:kc,curve:class extends bc{constructor(t){super(),this.setCurve(t),this.setIterations(32)}get curve(){return this._curve}set curve(t){this.dirty=this.dirty||this._curve!==t,this._curve=t}setCurve(t){return this.curve=t,this}get iterations(){return this._iterations}set iterations(t){this.dirty=this.dirty||this._iterations!==t,this._iterations=t}setIterations(t){return this.iterations=t,this}updateData(){this.pathData.length=0;for(var t=this.curve.getPoints(this.iterations),e=0,i=t.length;ethis.value)for(var d=0;dthis.value&&(t+=1));for(var r=this.getShapes(),n=0,a=r.length;n0?d.pop().setTexture(u,O):r(c,u,O),h&&c.add.existing(T),l){var M=b+k*P+a*k,E=x+w*S+o*w;T.setOrigin(a,o).setPosition(M,E).setScale(v,f).setRotation(m),HC(T,b,x,m)}C.push(T)}return C}(t,e,i,s),a=0,o=n.length;a0&&(a=this.getChildLocalScaleX(s),a/=s.biasScale,this.setChildLocalScale(s,a)),r.biasScale&&(a=this.getChildLocalScaleX(r),a/=r.biasScale,this.setChildLocalScale(r,a))),e?t.call(e,i,s,r,n):t(i,s,r,n),this.scaleMode&&(s.biasScale>0&&(a=this.getChildLocalScaleX(s),a*=s.biasScale,this.setChildLocalScale(s,a)),r.biasScale&&(a=this.getChildLocalScaleX(r),a*=r.biasScale,this.setChildLocalScale(r,a))))};Object.assign(ek.prototype,$C);const sk={fit:1,FIT:1,envelop:2,ENVELOP:2};t.register("transitionImage",(function(t,e,i,s,r){var n=new ek(this.scene,t,e,i,s,r);return this.scene.add.existing(n),n})),P(window,"RexPlugins.UI.TransitionImage",ek);const rk=Phaser.Renderer.WebGL.Pipelines.PostFXPipeline,nk=Phaser.Utils.Objects.GetValue,ak=Phaser.Math.Clamp;class ok extends rk{constructor(t){super({name:"rexDissolvePostFx",game:t,renderTarget:!0,fragShader:"#ifdef GL_FRAGMENT_PRECISION_HIGH\n#define highmedp highp\n#else\n#define highmedp mediump\n#endif\nprecision highmedp float;\n// Scene buffer\nuniform sampler2D uMainSampler;\nuniform sampler2D uMainSampler2;\n\nuniform int resizeMode;\nuniform float progress;\nuniform float fromRatio;\nuniform float toRatio;\nvarying vec2 outFragCoord;\n// Effect parameters\nuniform float noiseX;\nuniform float noiseY;\nuniform float noiseZ;\nuniform float fromEdgeStart;\nuniform float fromEdgeWidth;\nuniform float toEdgeStart;\nuniform float toEdgeWidth;\n\nvec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }\nvec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }\nvec4 permute(vec4 x) { return mod289(((x*34.0)+1.0)*x); }\nvec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }\nvec3 fade(vec3 t) { return t*t*t*(t*(t*6.0-15.0)+10.0); }\nfloat Perlin(vec3 P) {\n vec3 i0 = mod289(floor(P)), i1 = mod289(i0 + vec3(1.0));\n vec3 f0 = fract(P), f1 = f0 - vec3(1.0), f = fade(f0);\n vec4 ix = vec4(i0.x, i1.x, i0.x, i1.x), iy = vec4(i0.yy, i1.yy);\n vec4 iz0 = i0.zzzz, iz1 = i1.zzzz;\n vec4 ixy = permute(permute(ix) + iy), ixy0 = permute(ixy + iz0), ixy1 = permute(ixy + iz1);\n vec4 gx0 = ixy0 * (1.0 / 7.0), gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5;\n vec4 gx1 = ixy1 * (1.0 / 7.0), gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5;\n gx0 = fract(gx0); gx1 = fract(gx1);\n vec4 gz0 = vec4(0.5) - abs(gx0) - abs(gy0), sz0 = step(gz0, vec4(0.0));\n vec4 gz1 = vec4(0.5) - abs(gx1) - abs(gy1), sz1 = step(gz1, vec4(0.0));\n gx0 -= sz0 * (step(0.0, gx0) - 0.5); gy0 -= sz0 * (step(0.0, gy0) - 0.5);\n gx1 -= sz1 * (step(0.0, gx1) - 0.5); gy1 -= sz1 * (step(0.0, gy1) - 0.5);\n vec3 g0 = vec3(gx0.x,gy0.x,gz0.x), g1 = vec3(gx0.y,gy0.y,gz0.y),\n g2 = vec3(gx0.z,gy0.z,gz0.z), g3 = vec3(gx0.w,gy0.w,gz0.w),\n g4 = vec3(gx1.x,gy1.x,gz1.x), g5 = vec3(gx1.y,gy1.y,gz1.y),\n g6 = vec3(gx1.z,gy1.z,gz1.z), g7 = vec3(gx1.w,gy1.w,gz1.w);\n vec4 norm0 = taylorInvSqrt(vec4(dot(g0,g0), dot(g2,g2), dot(g1,g1), dot(g3,g3)));\n vec4 norm1 = taylorInvSqrt(vec4(dot(g4,g4), dot(g6,g6), dot(g5,g5), dot(g7,g7)));\n g0 *= norm0.x; g2 *= norm0.y; g1 *= norm0.z; g3 *= norm0.w;\n g4 *= norm1.x; g6 *= norm1.y; g5 *= norm1.z; g7 *= norm1.w;\n vec4 nz = mix(vec4(dot(g0, vec3(f0.x, f0.y, f0.z)), dot(g1, vec3(f1.x, f0.y, f0.z)),\n dot(g2, vec3(f0.x, f1.y, f0.z)), dot(g3, vec3(f1.x, f1.y, f0.z))),\n vec4(dot(g4, vec3(f0.x, f0.y, f1.z)), dot(g5, vec3(f1.x, f0.y, f1.z)),\n dot(g6, vec3(f0.x, f1.y, f1.z)), dot(g7, vec3(f1.x, f1.y, f1.z))), f.z);\n return 2.2 * mix(mix(nz.x,nz.z,f.y), mix(nz.y,nz.w,f.y), f.x);\n}\nfloat Perlin(vec2 P) { return Perlin(vec3(P, 0.0)); }\n\n\nvec4 getFromColor (vec2 uv) {\n return texture2D(uMainSampler, uv);\n}\n\nvec4 getToColor (vec2 uv) {\n if (resizeMode == 2) {\n // cover\n return texture2D(uMainSampler2, 0.5 + (vec2(uv.x, 1.0 - uv.y) - 0.5) * vec2(min(fromRatio / toRatio, 1.0), min((toRatio / fromRatio), 1.0)));\n } else if (resizeMode == 1) {\n // contain\n return texture2D(uMainSampler2, 0.5 + (vec2(uv.x, 1.0 - uv.y) - 0.5) * vec2(max(fromRatio / toRatio, 1.0), max((toRatio / fromRatio), 1.0)));\n } else {\n // stretch\n return texture2D(uMainSampler2, vec2(uv.x, 1.0 - uv.y));\n }\n}\n\nvec4 transition (vec2 uv) { \n vec4 colorFront = getFromColor(uv);\n vec4 colorTo = getToColor(uv);\n\n float noise = (Perlin(vec3(uv.x * noiseX, uv.y * noiseY, noiseZ)) + 1.0) / 2.0\n * (1.0 - (fromEdgeStart + fromEdgeWidth + toEdgeStart + toEdgeWidth))\n + (fromEdgeStart + fromEdgeWidth + toEdgeStart + toEdgeWidth) * 0.5;\n vec4 colorResult = colorFront * smoothstep(progress - (fromEdgeStart + fromEdgeWidth), progress - fromEdgeStart, noise)\n + colorTo * smoothstep((1.0 - progress) - (toEdgeStart + toEdgeWidth), (1.0 - progress) - toEdgeStart, (1.0 - noise));\n return colorResult;\n}\n\nvoid main () {\n vec2 uv = outFragCoord;\n gl_FragColor = transition(uv);\n}\n"}),this._progress=0,this.toFrame=null,this.targetTexture=null,this.resizeMode=1,this.toRatio=1,this.noiseX=0,this.noiseY=0,this.noiseZ=0,this.fromEdgeStart=.01,this.fromEdgeWidth=.05,this.toEdgeStart=.01,this.toEdgeWidth=.05}resetFromJSON(t){return this.setProgress(nk(t,"progress",0)),this.setTransitionTargetTexture(nk(t,"toTexture","__DEFAULT"),nk(t,"toFrame",void 0),nk(t,"resizeMode",1)),this.setNoise(nk(t,"noiseX",void 0),nk(t,"noiseY",void 0),nk(t,"noiseZ",void 0)),this.setFromEdge(nk(t,"fromEdgeStart",.01),nk(t,"fromEdgeWidth",.05)),this.setToEdge(nk(t,"toEdgeStart",.01),nk(t,"toEdgeWidth",.05)),this}onBoot(){}onPreRender(){this.set1f("progress",this.progress),this.set1i("resizeMode",this.resizeMode),this.set1f("noiseX",this.noiseX),this.set1f("noiseY",this.noiseY),this.set1f("noiseZ",this.noiseZ),this.set1f("fromEdgeStart",this.fromEdgeStart),this.set1f("fromEdgeWidth",this.fromEdgeWidth),this.set1f("toEdgeStart",this.toEdgeStart),this.set1f("toEdgeWidth",this.toEdgeWidth)}onDraw(t){this.set1f("fromRatio",t.width/t.height),this.set1f("toRatio",this.toRatio),this.set1i("uMainSampler2",1),this.bindTexture(this.targetTexture,1),this.bindAndDraw(t)}get progress(){return this._progress}set progress(t){this._progress=ak(t,0,1)}setProgress(t){return this.progress=t,this}setTransitionTargetTexture(t,e,i){void 0===t&&(t="__DEFAULT");var s=this.game.textures.getFrame(t,e);return s||(s=this.game.textures.getFrame("__DEFAULT")),this.toRatio=s.width/s.height,this.toFrame=s,this.targetTexture=s.glTexture,void 0!==i&&(this.resizeMode=i),this}setResizeMode(t){return"string"==typeof t&&(t=hk[t]),this.resizeMode=t,this}setNoise(t,e,i){return void 0===t&&(t=4+6*Math.random()),void 0===e&&(e=4+6*Math.random()),void 0===i&&(i=10*Math.random()),this.noiseX=t,this.noiseY=e,this.noiseZ=i,this}setFromEdge(t,e){return this.fromEdgeStart=t,this.fromEdgeWidth=e,this}setToEdge(t,e){return this.toEdgeStart=t,this.toEdgeWidth=e,this}}var hk={stretch:0,contain:1,cover:2};const lk=Phaser.Utils.Array.SpliceOne,dk=.1,ck=[function(t){t.addTransitionMode("slideAwayRight",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.width*s;t.setChildLocalPosition(e,r,0)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0)}}).addTransitionMode("slideAwayLeft",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.width*-s;t.setChildLocalPosition(e,r,0)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0)}}).addTransitionMode("slideAwayDown",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.height*s;t.setChildLocalPosition(e,0,r)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0)}}).addTransitionMode("slideAwayUp",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.height*-s;t.setChildLocalPosition(e,0,r)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0)}})},function(t){t.addTransitionMode("slideRight",{ease:"Linear",dir:"in",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=i.width*(s-1);t.setChildLocalPosition(i,r,0)},onComplete:function(t,e,i,s){t.setChildLocalPosition(i,0,0)}}).addTransitionMode("slideLeft",{ease:"Linear",dir:"in",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=i.width*(1-s);t.setChildLocalPosition(i,r,0)},onComplete:function(t,e,i,s){t.setChildLocalPosition(i,0,0)}}).addTransitionMode("slideDown",{ease:"Linear",dir:"in",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=i.height*(s-1);t.setChildLocalPosition(i,0,r)},onComplete:function(t,e,i,s){t.setChildLocalPosition(i,0,0)}}).addTransitionMode("slideUp",{ease:"Linear",dir:"in",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=i.height*(1-s);t.setChildLocalPosition(i,0,r)},onComplete:function(t,e,i,s){t.setChildLocalPosition(i,0,0)}})},function(t){t.addTransitionMode("pushRight",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.width*s;t.setChildLocalPosition(e,r,0),r=i.width*(s-1),t.setChildLocalPosition(i,r,0)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0),t.setChildLocalPosition(i,0,0)}}).addTransitionMode("pushLeft",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.width*-s;t.setChildLocalPosition(e,r,0),r=i.width*(1-s),t.setChildLocalPosition(i,r,0)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0),t.setChildLocalPosition(i,0,0)}}).addTransitionMode("pushDown",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.height*s;t.setChildLocalPosition(e,0,r),r=i.height*(s-1),t.setChildLocalPosition(i,0,r)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0),t.setChildLocalPosition(i,0,0)}}).addTransitionMode("pushUp",{ease:"Linear",dir:"out",mask:!0,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=e.height*-s;t.setChildLocalPosition(e,0,r),r=i.height*(1-s),t.setChildLocalPosition(i,0,r)},onComplete:function(t,e,i,s){t.setChildLocalPosition(e,0,0),t.setChildLocalPosition(i,0,0)}})},function(t){t.addTransitionMode("zoomOut",{ease:"Linear",dir:"out",mask:!1,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=1-s;t.setChildLocalScale(e,r,r)},onComplete:function(t,e,i,s){t.setChildLocalScale(e,1,1)}}).addTransitionMode("zoomIn",{ease:"Linear",dir:"in",mask:!1,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){var r=s;t.setChildLocalScale(i,r,r)},onComplete:function(t,e,i,s){t.setChildLocalScale(i,1,1)}}).addTransitionMode("zoomInOut",{ease:"Linear",dir:"out",mask:!1,onStart:function(t,e,i,s){i.tint=0},onProgress:function(t,e,i,s){var r;s<.5?(r=1-wo(s),t.setChildLocalScale(e,r,r)):(e.visible&&t.setChildVisible(e,!1),r=1-wo(s),t.setChildLocalScale(i,r,r))},onComplete:function(t,e,i,s){t.setChildLocalScale(e,1,1),t.setChildVisible(e,!0),e.tint=16777215,t.setChildLocalScale(i,1,1),t.setChildVisible(i,!0),i.tint=16777215}})},function(t){t.addTransitionMode("fade",{ease:"Linear",dir:"out",mask:!1,onStart:function(t,e,i,s){i.tint=0},onProgress:function(t,e,i,s){var r;s<.5?(s=wo(s),r=Math.floor(255*(1-s)),e.tint=(r<<16)+(r<<8)+r):(e.visible&&t.setChildVisible(e,!1),s=wo(s),r=Math.floor(255*(1-s)),i.tint=(r<<16)+(r<<8)+r)},onComplete:function(t,e,i,s){t.setChildVisible(e,!0),e.tint=16777215,t.setChildVisible(i,!0),i.tint=16777215}}).addTransitionMode("crossFade",{ease:"Linear",dir:"out",mask:!1,onStart:function(t,e,i,s){},onProgress:function(t,e,i,s){t.setChildLocalAlpha(e,1-s),t.setChildLocalAlpha(i,s)},onComplete:function(t,e,i,s){t.setChildLocalAlpha(e,1)}})},function(t){var e,i=(e=t.scene,new Px(e,{type:"Graphics",create:[{name:"rect",type:"rectangle"}],update:function(){this.getShape("rect").fillStyle(16777215).setSize(this.width*this.value,this.height*this.value).setCenterPosition(this.centerX,this.centerY)}}));t.once("destroy",(function(){i.destroy()})).addTransitionMode("irisOut",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){t.setCurrentImageMaskEnable(!0,!0)},onProgress:function(t,e,i,s){t.maskGameObject.setValue(s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("irisIn",{ease:"Linear",dir:"in",mask:i,onStart:function(t,e,i,s){t.setNextImageMaskEnable(!0,!0)},onProgress:function(t,e,i,s){t.maskGameObject.setValue(1-s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("irisInOut",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){i.tint=0,t.setCurrentImageMaskEnable(!0),t.setNextImageMaskEnable(!0)},onProgress:function(t,e,i,s){var r;s<.5?(s=wo(s),r=Math.floor(255*(1-s)),t.maskGameObject.setValue(1-s),e.tint=(r<<16)+(r<<8)+r):(e.visible&&t.setChildVisible(e,!1),s=wo(s),r=Math.floor(255*(1-s)),t.maskGameObject.setValue(1-s),i.tint=(r<<16)+(r<<8)+r)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1),t.setChildVisible(e,!0),e.tint=16777215,t.setChildVisible(i,!0),i.tint=16777215}})},function(t){var e,i=(e=t.scene,new Px(e,{type:"Graphics",create:[{name:"pie",type:"arc"}],update:function(){var t=2*Math.max(this.width,this.height),e=90*this.value;this.getShape("pie").fillStyle(16777215).setCenterPosition(this.centerX,0).setRadius(t).setAngle(90-e,90+e).setPie()}}));t.once("destroy",(function(){i.destroy()})).addTransitionMode("pieOut",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){t.setCurrentImageMaskEnable(!0,!0)},onProgress:function(t,e,i,s){t.maskGameObject.setValue(s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("pieIn",{ease:"Linear",dir:"in",mask:i,onStart:function(t,e,i,s){t.setNextImageMaskEnable(!0,!0)},onProgress:function(t,e,i,s){t.maskGameObject.setValue(1-s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("pieInOut",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){i.tint=0,t.setCurrentImageMaskEnable(!0),t.setNextImageMaskEnable(!0)},onProgress:function(t,e,i,s){var r;s<.5?(s=wo(s),r=Math.floor(255*(1-s)),t.maskGameObject.setValue(1-s),e.tint=(r<<16)+(r<<8)+r):(e.visible&&t.setChildVisible(e,!1),s=wo(s),r=Math.floor(255*(1-s)),t.maskGameObject.setValue(1-s),i.tint=(r<<16)+(r<<8)+r)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1),t.setChildVisible(e,!0),e.tint=16777215,t.setChildVisible(i,!0),i.tint=16777215}})},function(t){var e,i=(e=t.scene,new Px(e,{type:"Graphics",create:[{name:"rect",type:"rectangle"}],update:function(){var t=this.getShape("rect").fillStyle(16777215),e=1-this.value;switch(this.wipeMode){case"right":t.setSize(this.width*e,this.height).setTopLeftPosition(this.width-t.width,0);break;case"left":t.setSize(this.width*e,this.height).setTopLeftPosition(0,0);break;case"down":t.setSize(this.width,this.height*e).setTopLeftPosition(0,this.height-t.height);break;case"up":t.setSize(this.width,this.height*e).setTopLeftPosition(0,0)}}}));t.once("destroy",(function(){i.destroy()})).addTransitionMode("wipeRight",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){t.setCurrentImageMaskEnable(!0),t.maskGameObject.wipeMode="right"},onProgress:function(t,e,i,s){t.maskGameObject.setValue(s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("wipeLeft",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){t.setCurrentImageMaskEnable(!0),t.maskGameObject.wipeMode="left"},onProgress:function(t,e,i,s){t.maskGameObject.setValue(s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("wipeDown",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){t.setCurrentImageMaskEnable(!0),t.maskGameObject.wipeMode="down"},onProgress:function(t,e,i,s){t.maskGameObject.setValue(s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}}).addTransitionMode("wipeUp",{ease:"Linear",dir:"out",mask:i,onStart:function(t,e,i,s){t.setCurrentImageMaskEnable(!0),t.maskGameObject.wipeMode="up"},onProgress:function(t,e,i,s){t.maskGameObject.setValue(s)},onComplete:function(t,e,i,s){t.removeMaskGameObject(!1)}})},function(t){var e=function(t,e){var i=new Px(t,{type:"Graphics",create:{rectangle:e},update:function(){for(var t=this.getShapes(),i=this.width/e,s=0;s=0;s--)(a=r[s])instanceof e&&(a.destroy(),lk(r,s));else{s=0;for(var r,n=(r=t.postPipelines).length;s0}(e,ok),delete e.effect}})},function(t){t.addTransitionMode("revealRight",{ease:"Linear",dir:"in",mask:!1,onStart:function(t,e,i,s){i.effect=i.preFX.addReveal(dk,0,0)},onProgress:function(t,e,i,s){i.effect.progress=s},onComplete:function(t,e,i,s){i.preFX.remove(i.effect),delete i.effect}}).addTransitionMode("revealLeft",{ease:"Linear",dir:"in",mask:!1,onStart:function(t,e,i,s){i.effect=i.preFX.addReveal(dk,1,0)},onProgress:function(t,e,i,s){i.effect.progress=s},onComplete:function(t,e,i,s){i.preFX.remove(i.effect),delete i.effect}}).addTransitionMode("revealDown",{ease:"Linear",dir:"in",mask:!1,onStart:function(t,e,i,s){i.effect=i.preFX.addReveal(dk,0,1)},onProgress:function(t,e,i,s){i.effect.progress=s},onComplete:function(t,e,i,s){i.preFX.remove(i.effect),delete i.effect}}).addTransitionMode("revealUp",{ease:"Linear",dir:"in",mask:!1,onStart:function(t,e,i,s){i.effect=i.preFX.addReveal(dk,1,1)},onProgress:function(t,e,i,s){i.effect.progress=s},onComplete:function(t,e,i,s){i.preFX.remove(i.effect),delete i.effect}})}];class uk extends ek{constructor(t,e,i,s,r,n){super(t,e,i,s,r,n);for(var a=0,o=ck.length;at.dropEnable}),this.on("drop",(function(t,e){this._files=e.dataTransfer.files;var i=this._files;if(i&&this.filters)for(var s in this.filters){for(var r=this.filters[s],n=[],a=0,o=i.length;a0&&this.emit(`drop.${s}`,n)}}),this)}get files(){return this._files}}Object.assign(Jk.prototype,Hk),t.register("fileDropZone",(function(t){var e=new Jk(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.FileDropZone",Jk);const qk=Phaser.Math.Wrap;var Zk=function(t,e){if(this.hasRatioFitChild){var i,s,r;0===this.orientation?i=e-(this.getInnerPadding("top")+this.getInnerPadding("bottom"))*this.scaleY:(this.getInnerPadding("left"),this.getInnerPadding("right"),this.scaleX);for(var n=this.sizerChildren,a=0,o=n.length;a(i=0===this.orientation?Math.abs(h.left-t):Math.abs(h.top-e))&&(n=i,r=a)}return h=s[s.length-1],n>(i=0===this.orientation?Math.abs(h.right-t):Math.abs(h.bottom-e))&&(n=i,r=a+1),r};const iw=Phaser.Utils.Objects.IsPlainObject,sw=Phaser.Utils.Objects.GetValue,rw=Phaser.Display.Align.CENTER,nw={min:0,full:-1};var aw=function(t,e,i,s,r,n,a,o,h,l){fv.call(this,t);var d=t.isRexSpace,c=typeof e;if(null===e)return this;if("number"===c);else if("string"===c)e=nw[e];else if(iw(e)){var u;e=sw(u=e,"proportion",void 0),i=sw(u,"align",rw),s=sw(u,"padding",0),r=sw(u,"expand",!1),n=sw(u,"key",void 0),a=sw(u,"index",void 0),t.isRexSizer||(o=sw(u,"minWidth",void 0),h=sw(u,"minHeight",void 0)),l=sw(u,"fitRatio",0)}return"string"==typeof i&&(i=zg[i]),void 0===e&&(e=d?1:0),void 0===i&&(i=rw),void 0===s&&(s=0),void 0===r&&(r=!1),void 0===o&&(d?o=0:t.isRexSizer||(o=t._minWidth)),void 0===h&&(d?h=0:t.isRexSizer||(h=t._minHeight)),void 0===l||!1===l?l=0:!0===l&&(l=An(t)/zn(t)),(u=this.getSizerConfig(t)).proportion=e,u.align=i,u.padding=gv(s),u.expand=r,u.fitRatio=0===e?l:0,void 0===a||a>=this.sizerChildren.length?this.sizerChildren.push(t):this.sizerChildren.splice(a,0,t),t.isRexSizer||(e>0&&(0===this.orientation?t.minWidth=void 0===o?An(t):o:t.minHeight=void 0===h?zn(t):h),r&&(0===this.orientation?t.minHeight=h:t.minWidth=o)),void 0!==n&&this.addChildrenMap(n,t),this},ow={add:aw,addSpace(t){return this.insertSpace(void 0,t),this},insertSpace(t,e){return void 0===e&&(e=1),aw.call(this,new tw(this.scene),{proportion:e,minWidth:0,minHeight:0,index:t}),this},insert(t,e,i,s,r,n,a,o){return iw(i)&&(i.index=t),aw.call(this,e,i,s,r,n,a,t,o),this},insertAtPosition(t,e,i,s,r,n,a,o,h){var l=ew.call(this,t,e);return-1===l&&(l=void 0),this.insert(l,i,s,r,n,a,o,h),this}};const hw=Phaser.Utils.Array.Remove;var lw={remove(t,e){return this.getParentSizer(t)!==this||(hw(this.sizerChildren,t),wv.call(this,t,e)),this},removeAll(t){for(var e=this.sizerChildren.length-1;e>=0;e--)this.remove(this.sizerChildren[e],t);return this},clear(t){return this.sizerChildren.length=0,Ib.call(this,t),this}},dw={getChildAlign(t){return this.getSizerConfig(t).align},setChildAlign(t,e){return"string"==typeof e&&(e=zg[e]),this.getSizerConfig(t).align=e,this}},cw={getChildProportion(t){return this.getSizerConfig(t).proportion},setChildProportion(t,e){return this.getSizerConfig(t).proportion=e,this}},uw={getChildExpand(t){return this.getSizerConfig(t).expand},setChildExpand(t,e){return this.getSizerConfig(t).expand=e,this}},pw={sortChildren(t){return this.sizerChildren.sort(t),this},sortChildrenByData(t,e){return this.sizerChildren.sort((function(i,s){var r=i.getData(t),n=s.getData(t);return e?n-r:r-n})),this},sortChildrenByProperty(t,e){return this.sizerChildren.sort((function(i,s){var r=i[t],n=s[t];return e?n-r:r-n})),this}},gw={getChildrenWidth:function(t){if(this.rexSizer.hidden)return 0;void 0===t&&(t=!0);var e,i,s,r,n,a=0,o=this.sizerChildren,h=!1;if(this.childrenProportion,0===this.orientation)for(var l=!0,d=0,c=o.length;d0&&!i.resolved&&(n=void 0),void 0===n&&(0===s||this.hasProportion0Child?h=!0:n=0)):n=0,h||(n+=((r=e.rexSizer.padding).left+r.right)*this.scaleX,l?l=!1:n+=this.space.item*this.scaleX,a+=n)));else for(d=0,c=o.length;d0&&!i.resolved&&(n=void 0),void 0===n&&(0===s||this.hasProportion0Child?h=!0:n=0)):n=0,h||(n+=((r=i.padding).top+r.bottom)*this.scaleY,c?c=!1:n+=this.space.item*this.scaleY,a+=n)))}return h?void 0:a+(this.space.top+this.space.bottom)*this.scaleY},getExpandedChildWidth:function(t,e){var i;void 0===e&&(e=this.width*this.scaleX);var s=t.rexSizer;if(0===this.orientation)s.proportion>0&&this.proportionLength>0&&(i=s.proportion*this.proportionLength);else if(s.expand){var r=this.space,n=e-(r.left+r.right)*this.scaleX,a=s.padding;i=n-(a.left+a.right)*this.scaleX}return i},getExpandedChildHeight:function(t,e){var i;void 0===e&&(e=this.height);var s=t.rexSizer;if(0===this.orientation){if(s.expand){var r=this.space,n=e-(r.top+r.bottom)*this.scaleY,a=s.padding;i=n-(a.top+a.bottom)*this.scaleY}}else s.proportion>0&&this.proportionLength>0&&(i=s.proportion*this.proportionLength);return i},getChildrenSizers:function(t){void 0===t&&(t=[]);for(var e,i=this.sizerChildren,s=0,r=i.length;s0&&(Yv(t,0,0),e.resolved=!1,this.hasRatioFitChild=!0);return this._childrenProportion=void 0,this.hasProportion0Child=!1,this.proportionLength=void 0,Av.call(this),this},layoutChildren:function(){for(var t,e,i,s,r,n,a,o,h,l,d=this.sizerChildren,c=this.innerLeft,u=this.innerTop,p=this.innerWidth,g=this.innerHeight,v=c,f=u,m=this.startChildIndex,y=0,b=d.length;y0?(e=t-this.getChildrenWidth(!1),this.proportionLength=e/this.childrenProportion):this.proportionLength=0}return t},resolveHeight:function(t){if(void 0!==(t=Bv.call(this,t))&&1===this.orientation&&void 0===this.proportionLength){var e=t-this.childrenHeight;e>0?(e=t-this.getChildrenHeight(!1),this.proportionLength=e/this.childrenProportion):this.proportionLength=0}return t},hasWidthWrap:function(){return!(!this.hasRatioFitChild||1!==this.orientation)||Rv.call(this)},runWidthWrap:function(t){this.wrapResult||(1===this.orientation&&Zk.call(this,t,void 0),Lv.call(this,t))},hasHeightWrap:function(){return!(!this.hasRatioFitChild||0!==this.orientation)||Iv.call(this)},runHeightWrap:function(t){this.wrapResult||(0===this.orientation&&Zk.call(this,void 0,t),Dv.call(this,t))},setChildrenAlignMode:function(t){void 0===t&&(t="left");var e=this.sizerChildren,i=e[0],s=i&&i.isRexSpace;"right"===t||"bottom"===t||"center"===t?s||this.insertSpace(0):s&&this.remove(i,!0);var r=e.length-1,n=e[r],a=n&&n.isRexSpace;return"center"===t?a||this.insertSpace(r+1):a&&this.remove(n,!0),this}};Object.assign(gw,ow,lw,dw,cw,uw,pw);var vw=function(){for(var t,e,i=0,s=this.sizerChildren,r=0,n=s.length;r0?i+=e:0===e&&(this.hasProportion0Child=!0));return i},fw={x:0,h:0,horizontal:0,"left-to-right":0,y:1,v:1,vertical:1,"top-to-bottom":1},mw=function(t){return"string"==typeof t&&(t=fw[t]),t};const yw=Phaser.Utils.Objects.IsPlainObject,bw=Phaser.Utils.Objects.GetValue;class xw extends Cb{constructor(t,e,i,s,r,n,a){yw(e)?(e=bw(a=e,"x",0),i=bw(a,"y",0),s=bw(a,"width",void 0),r=bw(a,"height",void 0),n=bw(a,"orientation",0)):yw(s)?(s=bw(a=s,"width",void 0),r=bw(a,"height",void 0),n=bw(a,"orientation",0)):yw(n)&&(n=bw(a=n,"orientation",0)),void 0===n&&(n=0),super(t,e,i,s,r,a),this.type="rexSizer",this.sizerChildren=[],this.setOrientation(n),this.setItemSpacing(bw(a,"space.item",0)),this.setStartChildIndex(bw(a,"startChildIndex",0)),this.setRTL(bw(a,"rtl",!1)),this.addChildrenMap("items",this.sizerChildren)}setOrientation(t){return this.orientation=mw(t),this}setItemSpacing(t){return this.space.item=t,this}setStartChildIndex(t){return this.startChildIndex=t,this}setRTL(t){return void 0===t&&(t=!0),this.rtl=t,this}get childrenProportion(){return void 0===this._childrenProportion&&(this._childrenProportion=vw.call(this)),this._childrenProportion}}Object.assign(xw.prototype,gw);var Cw=function(t,e,i){if(t){var s=null==e,r=null==i;return s&&r||(s||(t.displayWidth=e),r||(t.displayHeight=i),s&&(t.scaleX=t.scaleY),r&&(t.scaleY=t.scaleX)),t}},kw={appendText:Mi,resetDisplayContent:function(t){void 0===t?t={}:"string"==typeof t&&(t={text:t});var e=t.text||"";this.setText(e);var i=this.childrenMap.icon;if(i){t.icon?this.show(i):this.hide(i);var s=t.iconSize;s&&(this.setChildDisplaySize(i,s,s),void 0!==this.iconWidth&&this.setIconSize(s)),!0!==t.icon&&this.setIconTexture(t.icon,t.iconFrame)}var r=this.childrenMap.action;if(r){t.action?this.show(r):this.hide(r);var n=t.actionSize;n&&(this.setChildDisplaySize(r,n,n),void 0!==this.actionWidth&&this.setActionSize(n)),!0!==t.action&&this.setActionTexture(t.action,t.actionFrame)}return this}};class ww extends xw{get text(){var t=this.childrenMap.text;return t?t.text:""}set text(t){var e=this.childrenMap.text;e&&e.setText(t)}setText(t){return this.text=t,this}setIconTexture(t,e){var i=this.childrenMap.icon;return i&&i.setTexture?(i.setTexture(t,e),void 0!==this.iconWidth&&void 0!==this.iconHeight&&(Cw(i,this.iconWidth,this.iconHeight),this.resetChildScaleState(i)),this):this}setTexture(t,e){return this.setIconTexture(t,e),this}setIconSize(t,e){return void 0===e&&(e=t),this.iconWidth=t,this.iconHeight=e,this}get texture(){var t=this.childrenMap.icon;if(t)return t.texture}get frame(){var t=this.childrenMap.icon;if(t)return t.frame}setActionTexture(t,e){var i=this.childrenMap.action;return i&&i.setTexture?(i.setTexture(t,e),void 0!==this.actionWidth&&void 0!==this.actionHeight&&(Cw(i,this.actionWidth,this.actionHeight),this.resetChildScaleState(i)),this):this}get actionTexture(){var t=this.childrenMap.action;if(t)return t.texture}get actionFrame(){var t=this.childrenMap.action;if(t)return t.frame}setActionSize(t,e){return void 0===e&&(e=t),this.actionWidth=t,this.actionHeight=e,this}preLayout(){var t=this.childrenMap.icon;t&&void 0!==this.iconWidth&&void 0!==this.iconHeight&&Cw(t,this.iconWidth,this.iconHeight);var e=this.childrenMap.action;e&&void 0!==this.actionWidth&&void 0!==this.actionHeight&&Cw(e,this.actionWidth,this.actionHeight),super.preLayout()}postLayout(t,e,i){var s=this.childrenMap.iconMask;s&&(s.setPosition(),this.resetChildPositionState(s));var r=this.childrenMap.actionMask;return r&&(r.setPosition(),this.resetChildPositionState(r)),super.postLayout(t,e,i),this}resize(t,e){super.resize(t,e);var i=this.childrenMap.iconMask;i&&i.resize();var s=this.childrenMap.actionMask;return s&&s.resize(),this}}Object.assign(ww.prototype,kw);var Sw=function(t,e,i,s){var r=new FC(e,i,s);if(t&&!t.isRexSizer){var n=r.createGeometryMask();t.setMask(n),this.once("destroy",(function(){t.setMask(),n.destroy()}))}return this.pin(r),r};const Pw=Phaser.GameObjects.Text;var Tw=function(t){return t instanceof Pw};const Ow=Phaser.GameObjects.BitmapText;var Mw=function(t){return t instanceof Ow},Ew=function(t){return Mw(t)?2:Tw(t)?0:1},_w=function(t,e){for(var i=[],s=t.split("\n"),r=e.style,n=r.wordWrapWidth,a=r.hasOwnProperty("wrapMode")?r.wrapMode:3,o=e.context,h=0,l=s.length;h0&&r.push(h.join("")),r},Lw=function(t,e){switch(Ew(t)){case 0:switch("string"==typeof e&&(e=Be[e]||0),t.style.wrapMode=e,e){case 2:case 3:t.style.wordWrapCallback=_w;break;default:t.style.wordWrapCallback=null}break;case 1:"string"==typeof e&&(e=Be[e]||0),t.style.wrapMode=e}},Bw=function(t,e){return void 0===e&&(e=0),t._minWidth=e,t.runWidthWrap=function(t){return t instanceof hn}(t)?function(t){return function(e){return t.setFixedSize(e,0).runWordWrap(),t.minHeight=t.height,t}}(t):Mw(t)?function(t){return function(e){return t.setMaxWidth(e),t.minHeight=t.height,t}}(t):function(t){return function(e){var i=t.padding,s=e-(i.left+i.right)*t.scaleX,r=t.style;return Tw(t)?(r.wordWrapWidth=s,r.maxLines=0):(0===r.wrapMode&&(r.wrapMode=1),r.wrapWidth=s,r.maxLines=0),r.fixedWidth=e,r.fixedHeight=0,t.updateText(),t.minHeight=t.height,t}}(t),t};const Iw=65535;var Dw=function(t,e,i){if(null==e)return t;if(0===e)return zw(t,0,i),t;var s=t.text.length;if(0===s)return zw(t,e,i),t;var r=Math.floor(1.5*e/s);void 0!==i&&r>i&&(r=Math.floor(i));for(var n={},a=Aw(t,r,e,i,n),o=0;o<=Iw&&0!==a;o++){if((r+=a)<0){r=0;break}a=Aw(t,r,e,i,n)}return o===Iw&&console.warn("FontSizeFit: Test count exceeds 65535"),t.setFontSize(r),zw(t,e,i),t},jw=function(t,e,i){return void 0===i[e]&&(t.setFontSize(e),i[e]={width:t.width,height:t.height}),i[e]},Aw=function(t,e,i,s,r){var n,a=jw(t,e,r),o=jw(t,e+1,r);if(void 0!==s)if(a.height<=s&&o.height>s)n=0;else{if(a.height>s)return-1;n=Math.floor(s-a.height)}if(a.width<=i&&o.width>i)return 0;if(a.width>i)return-1;var h=Math.floor(i-a.width);return void 0===n?h:Math.min(h,n)},zw=function(t,e,i){var s=t.style;s&&(s.fixedWidth=e,s.parent.width=e,void 0!==i&&(s.fixedHeight=i,s.parent.height=i),s.update(!1))};const Fw=Phaser.Utils.Objects.GetValue;var Yw=function(t,e){"number"==typeof e&&(e={minWidth:e});var i=Fw(e,"minWidth",0),s=Fw(e,"minHeight",0),r=Fw(e,"fitHeight",!1);return t._minWidth=i,t._minHeight=s,r?(t.runWidthWrap=function(e){return t.setFixedSize&&t.setFixedSize(0,0),t.setFontSize(1),t},t.resize=function(e,i){return Dw(t,e,i),t}):(t.runWidthWrap=function(e){return t.setFixedSize&&t.setFixedSize(0,0),Dw(t,e,void 0),t},t.resize=function(e,i){return t.width===e&&t.height===i||t.setFixedSize(e,i),t}),t};const Xw=Phaser.Utils.Objects.GetValue;class Ww extends ww{constructor(t,e){void 0===e&&(e={}),super(t,e),this.type="rexLabel";var i,s=Xw(e,"background",void 0),r=Xw(e,"icon",void 0),n=Xw(e,"iconMask",void 0),a=Xw(e,"text",void 0),o=Xw(e,"action",void 0),h=Xw(e,"actionMask",void 0),l=Xw(e,"align",void 0);if(s&&this.addBackground(s),r){0===this.orientation?(a||o)&&(i={right:Xw(e,"space.icon",0),top:Xw(e,"space.iconTop",0),bottom:Xw(e,"space.iconBottom",0),left:Xw(e,"space.iconLeft",0)}):(a||o)&&(i={bottom:Xw(e,"space.icon",0),left:Xw(e,"space.iconLeft",0),right:Xw(e,"space.iconRight",0),top:Xw(e,"space.iconTop",0)});var d=Xw(e,"squareFitIcon",!1)?1:0;if(this.add(r,{proportion:0,padding:i,fitRatio:d}),n&&(n=Sw.call(this,r,r,1)),!d){var c=Xw(e,"iconSize",void 0);this.setIconSize(Xw(e,"iconWidth",c),Xw(e,"iconHeight",c))}}if(a){var u=Xw(e,"wrapText",!1),p=Xw(e,"adjustTextFontSize",!1);u?(!0===u&&(u="word"),Lw(a,u),e.expandTextWidth=!0,Bw(a)):p&&(e.expandTextWidth=!0,e.expandTextHeight=!0,Yw(a,{fitHeight:!0}));var g,v,f=Xw(e,"space.text",0),m=Xw(e,"expandTextWidth",!1),y=Xw(e,"expandTextHeight",!1);0===this.orientation?(g=m?1:0,o&&(i={right:f}),v=y):(g=y?1:0,o&&(i={bottom:f}),v=m),this.add(a,{proportion:g,expand:v,padding:i})}if(o&&(i=0===this.orientation?{top:Xw(e,"space.actionTop",0),bottom:Xw(e,"space.actionBottom",0),right:Xw(e,"space.actionRight",0)}:{left:Xw(e,"space.actionLeft",0),right:Xw(e,"space.actionRight",0),bottom:Xw(e,"space.actionBottom",0)},d=Xw(e,"squareFitAction",!1)?1:0,this.add(o,{proportion:0,padding:i,fitRatio:d}),h&&(h=Sw.call(this,o,o,1)),!d)){var b=Xw(e,"actionSize");this.setActionSize(Xw(e,"actionWidth",b),Xw(e,"actionHeight",b))}this.setChildrenAlignMode(l),this.addChildrenMap("background",s),this.addChildrenMap("icon",r),this.addChildrenMap("iconMask",n),this.addChildrenMap("text",a),this.addChildrenMap("action",o),this.addChildrenMap("actionMask",h)}}const Vw=Phaser.Utils.Objects.GetValue;var Gw=function(t,e){var i=Vw(e,"canvas"),s=Vw(i,"width",128),r=Vw(i,"height",128),n=new Mu(t,0,0,s,r);t.add.existing(n);var a=Vw(i,"key"),o=Vw(i,"frame"),h=Vw(i,"fill");return void 0!==h?n.fill(h):void 0!==a&&n.loadTexture(a,o),n.setTexture=n.loadTexture.bind(n),n};const Hw=Phaser.Utils.Objects.GetValue;var Uw=function(t,e){var i=Hw(e,"clickTarget",this);return"string"==typeof i&&(i=t.getElement(i)),i};const Nw=Phaser.Utils.Objects.GetValue,$w={accept:"image/*",multiple:!1};var Kw=function(t,e){if(0!==e.length){var i=t.childrenMap.icon,s=i.image,r=e[0];return s.loadFromFilePromise(r).then((function(){return i.scaleImage(),t.emit("select",r,t),Promise.resolve(r)}))}},Jw={async openPromise(){var t=this;return Ik(this.scene.game,$w).then((function(e){return Kw(t,e.files)}))},open(){return this.openPromise(),this},setClickOpenEnable(t){return void 0===t&&(t=!0),this.clickBehavior&&this.clickBehavior.setEnable(t),this.fileChooser&&this.fileChooser.setOpenEnable(t),this}},qw={getFileName:function(t){if(!t)return null;var e=t.name;return e.substr(0,e.lastIndexOf("."))},saveTexture:function(t){return this.childrenMap.canvas.generateTexture(t),this}};Object.assign(qw,Jw);const Zw=Phaser.Utils.Objects.GetValue;class Qw extends Ww{constructor(t,e){var i=function(t,e){var i=new mk(t,{scaleUp:Vw(e,"scaleUpIcon",!1),background:Vw(e,"iconBackground"),image:Gw(t,e)});return t.add.existing(i),i}(t,e);e.icon=i,super(t,e),this.type="rexImageFileInputLabel";var s=this.iconWidth,r=this.iconWidth;void 0!==s&&void 0!==r&&i.resize(s,r),this.clickTarget=Uw(this,e),this.clickTarget&&(Zw(e,"domButton",!0)?this.fileChooser=function(t){var e=t.scene,i=new Xk(e,$w);return e.add.existing(i),t.pin(i),i.on("change",(function(){Kw(t,i.files)})),i}(this):this.clickBehavior=function(t,e){var i=Uw(t,e);if(i){var s=Nw(e,"click"),r=new hu(i,s);return r.on("click",t.open,t),r}}(this,e)),this.addChildrenMap("canvas",i.image),this.addChildrenMap("iconBackground",i.background),this.addChildrenMap("fileChooser",this.fileChooser)}postLayout(t,e,i){this.fileChooser&&(this.fileChooser.syncTo(this.clickTarget),this.resetChildState(this.fileChooser)),super.postLayout(t,e,i)}}Object.assign(Qw.prototype,qw),t.register("imageInputLabel",(function(t){var e=new Qw(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ImageInputLabel",Qw);let tS=class extends Ra{constructor(t,e){return super(t),new Proxy(this,this)}get(t,e){if(ae(t,e))return t[e];var i=t.parent;return ae(i,e)?i[e]:void 0}set(t,e,i){return ae(t,e)?t[e]=i:ae(t.parent,e)&&(t.parent[e]=i),!0}get key(){return this.parent.texture.key}set key(t){this.parent.setTexture(t,this.frame)}get frame(){return this.parent.frame.name}set frame(t){this.parent.setFrame(t)}get scale(){return this.parent.scaleX}set scale(t){this.parent.setScale(t)}};const eS=Phaser.Utils.Objects.GetValue;class iS extends Ra{constructor(t,e){super(t,e),this.style=eS(e,"style",this);var i=eS(e,"propertiesMap");this.activeStyle=sS(e,"active",i),this.hoverStyle=sS(e,"hover",i),this.disableStyle=sS(e,"disable",i),this.onModifyStyle=eS(e,"onModifyStyle")}getStyle(t){return Bd(this.style,t)}modifyStyle(t){for(var e in t)this.style[e]=t[e];return this.onModifyStyle&&this.onModifyStyle(this.parent,t),this}applyStyle(t){if(t){var e=this.getStyle(t);return Id(e,t)?void 0:(this.modifyStyle(t),e)}}setActiveState(t){return rS.call(this,"active",t),this}setHoverState(t){return rS.call(this,"hover",t),this}setDisableState(t){return rS.call(this,"disable",t),this}}var sS=function(t,e,i){var s=Rd(t,e);if(i)for(var r in s)i.hasOwnProperty(r)&&(s[i[r]]=s[r],delete s[r]);return s},rS=function(t,e){void 0===e&&(e=!0);var i=`${t}State`,s=`${t}Style`,r=`${t}StyleSave`;this[i]!==e&&(this[i]=e,e?this[r]=this.applyStyle(this[s]):(this.applyStyle(this[r]),this[r]=void 0))},nS={addStyleManager(t){return this.styleManager=new iS(this,t),this},setActiveState(t){return this.styleManager.setActiveState(t),this},setHoverState(t){return this.styleManager.setHoverState(t),this},setDisableState(t){return this.styleManager.setDisableState(t),this}};const aS=Phaser.GameObjects.Image,oS=Phaser.Utils.Objects.GetValue;class hS extends aS{constructor(t,e){void 0===e&&(e={}),super(t,oS(e,"x",0),oS(e,"y",0),oS(e,"key",""),oS(e,"frame",void 0)),this.type="rexStatesImage";var i=oS(e,"effects",!0);i&&Mn(this,i),this.style=new tS(this,e),e.style=this.style,this.addStyleManager(e),delete e.style}}Object.assign(hS.prototype,nS),t.register("statesImage",(function(t){var e=new hS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesImage",hS);class lS extends Dt{constructor(t,e){void 0===e&&(e={}),super(t,e),this.type="rexStatesRoundRectangleShape",e.style=this,e.propertiesMap=dS,this.addStyleManager(e),delete e.style,delete e.propertiesMap}}const dS={color:"fillColor",alpha:"fillAlpha",strokeWidth:"lineWidth"};Object.assign(lS.prototype,nS),t.register("statesRoundRectangle",(function(t){var e=new lS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesRoundRectangle",lS);let cS=class extends Ra{constructor(t,e){return super(t),new Proxy(this,this)}get(t,e){if(ae(t,e))return t[e];var i=t.parent;return ae(i,e)?i[e]:void 0}set(t,e,i){return ae(t,e)?t[e]=i:ae(t.parent,e)&&(t.parent[e]=i),!0}get key(){return this.parent.texture.key}set key(t){this.key!==t&&this.parent.setTexture(t,this.frame)}get frame(){return this.parent.frame.name}set frame(t){this.frame!==t&&this.parent.setFrame(t)}};const uS=Phaser.GameObjects.NineSlice,pS=Phaser.Utils.Objects.GetValue;class gS extends uS{constructor(t,e){void 0===e&&(e={}),super(t,pS(e,"x",0),pS(e,"y",0),pS(e,"key",null),pS(e,"frame",null),pS(e,"width",0),pS(e,"height",0),pS(e,"leftWidth",0),pS(e,"rightWidth",0),pS(e,"topHeight",0),pS(e,"bottomHeight",0)),this.type="rexStatesNineSlice";var i=pS(e,"effects",!0);i&&Mn(this,i),this.style=new cS(this,e),e.style=this.style,this.addStyleManager(e),delete e.style}}Object.assign(gS.prototype,nS),t.register("statesNineSlice",(function(t){var e=new gS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesNineSlice",gS);let vS=class extends Ra{constructor(t,e){return super(t),new Proxy(this,this)}get(t,e){if(ae(t,e))return t[e];var i=t.parent;return ae(i,e)?i[e]:void 0}set(t,e,i){return ae(t,e)?t[e]=i:ae(t.parent,e)&&(t.parent[e]=i),!0}get key(){return this.parent.textureKey}set key(t){this.key!==t&&this.parent.setBaseTexture(t,this.baseFrameName)}get frame(){return this.parent.baseFrameName}set frame(t){this.frame!==t&&this.parent.setBaseTexture(this.parent.textureKey,t)}};const fS=Phaser.Utils.Objects.GetValue;class mS extends k{constructor(t,e){void 0===e&&(e={}),super(t,e),this.type="rexStatesNinePatch";var i=fS(e,"effects",!0);i&&Mn(this,i),this.style=new vS(this,e),e.style=this.style,this.addStyleManager(e),delete e.style}}Object.assign(mS.prototype,nS),t.register("statesNinePatch",(function(t){var e=new mS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesNinePatch",mS);const yS=Phaser.GameObjects.Text,bS=Phaser.Utils.Objects.GetValue;class xS extends yS{constructor(t,e){void 0===e&&(e={}),super(t,bS(e,"x",0),bS(e,"y",0),bS(e,"text",""),e),this.type="rexStatesText",e.style=this.style,e.onModifyStyle=function(t,e){var i=e.hasOwnProperty("fontStyle")||e.hasOwnProperty("fontSize")||e.hasOwnProperty("fontFamily");t.style.update(i)},this.addStyleManager(e),delete e.style}}Object.assign(xS.prototype,nS),t.register("statesText",(function(t){var e=new xS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesText",xS);class CS extends Ra{constructor(t,e){return super(t),new Proxy(this,this)}get(t,e){if(ae(t,e))return t[e];var i=t.parent;return ae(i,e)?i[e]:void 0}set(t,e,i){return ae(t,e)?t[e]=i:ae(t.parent,e)&&(t.parent[e]=i),!0}get key(){return this.parent.texture.key}set key(t){this.parent.setTexture(t,this.frame)}get fontSize(){return this.parent.fontSize}set fontSize(t){this.parent.setFontSize(t)}get tint(){return this.parent.tintTopLeft}set tint(t){this.parent.setTint(t)}get letterSpacing(){return this.parent.letterSpacing}set letterSpacing(t){this.parent.setLetterSpacing(t)}get lineSpacing(){return this.parent.lineSpacing}set lineSpacing(t){this.parent.setLineSpacing(t)}}const kS=Phaser.GameObjects.BitmapText,wS=Phaser.Utils.Objects.GetValue;class SS extends kS{constructor(t,e){void 0===e&&(e={});var i=wS(e,"x",0),s=wS(e,"y",0),r=wS(e,"font",""),n=wS(e,"fontSize",!1),a=wS(e,"align",0),o=wS(e,"tint");super(t,i,s,r,"",n,a),this.type="rexStatesBitmapText",void 0!==o&&this.setTint(o);var h=wS(e,"effects",!0);h&&Mn(this,h),this.style=new CS(this,e),e.style=this.style,this.addStyleManager(e),delete e.style}}Object.assign(SS.prototype,nS),t.register("statesBitmapText",(function(t){var e=new SS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesBitmapText",SS);class PS extends dp{constructor(t,e){void 0===e&&(e={}),e.hasOwnProperty("value")||(e.value=0),e.hasOwnProperty("hover.bar")||(e["hover.bar"]=!0),e.hasOwnProperty("easeDuration")||(e.easeDuration=200),e.hasOwnProperty("ease")||(e.ease="Quad"),P(e,"easeValue.duration",e.easeDuration),P(e,"easeValue.ease",e.ease),super(t,e),this.type="rexStatesBarRectangleShape",this.barState=!1,e.style=this,e.propertiesMap=TS,this.addStyleManager(e),delete e.style,delete e.propertiesMap}get bar(){return this.barState}set bar(t){t=!!t,this.barState!==t&&(this.barState=t,this.easeValueTo(this.barState?1:0))}}const TS={color:"trackColor",strokeColor:"trackStrokeColor",strokeWidth:"trackStrokeThickness"};Object.assign(PS.prototype,nS),t.register("statesBarRectangle",(function(t){var e=new PS(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.StatesBarRectangle",PS);var OS=function(t,e){void 0===e&&(e={}),void 0===e.options&&(e.options={});var i=e.options;i.responsive=!1,i.maintainAspectRatio=!1,i.hasOwnProperty("devicePixelRatio")||(i.devicePixelRatio=1);var s=!1;void 0===i.animation?i.animation={}:!1===i.animation&&(s=!0,i.animation={});var r=i.animation;s&&(r.duration=0);var n=r.onProgress;r.onProgress=function(e){n&&n(e),t.needRedraw()};var a=r.onComplete;return r.onComplete=function(e){a&&a(e),t.needRedraw()},e};let MS=class extends Mu{constructor(t,e,i,s,r,n){super(t,e,i,s,r),this.type="rexChart",this.chart=void 0,void 0!==n&&this.setChart(n)}destroy(t){this.scene&&(this.chart&&(this.chart.destroy(),this.chart=void 0),super.destroy(t))}resize(t,e){if(t===this.width&&e===this.height)return this;if(super.resize(t,e),this.chart){var i=this.chart;i.height=this.canvas.height,i.width=this.canvas.width,i.aspectRatio=i.height?i.width/i.height:null,i.update()}return this}};var ES={setChart:function(t){return window.Chart?(this.chart&&this.chart.destroy(),this.chart=new Chart(this.context,OS(this,t)),this):(console.error("Can not find chartjs! Load chartjs in preload stage.\nscene.load.script('chartjs', 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/Chart.min.js');"),this)},getChartDataset:function(t){if(void 0!==this.chart){if("string"!=typeof t)return this.chart.data.datasets[t];for(var e,i=this.chart.data.datasets,s=0,r=i.length;s=0;e--){var i=this.sizerChildren[e];i&&this.remove(i,t)}return this},clear(t){return AS(this.sizerChildren,null),Ib.call(this,t),this}},FS={setColumnSpace(t){if(this.space.column||(this.space.column=[]),this.space.column.length=this.columnCount-1,"number"==typeof t)AS(this.space.column,t);else for(var e=0,i=this.columnCount-1;e=0;s--){var r=s*this.columnCount+t;this.sizerChildren.splice(r,0,null)}return this.columnProportions.push(e),this.columnWidth.length+=1,this.space.column.splice(t,0,i),this},VS={getChildrenWidth:function(t){if(this.rexSizer.hidden)return 0;void 0===t&&(t=!0);var e,i,s,r,n,a=0,o=this.sizerChildren,h=!1;this.totalColumnProportions;for(var l=0;l0){var i=t-this.getChildrenWidth(!1);i>=0&&(this.proportionWidthLength=i/e)}else this.proportionWidthLength=0}return t},resolveHeight:function(t){if(void 0!==(t=Bv.call(this,t))&&void 0===this.proportionHeightLength){var e=this.totalRowProportions;if(e>0){var i=t-this.getChildrenHeight(!1);i>=0&&(this.proportionHeightLength=i/e)}else this.proportionHeightLength=0}return t},resolveChildrenWidth:function(t){var e,i,s,r;for(var n in this.sizerChildren)(e=this.sizerChildren[n])&&e.isRexSizer&&!e.ignoreLayout&&(r=this.getColumnWidth(parseInt(n)%this.columnCount),i=this.getExpandedChildWidth(e,r),void 0===(s=e.resolveWidth(i))&&(s=i),e.resolveChildrenWidth(s))},resolveChildrenHeight:function(t){var e,i,s,r;for(var n in this.sizerChildren)(e=this.sizerChildren[n])&&e.isRexSizer&&!e.ignoreLayout&&(r=this.getRowHeight(Math.floor(parseInt(n)/this.rowCount)),i=this.getExpandedChildHeight(e,r),void 0===(s=e.resolveHeight(i))&&(s=i),e.resolveChildrenHeight(s))},runWidthWrap:function(t){var e,i,s,r;for(var n in this.sizerChildren)!(e=this.sizerChildren[n])||e.isRexSizer&&e.ignoreLayout||!e.runWidthWrap||(r=this.getColumnWidth(parseInt(n)%this.columnCount),i=this.getExpandedChildWidth(e,r),e.isRexSizer&&void 0===(s=e.resolveWidth(i))&&(s=i),e.runWidthWrap(s));return this},runHeightWrap:function(t){var e,i,s,r;for(var n in this.sizerChildren)!(e=this.sizerChildren[n])||e.isRexSizer&&e.ignoreLayout||!e.runHeightWrap||(r=this.getRowHeight(Math.floor(parseInt(n)/this.rowCount)),i=this.getExpandedChildHeight(e,r),e.isRexSizer&&void 0===(s=e.resolveHeight(i))&&(s=i),e.runHeightWrap(s));return this},resetGrid:function(t,e,i,s,r){if(void 0===i&&(i=0),void 0===s&&(s=0),this.columnCount=t,this.rowCount=e,this.gridCount=t*e,this.removeAll(),this.sizerChildren.length=t*e,AS(this.sizerChildren,null),this.columnProportions=[],this.columnProportions.length=t,"number"==typeof i)AS(this.columnProportions,i);else for(var n=0;n0?e+=t:0===t&&(this.hasColumnProportion0Child=!0);return e},HS=function(){for(var t,e=0,i=0;i0?e+=t:0===t&&(this.hasRowProportion0Child=!0);return e};const US=Phaser.Utils.Objects.IsPlainObject,NS=Phaser.Utils.Objects.GetValue;class $S extends Cb{constructor(t,e,i,s,r,n,a,o,h,l){US(e)?(e=NS(l=e,"x",0),i=NS(l,"y",0),s=NS(l,"width",void 0),r=NS(l,"height",void 0),n=NS(l,"column",l.col||0),a=NS(l,"row",0),o=NS(l,"columnProportions",0),h=NS(l,"rowProportions",0)):US(s)?(s=NS(l=s,"width",void 0),r=NS(l,"height",void 0),n=NS(l,"column",l.col||0),a=NS(l,"row",0),o=NS(l,"columnProportions",0),h=NS(l,"rowProportions",0)):US(n)?(n=NS(l=n,"column",l.col||0),a=NS(l,"row",0),o=NS(l,"columnProportions",0),h=NS(l,"rowProportions",0)):US(o)&&(o=NS(l=o,"columnProportions",0),h=NS(l,"rowProportions",0)),super(t,e,i,s,r,l),this.type="rexGridSizer",this.sizerChildren=[],this.addChildrenMap("items",this.sizerChildren),this.setCreateCellContainerCallback(NS(l,"createCellContainerCallback")),this.setIndentLeft(NS(l,"space.indentLeftOdd",0),NS(l,"space.indentLeftEven",0)),this.setIndentTop(NS(l,"space.indentTopOdd",0),NS(l,"space.indentTopEven",0)),this.resetGrid(n,a,o,h,NS(l,"space",void 0))}destroy(t){this.scene&&!this.ignoreDestroy&&(super.destroy(t),this.columnProportions=void 0,this.rowProportions=void 0,this.columnWidth=void 0,this.rowHeight=void 0,this.createCellContainerCallback=void 0)}setColumnProportion(t,e){return t>=this.columnProportions.length||(this.columnProportions[t]=e),this}setRowProportion(t,e){return t>=this.rowProportions.length||(this.rowProportions[t]=e),this}get totalColumnProportions(){return void 0===this._totalColumnProportions&&(this._totalColumnProportions=GS.call(this)),this._totalColumnProportions}get totalRowProportions(){return void 0===this._totalRowProportions&&(this._totalRowProportions=HS.call(this)),this._totalRowProportions}getChildAt(t,e){return this.sizerChildren[e*this.columnCount+t]}childToGridIndex(t,e){if(!t)return null;var i=this.sizerChildren.indexOf(t);return-1===i?null:(void 0===e&&(e={}),e.x=i%this.columnCount,e.y=Math.floor(i/this.columnCount),e)}getColumnWidth(t){var e=this.columnProportions[t];return 0===e?this.columnWidth[t]:e*this.proportionWidthLength}getRowHeight(t){var e=this.rowProportions[t];return 0===e?this.rowHeight[t]:e*this.proportionHeightLength}setCreateCellContainerCallback(t){return this.createCellContainerCallback=t,this}}Object.assign($S.prototype,VS),t.register("gridSizer",(function(t,e,i,s,r,n,a,o,h){var l=new $S(this.scene,t,e,i,s,r,n,a,o,h);return this.scene.add.existing(l),l})),P(window,"RexPlugins.UI.GridSizer",$S);var KS=function(t,e,i,s){return e/t<=i?e/(s-1):0},JS=function(t){var e,i,s,r,n,a={lines:[],width:0,height:0},o=this.sizerChildren,h=0,l=a.lines,d=void 0;if(0===this.orientation){for(var c=0,u=o.length;co.height/2)){r>(h=qS(o.left,o.centerY,t,e))&&(r=h,s=n);var h,l=i[n+1];l&&l.y===o.y||r>(h=qS(o.right,o.centerY,t,e))&&(r=h,s=n+1)}}return s};const QS=Phaser.Utils.Objects.IsPlainObject,tP=Phaser.Utils.Objects.GetValue,eP=Phaser.Display.Align.CENTER;var iP=function(t,e,i,s){return"\n"===t?(this.addNewLine(),this):(fv.call(this,t),QS(e)&&(e=tP(r=e,"padding",0),i=tP(r,"key",void 0),s=tP(r,"index",void 0)),void 0===e&&(e=0),(r=this.getSizerConfig(t)).align=eP,r.padding=gv(e),void 0===s||s>=this.sizerChildren.length?this.sizerChildren.push(t):this.sizerChildren.splice(s,0,t),void 0!==i&&this.addChildrenMap(i,t),this);var r},sP={add(t,e,i){if(Tm(t))for(var s=t,r=0,n=s.length;r=0;e--)this.remove(this.sizerChildren[e],t);return this},clear(t){return this.sizerChildren.length=0,Ib.call(this,t),this}},aP={getChildrenWidth:function(t){return this.rexSizer.hidden?0:(void 0===t&&(t=!0),void 0!==(e=0===this.orientation&&t?this.maxChildWidth:this.rexSizer.resolved?this.wrapResult.width:void 0)?e+(this.space.left+this.space.right)*this.scaleX:void 0);var e},getChildrenHeight:function(t){return this.rexSizer.hidden?0:(void 0===t&&(t=!0),void 0!==(e=1===this.orientation&&t?this.maxChildHeight:this.rexSizer.resolved?this.wrapResult.height:void 0)?e+(this.space.top+this.space.bottom)*this.scaleY:void 0);var e},getChildrenSizers:function(t){void 0===t&&(t=[]);for(var e,i=this.sizerChildren,s=0,r=i.length;s=t.dragThreshold?"DRAG":"DRAGBEGIN":"IDLE"}update_DRAGBEGIN(t,e){this.next()}next_DRAG(){var t,e=this.parent;return e.dragState.isUp&&(t=e.outOfBounds?"BACK":e.slidingEnable?"SLIDE":"IDLE"),t}update_DRAG(t,e){var i=this.parent;i.dragState.justMoved&&i.dragging(),this.next()}enter_DRAG(){this.parent.onDragStart()}exit_DRAG(){this.parent.onDragEnd()}next_SLIDE(){var t,e=this.parent;return e.dragState.isDown?t="DRAG":e.isSliding||(t="IDLE"),t}enter_SLIDE(){this.parent.onSliding()}exit_SLIDE(){this.parent.stop()}update_SLIDE(t,e){this.parent.sliding(t,e),this.next()}next_BACK(){var t,e=this.parent;return e.dragState.isDown?t="DRAG":e.isPullBack||(t="IDLE"),t}enter_BACK(){this.parent.onPullBack()}exit_BACK(){this.parent.stop()}update_BACK(t,e){this.parent.pullBack(t,e),this.next()}}const JP=Phaser.Utils.Objects.GetValue,qP=Phaser.Math.Distance.Between;class ZP extends Ra{constructor(t,e){super(t,e),this._enable=void 0,this.rectBoundsInteractive=JP(e,"rectBoundsInteractive",!1),this.rectBoundsInteractive||t.setInteractive(JP(e,"inputConfig",void 0)),this.resetFromJSON(e),this.boot()}resetFromJSON(t){return this.pointer=void 0,this.isInTouched=!1,this.holdStartTime=void 0,this.x=void 0,this.y=void 0,this.preX=void 0,this.preY=void 0,this.localX=void 0,this.localY=void 0,this.justMoved=!1,this.setEnable(JP(t,"enable",!0)),this.holdThreshold=JP(t,"holdThreshold",50),this.pointerOutReleaseEnable=JP(t,"pointerOutRelease",!0),this}boot(){var t=this.scene,e=this.parent;this.rectBoundsInteractive?(t.input.on("pointerdown",this.onPointIn,this),t.input.on("pointerup",this.onPointOut,this),t.input.on("pointermove",this.onPointerMove,this)):(e.on("pointerdown",this.onPointIn,this),e.on("pointerup",this.onPointOut,this),this.pointerOutReleaseEnable&&e.on("pointerout",this.onPointOut,this),e.on("pointermove",this.onPointerMove,this)),t.sys.events.on("preupdate",this.preupdate,this)}shutdown(t){if(!this.isShutdown){var e=this.scene;this.parent,this.rectBoundsInteractive&&(e.input.off("pointerdown",this.onPointIn,this),e.input.off("pointerup",this.onPointOut,this),e.input.off("pointermove",this.onPointerMove,this)),e.sys.events.off("preupdate",this.preupdate,this),this.pointer=void 0,super.shutdown(t)}}get enable(){return this._enable}set enable(t){this._enable!==t&&(t||(this.isInTouched=!1,this.pointer=void 0),this._enable=t)}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}toggleEnable(){return this.setEnable(!this.enable),this}setPointerOutReleaseEnable(t){return void 0===t&&(t=!0),this.pointerOutReleaseEnable=t,this}get isDown(){return this.pointer&&this.pointer.isDown}get isUp(){return!this.isDown}get dx(){return this.x-this.preX}get dy(){return this.y-this.preY}get dt(){return rc(this.scene)}get speed(){return this.x===this.preX&&this.y===this.preY?0:qP(this.preX,this.preY,this.x,this.y)/(.001*this.dt)}get speedX(){return this.dx/(.001*this.dt)}get speedY(){return this.dy/(.001*this.dt)}onPointIn(t,e,i){this.enable&&t.isDown&&void 0===this.pointer&&(this.rectBoundsInteractive&&!Pm(this.parent,t)||(this.pointer=t,this.localX=e,this.localY=i))}onPointOut(t){this.enable&&this.pointer===t&&(this.pointer=void 0)}onPointerMove(t,e,i){this.enable&&t.isDown&&this.pointer===t&&(this.rectBoundsInteractive&&this.pointerOutReleaseEnable&&!Pm(this.parent,t)?this.onPointOut(t):(this.localX=e,this.localY=i))}preupdate(t,e){if(this.enable){var i=this.pointer;this.justMoved=!1,i&&!this.isInTouched?(this.x=i.worldX,this.y=i.worldY,this.preX=i.worldX,this.preY=i.worldY,this.isInTouched=!0,this.holdStartTime=void 0,this.emit("touchstart",i,this.localX,this.localY)):i&&this.isInTouched?this.x===i.x&&this.y===i.y?void 0===this.holdStartTime?this.holdStartTime=t:t-this.holdStartTime>this.holdThreshold&&(this.preX=this.x,this.preY=this.y):(this.preX=this.x,this.preY=this.y,this.x=i.worldX,this.y=i.worldY,this.holdStartTime=void 0,this.justMoved=!0,this.emit("touchmove",i,this.localX,this.localY)):!i&&this.isInTouched&&(this.isInTouched=!1,this.holdStartTime=void 0,this.emit("touchend",i))}}}const QP=Phaser.Utils.Objects.GetValue;class tT{constructor(t){this.resetFromJSON(t)}resetFromJSON(t){return this.setValue(QP(t,"value",0)),this.setSpeed(QP(t,"speed",0)),this.setAcceleration(QP(t,"acceleration",0)),this}reset(){this.setValue(0),this.setSpeed(0),this.setAcceleration(0)}setValue(t){return this.value=t,this}setSpeed(t){return this.speed=t,this}setAcceleration(t){return this.acceleration=t,this}updateSpeed(t){return 0!==this.acceleration&&(this.speed+=this.acceleration*t,this.speed<0&&(this.speed=0)),this}getDeltaValue(t){return this.updateSpeed(t),this.speed<=0?0:this.speed*t}update(t){return this.updateSpeed(t),this.speed>0&&(this.value+=this.getDeltaValue(t)),this}get isMoving(){return this.speed>0}}class eT{constructor(){this.value,this.dir,this.movement=new tT}init(t,e,i,s,r){return this.value=t,this.end=r,this.dir=void 0!==r?tthis.end&&(this.value=this.end):this.valuethis.maxValue}overMin(t){return null!=this.minValue&&t0,Math.abs(e),i)}sliding(t,e){e*=.001;var i=this._slowDown.update(e).value;this.overMax(i)?(this.value=this.maxValue,this._slowDown.stop()):this.overMin(i)?(this.value=this.minValue,this._slowDown.stop()):this.value=i}onPullBack(){var t=this.value,e=this.outOfMinBound?this.minValue:this.maxValue,i=Math.abs(e-t),s=this.backDeceleration,r=Math.sqrt(2*s*i);this._slowDown.init(t,void 0,r,s,e)}pullBack(t,e){e*=.001,this.value=this._slowDown.update(e).value,this._slowDown.isMoving||this._state.next()}stop(){this._slowDown.stop()}}const nT={y:0,v:0,vertical:0,x:1,h:1,horizontal:1},aT=Phaser.Utils.Objects.GetValue;class oT extends Ra{constructor(t,e){switch(super(t,e),this.parent!==this.scene?this.focusMode=aT(e,"focus",!0):this.focusMode=!1,"boolean"==typeof this.focusMode&&(this.focusMode=this.focusMode?1:0),this.setSpeed(aT(e,"speed",.1)),this.setEnable(aT(e,"enable",!0)),this.focusMode){case 0:case 2:this.scene.input.on("wheel",this.onSceneScroll,this);break;default:t.setInteractive(aT(e,"inputConfig",void 0)).on("wheel",(function(t,e,i,s,r){this.tryScroll(i)}),this)}}destroy(){switch(this.focusMode){case 0:case 2:this.scene.input.off("wheel",this.onSceneScroll,this)}}onSceneScroll(t,e,i,s,r,n){(2!==this.focusMode||Pm(this.parent,t))&&this.tryScroll(s)}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}setSpeed(t){return this.speed=t,this}tryScroll(t){if(this.enable)return this.scroll(t),this}scroll(t){return t*=this.speed,this.emit("scroll",t,this.parent,this),this}}const hT=Phaser.Utils.Objects.GetValue;var lT=function(t,e,i,s){var r,n,a="Y"===(i=i.toUpperCase()),o=2===t.scrollMode,h=t.childrenMap.child,l=`slider${i}`;if(r=o||s.hasOwnProperty(l)?hT(s,l,void 0):hT(s,"slider",void 0)){var d,c,u;!0===r&&(r={}),r.orientation=a?1:0,n=function(t,e){void 0===e&&(e={});var i=Ve(e);(e={slider:i}).orientation=i.orientation,delete i.orientation,e.background=i.background,delete i.background,e.buttons=i.buttons,delete i.buttons,e.value=null;var s=new $P(t,e);t.add.existing(s);var r=s.childrenMap.slider;return s.addChildrenMap("track",r.childrenMap.track),s.addChildrenMap("indicator",r.childrenMap.indicator),s.addChildrenMap("thumb",r.childrenMap.thumb),s}(t.scene,r);var p=hT(r,"position",0);"string"==typeof p&&(p=dT[p]);var g,v,f=hT(s,`space.slider${i}`,void 0);void 0===f&&void 0===(f=hT(s,"space.slider",void 0))&&(o?f=0:g=hT(s,"space.child",0)),v=void 0===g?"number"==typeof f:"number"==typeof g,a?0===p?(d=2,c=1,u=void 0===g?v?{left:f}:f:{left:hT(g,"right",g)}):(d=0,c=1,u=void 0===g?v?{right:f}:f:{right:hT(g,"left",g)}):0===p?(d=1,c=2,u=void 0===g?v?{top:f}:f:{top:hT(g,"bottom",g)}):(d=1,c=0,u=void 0===g?v?{bottom:f}:f:{bottom:hT(g,"top",g)}),e.add(n,{column:d,row:c,align:"center",padding:u,expand:!0}),t[`hideUnscrollableSlider${i}`]=hT(r,"hideUnscrollableSlider",!1),t[`adaptThumb${i}SizeMode`]=hT(r,"adaptThumbSize",!1),t[`minThumb${i}Size`]=hT(r,"minThumbSize",void 0)}else t[`hideUnscrollableSlider${i}`]=!1,t[`adaptThumb${i}SizeMode`]=!1,t[`minThumb${i}Size`]=void 0;var m,y,b=hT(s,"scrollDetectionMode");"string"==typeof b&&(b=cT[b]);var x=`scroller${i}`;(m=o||s.hasOwnProperty(x)?hT(s,x,!0):hT(s,"scroller",!0))&&h&&(!0===m&&(m={}),m.orientation=a?0:1,void 0!==b&&(m.rectBoundsInteractive=1===b),y=new rT(h,m),h.isRexContainerLite&&h.sendChildToBack(h));var C,k,w,S,P,T=hT(s,o?`mouseWheelScroller${i}`:"mouseWheelScroller",!1);T&&h&&(void 0!==b&&(T.focus=1===b?2:0),C=new oT(h,T)),t.addChildrenMap(`slider${i}`,n),t.addChildrenMap(`scroller${i}`,y),t.addChildrenMap(`mouseWheelScroller${i}`,C),o&&!a||(t.hideUnscrollableSlider=t[`hideUnscrollableSlider${i}`],t.adaptThumbSizeMode=t[`adaptThumb${i}SizeMode`],t.minThumbSize=t[`minThumb${i}Size`],t.addChildrenMap("slider",n),t.addChildrenMap("scroller",y),t.addChildrenMap("mouseWheelScroller",C)),n&&(o?(k=a?"t":"s",S=`scroll${i}`):(k="t",S="scroll"),n.on("valuechange",(function(e){t[k]=e,t.emit(S,t)}))),y&&(o?(w=`childO${i}`,S=`scroll${i}`):(w="childOY",S="scroll"),y.on("valuechange",(function(e){t[w]=e,t.emit(S,t)}))),C&&(P=o?`addChildO${i}`:"addChildOY",C.on("scroll",(function(e){t[P](-e,!0)})))};const dT={right:0,left:1,bottom:0,top:1},cT={gameObject:0,rectBounds:1},uT=Phaser.Utils.Objects.GetValue;var pT=function(t,e){var i=t.scene,s=[0,1,0],r=[0,1,0],n=uT(e,"width"),a=uT(e,"height");n||uT(e,"child.expandWidth",!0)||(s[1]=0),a||uT(e,"child.expandHeight",!0)||(r[1]=0);var o=new $S(i,{column:3,row:3,columnProportions:s,rowProportions:r});switch(function(t,e,i){var s=bP(i,"child"),r=bP(s,"gameObject",void 0);if(r){var n=bP(i,"space.child",0);t.childMargin={};var a=t.childMargin,o={};if("number"==typeof n)switch(t.scrollMode){case 0:case 1:a.top=0,a.bottom=0,a.left=0,a.right=0;break;default:a.top=n,a.bottom=n,a.left=n,a.right=n}else switch(t.scrollMode){case 0:a.top=bP(n,"top",0),a.bottom=bP(n,"bottom",0),o.left=bP(n,"left",0),o.right=bP(n,"right",0);break;case 1:a.top=bP(n,"left",0),a.bottom=bP(n,"right",0),o.top=bP(n,"top",0),o.bottom=bP(n,"bottom",0);break;default:a.top=bP(n,"top",0),a.bottom=bP(n,"bottom",0),a.left=bP(n,"left",0),a.right=bP(n,"right",0)}e.add(r,{column:1,row:1,align:bP(s,"align","center"),padding:o,expand:{width:bP(s,"expandWidth",!0),height:bP(s,"expandHeight",!0)}})}t.addChildrenMap("child",r)}(t,o,e),t.scrollMode){case 0:lT(t,o,"y",e);break;case 1:lT(t,o,"x",e);break;default:lT(t,o,"y",e),lT(t,o,"x",e)}return o},gT=function(t){var e,i,s,r;switch(this.scrollMode){case 0:case 1:e=this.topChildOY,i=this.bottomChildOY,s=this.childrenMap.scroller,r=this.childrenMap.slider,t=0===this.scrollMode?"Y":"X";break;default:"Y"===(t=t.toUpperCase())?(e=this.topChildOY,i=this.bottomChildOY):(e=this.leftChildOX,i=this.rightChildOX),s=this.childrenMap[`scroller${t}`],r=this.childrenMap[`slider${t}`]}if(s){var n="Y"===t?this.scaleY:this.scaleX;s.setBounds(e,i*n)}r&&r.setEnable(e!==i)},vT=function(t){switch(this.scrollMode){case 0:case 1:(e=this.childrenMap.slider)&&this.hideUnscrollableSlider&&this.setChildVisible(e,this.isOverflow);break;default:t=t.toUpperCase();var e=this.childrenMap[`slider${t}`],i=this[`hideUnscrollableSlider${t}`],s=this[`isOverflow${t}`];e&&i&&this.setChildVisible(e,s)}},fT=function(t){switch(this.scrollMode){case 0:case 1:if(!this.adaptThumbSizeMode)return;if(!(o=this.childrenMap.slider))return;var e=Math.min(this.childVisibleHeight/this.childHeight,1),i=o.childrenMap.track,s=o.childrenMap.thumb,r=this.minThumbSize;if(0===this.scrollMode){var n=i.displayHeight*e;void 0!==r&&n0?t.setText(e).getTextBounds().wrappedText.split("\n"):e.split("\n")}return i},wT=function(t){return(t-this.textLineSpacing)/(this.textLineHeight+this.textLineSpacing)},ST=function(t){return t*(this.textLineHeight+this.textLineSpacing)-this.textLineSpacing},PT=function(t){var e,i=t+this.visibleLinesCount+1;switch(this.textObjectType){case 0:case 2:e=this.lines.slice(t,i).join("\n");break;case 1:var s=this.lines.getLineStartIndex(t),r=this.lines.getLineEndIndex(i-1);e=this.lines.getSliceTagText(s,r,!0)}return e},TT=function(t,e){switch(Ew(t)){case 0:var i=(r=t.style).wordWrapWidth,s=r.wordWrapCallback;r.wordWrapWidth=0,r.wordWrapCallback=void 0,t.setText(e),r.wordWrapWidth=i,r.wordWrapCallback=s;break;case 1:var r,n=(r=t.style).wrapMode;r.wrapMode=0,t.setText(e),r.wrapMode=n;break;case 2:var a=t._maxWidth;t._maxWidth=0,t.setText(e),t._maxWidth=a}},OT=function(){var t=this.textObject.rexSizer;this.textObject.y+=t.offsetY-t.preOffsetY,t.preOffsetY=t.offsetY,this.resetChildPositionState(this.textObject),this.textCropEnable&&MT.call(this)},MT=function(){if(this.textObject.setCrop){var t,e,i=this.textObject.rexSizer.offsetY;i<=0?(t=-i,e=this.height):(t=0,e=this.height-i),this.textObject.setCrop(0,t,this.width,e)}},ET=function(t,e,i){if(i+=this.textLineHeight+this.textLineSpacing,this.textObjectWidth!==e||this._textObjectRealHeight!==i){switch(this.textObjectWidth=e,this._textObjectRealHeight=i,this.textObjectType){case 0:case 1:t.setFixedSize(e,i);var s=t.style,r=Math.max(e,0);0===this.textObjectType?s.wordWrapWidth=r:(0===s.wrapMode&&(s.wrapMode=1),s.wrapWidth=r);break;case 2:t.setMaxWidth(e)}this.setText()}},_T={setText:function(t){return void 0!==t&&(this.text=t),this.lines=kT(this.textObject,this.text,this.lines),this.linesCount=this.lines.length,this._textHeight=void 0,this._textVisibleHeight=void 0,this.updateTextObject(),this},updateTextObject:function(){var t=Math.max(Math.floor(wT.call(this,-this.textOY)),0),e=ST.call(this,t)+this.textOY,i=PT.call(this,t);return TT(this.textObject,i),this.textObject.rexSizer.offsetY=e,OT.call(this),this},preLayout:function(){return this._textLineHeight=void 0,this._textLineSpacing=void 0,this._visibleLinesCount=void 0,this._textHeight=void 0,this._textVisibleHeight=void 0,Av.call(this),this},layoutChildren:function(){var t,e,i,s,r,n,a,o=this.left,h=this.top;(t=this.textObject).rexSizer.hidden||(s=o+(i=(e=t.rexSizer).padding).left*this.scaleX,r=h+i.top*this.scaleY,n=this.width*this.scaleX-(i.left+i.right)*this.scaleX,a=this.height*this.scaleY-(i.top+i.bottom)*this.scaleY,ET.call(this,t,n,a),hv(t,s,r,n,a,e.align),e.preOffsetY=0,OT.call(this),this.textMask&&(this.textMask.setPosition().resize(),this.resetChildPositionState(this.textMask)))}};const RT=Phaser.Utils.Objects.IsPlainObject,LT=Phaser.Utils.Objects.GetValue,BT=Phaser.Display.Align.TOP_LEFT;class IT extends Cb{constructor(t,e,i,s,r,n){RT(e)?(e=LT(n=e,"x",0),i=LT(n,"y",0),s=LT(n,"width",void 0),r=LT(n,"height",void 0)):RT(s)&&(s=LT(n=s,"width",void 0),r=LT(n,"height",void 0)),super(t,e,i,s,r,n),this.type="rexTextBlock",this.textObject=void 0,this.linesCount=0,this.textMask=void 0,this.textObjectType=void 0,this._textLineHeight=void 0,this._textLineSpacing=void 0,this._visibleLinesCount=void 0,this._textHeight=void 0,this._textVisibleHeight=void 0,this._textObjectRealHeight=0,this.lines=void 0,this.text=LT(n,"content",""),this._textOY=0,this.execeedTopState=!1,this.execeedBottomState=!1,this.setClampMode(LT(n,"clampTextOY",!0)),this.alwaysScrollable=LT(n,"alwaysScrollable",!1);var a=LT(n,"background",void 0),o=LT(n,"text",void 0);void 0===o&&(o=DT(t)),this.textCropEnable=LT(n,"textCrop",!!o.setCrop);var h=LT(n,"textMask",!this.textCropEnable);a&&this.addBackground(a),this.add(o),this.sizerChildren=[o];var l=this.getSizerConfig(o);l.align=BT,l.padding=gv(0),l.expand=!0,this.textObject=o,this.textObjectType=Ew(o),l.preOffsetY=0,l.offsetY=0,h&&(this.textMask=Sw.call(this,this.textObject,this)),this.addChildrenMap("background",a),this.addChildrenMap("text",o)}destroy(t){if(this.scene&&!this.ignoreDestroy){if(this.textObject=void 0,this.textMask=void 0,this.lines){switch(this.textObjectType){case 0:case 2:this.lines.length=0;break;case 1:this.lines.destroy()}this.lines=void 0}super.destroy(t)}}setClampMode(t){return void 0===t&&(t=!0),this.clampTextOY=t,this}get textLineHeight(){if(void 0===this._textLineHeight){var t;switch(this.textObjectType){case 0:case 1:var e=this.textObject.style;t=e.metrics.fontSize+e.strokeThickness;break;case 2:var i=this.textObject.fontSize/this.textObject.fontData.size;t=this.textObject.fontData.lineHeight*i}this._textLineHeight=t}return this._textLineHeight}get textLineSpacing(){if(void 0===this._textLineSpacing){var t;switch(this.textObjectType){case 0:case 1:t=this.textObject.lineSpacing;break;case 2:t=0}this._textLineSpacing=t}return this._textLineSpacing}get visibleLinesCount(){return void 0===this._visibleLinesCount&&(this._visibleLinesCount=Math.floor(wT.call(this,this._textObjectRealHeight))),this._visibleLinesCount}get topTextOY(){return 0}get bottomTextOY(){return-this.textVisibleHeight}get textHeight(){return void 0===this._textHeight&&(this._textHeight=ST.call(this,this.linesCount)),this._textHeight}get textObjectHeight(){return this._textObjectRealHeight-(this.textLineHeight+this.textLineSpacing)}get textVisibleHeight(){if(void 0===this._textVisibleHeight){var t=this.textHeight-this.textObjectHeight;!this.alwaysScrollable&&t<0&&(t=0),this._textVisibleHeight=t}return this._textVisibleHeight}textOYExceedTop(t){return void 0===t&&(t=this.textOY),t>this.topTextOY}textOYExeceedBottom(t){return void 0===t&&(t=this.textOY),tthis.linesCount?t=0:s?t=e:r&&(t=i)),this._textOY!==t&&(this._textOY=t,this.updateTextObject()),s&&(this.execeedTopState||this.emit("execeedtop",this,t,e)),this.execeedTopState=s,r&&(this.execeedBottomState||this.emit("execeedbottom",this,t,i)),this.execeedBottomState=r}setTextOY(t){return this.textOY=t,this}set t(t){this.textOY=-this.textVisibleHeight*t}get t(){var t=this.textVisibleHeight;return 0===t?0:this.textOY/-t}setTextOYByPercentage(t){return this.t=t,this}}var DT=function(t){return t.add.text(0,0,"")};Object.assign(IT.prototype,_T);var jT={setText(t){return this.childrenMap.child.setText(t),this.resizeController(),this},appendText(t){return this.setText(this.text+t),this}},AT={scrollToLine(t){return this.setChildOY(-this.lineHeight*t),this},scrollToNextLine(t){void 0===t&&(t=1);var e=this.lineIndex+t;return this.scrollToLine(e),this}};const zT=Phaser.Utils.Objects.GetValue;class FT extends xT{constructor(t,e){void 0===e&&(e={});var i=zT(e,"text",void 0),s=zT(e,"textWidth",void 0),r=zT(e,"textHeight",void 0),n=zT(e,"textCrop",!!i.setCrop),a=zT(e,"textMask",!n),o=zT(e,"content",""),h=new IT(t,{width:s,height:r,text:i,textMask:a,textCrop:n&&!a,content:o,clampTextOY:zT(e,"clampChildOY",!1),alwaysScrollable:zT(e,"alwaysScrollable",!1)});t.add.existing(h),function(t){Object.defineProperty(t,"childOY",{configurable:!0,get:function(){return t.textOY},set:function(e){t.textOY=e}}),Object.defineProperty(t,"topChildOY",{get:function(){return t.topTextOY}}),Object.defineProperty(t,"bottomChildOY",{get:function(){return t.bottomTextOY}}),Object.defineProperty(t,"childVisibleHeight",{get:function(){return t.textObjectHeight}}),Object.defineProperty(t,"childHeight",{get:function(){return t.textHeight}})}(h),e.scrollMode=0,e.type="rexTextArea",e.child={gameObject:h,expandWidth:void 0===s,expandHeight:void 0===r};var l=zT(e,"space",void 0);l&&(l.child=zT(l,"text",0)),super(t,e),this.addChildrenMap("text",i)}get text(){return this.childrenMap.child.text}get lineHeight(){var t=this.childrenMap.child;return t.textLineHeight+t.textLineSpacing}get lineIndex(){return Math.floor(-this.childOY/this.lineHeight)}get linesCount(){return this.childrenMap.child.linesCount}get contentHeight(){return this.childrenMap.child.textHeight}}Object.assign(FT.prototype,jT,AT);const YT=Phaser.Utils.Objects.GetValue;var XT=function(t,e,s){e=e?i(e):{};var r=YT(s,"background",vP),n=YT(s,"text",WT),a=YT(s,"track",vP),o=YT(s,"thumb",vP);r?e.background=r(t,e.background):delete e.background,n?e.text=n(t,e.text):delete e.text;var h=e.slider;!1!==h&&null!==h&&(void 0===h&&(h={}),a?h.track=a(t,h.track):delete h.track,o?h.thumb=o(t,h.thumb):delete h.thumb,e.slider=h);var l=new FT(t,e);return t.add.existing(l),l},WT=function(t,e){var i,s;switch(e&&(e.hasOwnProperty("$type")?i=e.$type:e.hasOwnProperty("key")&&(i="bitmaptext",e.font=e.key)),i){case"bitmaptext":case"bitmap":s=new SS(t,e);break;case"bbcodetext":case"bbcode":s=new ds(t,0,0,"",e);break;case"label":s=new UT(t,e);break;case"textarea":s=XT(t,e);break;default:s=new xS(t,e)}return gP(s,e),t.add.existing(s),s},VT=function(t,e){var i,s;switch(e&&(e.hasOwnProperty("$type")?i=e.$type:e.hasOwnProperty("leftWidth")?i="nineSlice":(e.hasOwnProperty("color")||e.hasOwnProperty("strokeColor"))&&(i="roundRectangle")),i){case"nineSlice":s=e.hasOwnProperty("stretchMode")?new mS(t,e):new gS(t,e);break;case"roundRectangle":s=new lS(t,e);break;default:s=new hS(t,e)}return gP(s,e),t.add.existing(s),s};const GT=Phaser.Utils.Objects.GetValue;var HT=function(t,e,s){e=e?i(e):{};var r=GT(s,"background",vP),n=GT(s,"text",WT),a=GT(s,"icon",VT),o=GT(s,"action",VT);return null!==e.background&&r?e.background=r(t,e.background):delete e.background,null!==e.text&&n?e.text=n(t,e.text):delete e.text,null!==e.icon&&a?e.icon=a(t,e.icon):delete e.icon,null!==e.action&&o?e.action=o(t,e.action):delete e.action,e};class UT extends Ww{constructor(t,e,i){super(t,e=HT(t,e,i)),this.type="rexSimpleLabel"}setActiveState(t){return NT(this.getChildren(),"setActiveState",t),this}setHoverState(t){return NT(this.getChildren(),"setHoverState",t),this}setDisableState(t){return NT(this.getChildren(),"setDisableState",t),this}}var NT=function(t,e,i){for(var s=0,r=t.length;sthis.maxExp&&(t=this.maxExp),void 0===e&&(e=this.getLevel(t)),this._exp=t,this._level=e,this._requiredExp=this.getRequiredExpToNextLevel(e,t),this}get exp(){return this._exp}set exp(t){if(this.hasMaxLevel&&t>this.maxExp&&(t=this.maxExp),tthis.maxLevel?this.exp=this.maxExp:this.exp=this.getExp(t)}get requiredExp(){return this._requiredExp}getExp(t){return void 0===t?this._exp:this.isLevelMapFunction?this.levelTable(t):(this.hasMaxLevel&&t>this.maxLevel&&(t=this.maxLevel),this.levelTable[t])}getLevel(t,e){if(void 0===t)return this._level;for(void 0===e&&(e=0);;){var i=this.getExp(e+1);if(i>t)break;if(e++,this.hasMaxLevel&&i===this.maxExp)break}return e}getRequiredExpToNextLevel(t,e){return void 0===t&&(t=this.level),void 0===e&&(e=this.exp),this.getExp(t+1)-e}checkLevel(t,e){return e>=this.getExp(t)&&e=0;n--)s=cO(t[n],e,i);else for(var n=0,a=t.length;ns?1:it)return this;for(var e=this.commands;;){var i=e[this.index],s=i[1];if(Tm(s)||(s=Bc(fO,i,1)),cO(s,this.scope),this.emit("runcommand",s,this.scope),this.index>=e.length-1)return this.nextTime=0,this.complete(),this;if(this.index++,this.nextTime=this.getNextDt(this.nextTime),this.nextTime>t)return this}}complete(){this.clock.stop(),this.state=2,this.emit("complete",this.parent,this)}getNextDt(t){var e=this.commands[this.index][0];return 1===this.timeUnit&&(e*=1e3),1===this.dtMode&&(e+=t),e}setDtMode(t){return"string"==typeof t&&(t=yO[t]),this.dtMode=t,this}setTimeUnit(t){return"string"==typeof t&&(t=mO[t]),this.timeUnit=t,this}}var fO=[];const mO={ms:0,s:1,sec:1},yO={abs:0,absolute:0,inc:1,increment:1};var bO=function(t,e,i,s,r){var n=(i-e)/(r-s)*this.totalEaseDuration,a=i===r?t+1:t;this.player.append(0,this.setEaseValueDuration,n).append(0,this.easeValueTo,i,s,r).append(0,this.emit,"levelup.start",t,e,i,this).append(n,h).append(0,this.emit,"levelup.end",a,e,i,this),this.player.isPlaying||this.player.start()},xO={setExpTable(t){return this.levelCounter.setTable(t),this},resetExp(t){return this.levelCounter.resetExp(t),this.setValue(this.exp,this.getExp(this.level),this.getExp(this.level+1)),this},getExp(t){return this.levelCounter.getExp(t)},getLevel(t,e){return this.levelCounter.getLevel(t,e)},getRequiredExpToNextLevel(t,e){return this.levelCounter.getRequiredExpToNextLevel(t,e)},gainExp(t){return this.levelCounter.gainExp(t),this},setExp(t){return this.levelCounter.setExp(t),this},setLevel(t){return this.levelCounter.setLevel(t),this}};const CO=Phaser.Utils.Objects.GetValue;class kO extends lO{constructor(t,e){super(t,e),this.type="rexExpBar",this.setTotalEaseDuration(CO(e,"easeDuration",1e3)),this.levelCounter=new dO(CO(e,"levelCounter")),this.player=new vO(this,{scope:this,dtMode:1}),this.levelCounter.on("levelup",bO,this),this.player.on("complete",(function(){this.player.clear(),this.emit("levelup.complete",this.level,this)}),this),this.setValue(this.exp,this.getExp(this.level),this.getExp(this.level+1))}destroy(t){this.scene&&!this.ignoreDestroy&&(this.levelCounter.destroy(),this.levelCounter=void 0,this.player.destroy(),this.player=void 0,super.destroy(t))}get exp(){return this.levelCounter.exp}set exp(t){this.levelCounter.exp=t}get level(){return this.levelCounter.level}set level(t){this.levelCounter.level=t}get requiredExp(){return this.levelCounter.requiredExp}setTotalEaseDuration(t){return this.totalEaseDuration=t,this}}Object.assign(kO.prototype,xO),t.register("expBar",(function(t){var e=new kO(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ExpBar",kO);const wO=xw.prototype.add,SO=xw.prototype.addSpace;var PO=function(t){var e=!t.isRexSpace,i=!e||this.buttonsExpand?1:0;if(0===this.sizerChildren.length)if(e){!this.buttonsExpand&&("right"===this.buttonsAlign||"center"===this.buttonsAlign||"bottom"===this.buttonsAlign)&&SO.call(this),wO.call(this,t,{proportion:i,expand:!0});var s=!this.buttonsExpand&&"center"===this.buttonsAlign;s&&SO.call(this),this.hasTailSpace=s}else wO.call(this,t,{proportion:i,expand:!0}),this.hasTailSpace=!1;else if(this.hasTailSpace){var r=this.sizerChildren.length-1;wO.call(this,t,{index:r,proportion:i,expand:!0})}else wO.call(this,t,{proportion:i,expand:!0});return e&&this.buttonGroup.add(t),this},TO={addButton(t){if(Tm(t))for(var e=t,i=0,s=e.length;i=0;i--)EO.call(this,e[i],t);return this}},RO=function(t,e,i){if(t){var s=this.setValueCallback,r=this.setValueCallbackScope;s&&(r?s.call(r,t,e,i):s(t,e,i)),this.fireEvent("button.statechange",t,e,i)}},LO=function(t){var e=this;t._selected=void 0,Object.defineProperty(t,"selected",{get:function(){return t._selected},set:function(i){if(t._selected!==i){var s=t._selected;t._selected=i,RO.call(e,t,i,s)}},enumerable:!0,configurable:!0}),t.selected=!1},BO={add(t){return this.buttons.push(t),t._click||(t._click=new hu(t,this.clickConfig),t._click.on("click",(function(t,e,i,s){this.fireEvent("button.click",e,i,s)}),this).on("enable",(function(t,e){this.fireEvent("button.enable",e)}),this).on("disable",(function(t,e){this.fireEvent("button.disable",e)}),this).on("over",(function(t,e,i,s){this.fireEvent("button.over",e,i,s)}),this).on("out",(function(t,e,i,s){this.fireEvent("button.out",e,i,s)}),this).on("down",(function(t,e,i,s){this.fireEvent("button.down",e,i,s)}),this).on("up",(function(t,e,i,s){this.fireEvent("button.up",e,i,s)}),this),t.isRexContainerLite&&t.sendChildToBack(t)),this.buttonsType&&(void 0===t.name&&console.error(`${this.parent.constructor.name}: Option button miss value`),LO.call(this,t)),this},addMultiple(t){for(var e=0,i=t.length;e0},setButtonEnable(t,e){var i=this.buttons;if(void 0===t||"boolean"==typeof t){e=t;for(var s=0,r=i.length;s=0;i--)KO.call(this,e[i],t);return this}};const qO=Phaser.Utils.Objects.GetValue;class ZO extends $S{constructor(t,e){void 0===e&&(e={});var i=qO(e,"row",0),s=qO(e,"column",e.col||0),r=qO(e,"createCellContainerCallback"),n=qO(e,"buttons",void 0),a=qO(e,"expand",!0),o=a?1:0;if(r&&(e.createCellContainerCallback=void 0),void 0!==n){i=Math.max(i,n.length);for(var h=0,l=n.length;hr&&QO.addNewLine(this)}else for(n=0,a=t.length;n=0;i--)rM.call(this,e[i],t);return this}};const aM=Phaser.Utils.Objects.GetValue;class oM extends cP{constructor(t,e){void 0===e&&(e={});var i=e.space;"number"==typeof i&&(e.space={item:i,line:i}),super(t,e),this.type="rexFixWidthButtons",this.buttonGroup=new YO({parent:this,eventEmitter:aM(e,"eventEmitter",this),groupName:aM(e,"groupName",void 0),clickConfig:aM(e,"click",void 0)}).setButtonsType(e);var s=aM(e,"background",void 0),r=aM(e,"buttons",void 0);this.buttonsAlign=aM(e,"align",void 0),s&&this.addBackground(s),r&&this.addButtons(r),this.addChildrenMap("background",s),this.addChildrenMap("buttons",this.buttonGroup.buttons)}destroy(t){this.scene&&!this.ignoreDestroy&&(super.destroy(t),this.buttonGroup.destroy(),this.buttonGroup=void 0)}get buttons(){return this.buttonGroup.buttons}get groupName(){return this.buttonGroup.groupName}set groupName(t){this.buttonGroup.groupName=t}get eventEmitter(){return this.buttonGroup.eventEmitter}}Object.assign(oM.prototype,eM,nM,FO,WO),t.register("fixWidthButtons",(function(t){var e=new oM(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.FixWidthButtons",oM);var hM={setAccept(t){return this.childrenMap.fileChooser.setAccept(t),this},setMultiple(t){return this.childrenMap.fileChooser.setMultiple(t),this},loadFile(t,e,i,s,r){return this.childrenMap.fileChooser.loadFile(t,e,i,s,r),this},loadFilePromise(t,e,i,s){return this.childrenMap.fileChooser.loadFilePromise(t,e,i,s)}};const lM=Phaser.Utils.Objects.GetValue;class dM extends Ww{constructor(t,e){super(t,e),this.type="rexFileSelectorButton";var i=new Xk(t);t.add.existing(i),this.addBackground(i),this.addChildrenMap("fileChooser",i),this.setAccept(lM(e,"accept","")),this.setMultiple(lM(e,"multiple",!1)),i.on("change",(function(t){var e=t.files;0!==e.length&&(e=Array.from(e),this.emit("select",e,this))}),this)}get files(){return this.childrenMap.fileChooser.files}}Object.assign(dM.prototype,hM),t.register("fileSelectorButton",(function(t){var e=new dM(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.FileSelectorButton",dM);var cM={getChoice(t){var e=this.childrenMap.choicesSizer;return e?e.getButton(t):void 0},getAction(t){return this.childrenMap.actionsSizer.getButton(t)},getToolbar(t){return this.childrenMap.toolbarSizer.getButton(t)},getLeftToolbar(t){return this.childrenMap.leftToolbarSizer.getButton(t)},setChoiceEnable(t,e){var i=this.childrenMap.choicesSizer;return i&&i.setButtonEnable(t,e),this},setActionEnable(t,e){return this.childrenMap.actionsSizer.setButtonEnable(t,e),this},setToolbarEnable(t,e){return this.childrenMap.toolbarSizer.setButtonEnable(t,e),this},setLeftToolbarEnable(t,e){return this.childrenMap.leftToolbarSizer.setButtonEnable(t,e),this},toggleChoiceEnable(t){var e=this.childrenMap.choicesSizer;return e&&e.toggleButtonEnable(t),this},toggleActionEnable(t){return this.childrenMap.actionsSizer.toggleButtonEnable(t),this},toggleToolbarEnable(t){return this.childrenMap.toolbarSizer.toggleButtonEnable(t),this},toggleLeftToolbarEnable(t){return this.childrenMap.leftToolbarSizer.toggleButtonEnable(t),this},getChoiceEnable(t){var e=this.childrenMap.choicesSizer;return!!e&&e.getButtonEnable(t)},getActionEnable(t){return this.childrenMap.actionsSizer.getButtonEnable(t)},getToolbarEnable(t){return this.childrenMap.toolbarSizer.getButtonEnable(t)},getLeftToolbarEnable(t){return this.childrenMap.leftToolbarSizer.getButtonEnable(t)},emitChoiceClick(t){var e=this.childrenMap.choicesSizer;return e&&e.emitButtonClick(t),this},emitActionClick(t){return this.childrenMap.actionsSizer.emitButtonClick(t),this},emitToolbarClick(t){return this.childrenMap.toolbarSizer.emitButtonClick(t),this},emitLeftToolbarClick(t){return this.childrenMap.leftToolbarSizer.emitButtonClick(t),this},showChoice(t){var e=this.childrenMap.choicesSizer;return e&&e.showButton(t),this},showAction(t){return this.childrenMap.actionsSizer.showButton(t),this},showToolbar(t){return this.childrenMap.toolbarSizer.showButton(t),this},showLeftToolbar(t){return this.childrenMap.leftToolbarSizer.showButton(t),this},hideChoice(t){var e=this.childrenMap.choicesSizer;return e&&e.hideButton(t),this},hideAction(t){return this.childrenMap.actionsSizer.hideButton(t),this},hideToolbar(t){return this.childrenMap.toolbarSizer.hideButton(t),this},hideLeftToolbar(t){return this.childrenMap.leftToolbarSizer.hideButton(t),this},addChoice(t){var e=this.childrenMap.choicesSizer;return e&&e.addButton(t),this},addAction(t){return this.childrenMap.actionsSizer.addButton(t),this},addToolbar(t){return this.childrenMap.toolbarSizer.addButton(t),this},addLeftToolbar(t){return this.childrenMap.leftToolbarSizer.addButton(t),this},removeChoice(t,e){var i=this.childrenMap.choicesSizer;return i&&i.removeButton(t,e),this},removeAction(t,e){return this.childrenMap.actionsSizer.removeButton(t,e),this},removeToolbar(t,e){return this.childrenMap.toolbarSizer.removeButton(t,e),this},removeLeftToolbar(t,e){return this.childrenMap.leftToolbarSizer.removeButton(t,e),this},clearChoices(t){var e=this.childrenMap.choicesSizer;return e&&e.clearButtons(t),this},clearActions(t){return this.childrenMap.actionsSizer.clearButtons(t),this},clearToolbar(t){return this.childrenMap.toolbarSizer.clearButtons(t),this},clearLeftToolbar(t){return this.childrenMap.leftToolbarSizer.clearButtons(t),this},forEachChoice(t,e){var i=this.childrenMap.choicesSizer;return i&&i.forEachButtton(t,e),this},forEachAction(t,e){return this.childrenMap.actionsSizer.forEachButtton(t,e),this},forEachToolbar(t,e){return this.childrenMap.toolbarSizer.forEachButtton(t,e),this},forEachLeftToolbar(t,e){return this.childrenMap.leftToolbarSizer.forEachButtton(t,e),this},setAllButtonsEnable(t){return void 0===t&&(t=!0),this.childrenMap.toolbarSizer&&this.setToolbarEnable(t),this.childrenMap.leftToolbarSizer&&this.setLeftToolbarEnable(t),this.childrenMap.actionsSizer&&this.setActionEnable(t),this.childrenMap.choicesSizer&&this.setChoiceEnable(t),this},getChoicesButtonStates(){var t=this.childrenMap.choicesSizer;return t?t.getAllButtonsState():{}},getChoicesButtonState(t){var e=this.childrenMap.choicesSizer;return void 0===t?e?e.getAllButtonsState():{}:!!e&&e.getButtonState(t)},setChoicesButtonState(t,e){var i=this.childrenMap.choicesSizer;return i&&i.setButtonState(t,e),this},clearChoicesButtonStates(){var t=this.childrenMap.choicesSizer;return t&&t.clearAllButtonsState(),this},getChoicesSelectedButtonName(){var t=this.childrenMap.choicesSizer;return t?t.getSelectedButtonName():""},setChoicesSelectedButtonName(t){var e=this.childrenMap.choicesSizer;return e&&e.setSelectedButtonName(t),this},hasAnyChoice(){var t=this.childrenMap.choicesSizer;return!!t&&t.hasAnyButton()},hasAnyAction(){var t=this.childrenMap.actionsSizer;return!!t&&t.hasAnyButton()},hasAnyToolbar(){var t=this.childrenMap.toolbarSizer;return!!t&&t.hasAnyButton()},hasAnyLeftToolbar(){var t=this.childrenMap.leftToolbarSizer;return!!t&&t.hasAnyButton()}},uM={onCreateModalBehavior(t){t.on("button.click",(function(e,i,s,r,n){var a=!1;switch(i){case"actions":a=!0;break;case"choices":t.hasAnyAction()||(a=!0)}if(a){var o={index:s,text:e.text,button:e,dialog:t};switch(t.buttonsType){case"radio":o.value=t.getChoicesSelectedButtonName();break;case"checkboxes":o.value=t.getChoicesButtonStates();break;default:o.value=void 0}t.modalClose(o)}}))},modal(t,e){return t&&!1===t.defaultBehavior?this.onCreateModalBehavior=!1:delete this.onCreateModalBehavior,xm.modal.call(this,t,e),this}},pM={};Object.assign(pM,cM,uM);const gM=Phaser.Utils.Objects.GetValue;class vM extends xw{constructor(t,e){void 0===e&&(e={}),e.orientation=1,super(t,e),this.type="rexDialog",this.eventEmitter=gM(e,"eventEmitter",this);var i,s,r,n,a=gM(e,"background",void 0),o=gM(e,"title",void 0),h=gM(e,"toolbar",void 0),l=gM(e,"toolbarBackground",void 0),d=gM(e,"leftToolbar",void 0),c=gM(e,"leftToolbarBackground",void 0),u=gM(e,"content",void 0),p=gM(e,"description",void 0),g=gM(e,"choices",void 0),v=gM(e,"choicesBackground",void 0),f=gM(e,"actions",void 0),m=gM(e,"actionsBackground",void 0),y=gM(e,"click",void 0);if(a&&this.addBackground(a),h&&(r=new GO(t,{groupName:"toolbar",background:l,buttons:h,orientation:0,space:{item:gM(e,"space.toolbarItem",0)},click:y,eventEmitter:this.eventEmitter}),t.add.existing(r)),d&&(n=new GO(t,{groupName:"leftToolbar",background:c,buttons:d,orientation:0,space:{item:gM(e,"space.leftToolbarItem",0)},click:y,eventEmitter:this.eventEmitter}),t.add.existing(n)),o||h||d){var b,x=!!o&&gM(e,"expand.title",!0),C=gM(e,"align.title","center"),k=!(o&&!x&&"center"===C||!o&&(h||d));b=k?new xw(t,{orientation:0}):new Yb(t),t.add.existing(b);var w=!!k||{height:!0};if(n&&b.add(n,{align:"left",expand:w}),o){k&&!x&&"right"===C&&b.addSpace();var S={left:gM(e,"space.titleLeft",0),right:gM(e,"space.titleRight",0)},P=x?1:0;b.add(o,{align:C,proportion:P,expand:w,padding:S}),k&&!x&&"left"===C&&b.addSpace()}r&&(k&&!o&&b.addSpace(),b.add(r,{align:"right",expand:w})),(u||p||g||f)&&(S={bottom:gM(e,"space.title",0),top:gM(e,"space.titleTop",0)}),P=gM(e,"proportion.title",0),this.add(b,{padding:S,proportion:P,expand:!0})}if(u){var T=gM(e,"align.content","center"),O=gM(e,"space.content",0),M=(S={left:gM(e,"space.contentLeft",0),right:gM(e,"space.contentRight",0),bottom:p||g||f?O:0},P=gM(e,"proportion.content",0),gM(e,"expand.content",!0));this.add(u,{align:T,padding:S,proportion:P,expand:M})}if(p){T=gM(e,"align.description","center");var E=gM(e,"space.description",0);S={left:gM(e,"space.descriptionLeft",0),right:gM(e,"space.descriptionRight",0),bottom:g||f?E:0},P=gM(e,"proportion.description",0),M=gM(e,"expand.description",!0),this.add(p,{align:T,padding:S,proportion:P,expand:M})}if(g){var _=gM(e,"choicesType","").split("-"),R=fM(_,"wrap")?oM:fM(_,"grid")?ZO:GO,L=fM(_,"radio")?"radio":fM(_,"checkboxes")?"checkboxes":void 0,B={left:gM(e,"space.choicesBackgroundLeft",0),right:gM(e,"space.choicesBackgroundRight",0),top:gM(e,"space.choicesBackgroundTop",0),bottom:gM(e,"space.choicesBackgroundBottom",0)},I=gM(e,"space.choice",0);R===GO?B.item=I:R===oM?(B.item=I,B.line=gM(e,"space.choiceLine",I)):(B.column=gM(e,"space.choiceColumn",I),B.row=gM(e,"space.choiceRow",I));var D={width:gM(e,"choicesWidth",void 0),height:gM(e,"choicesHeight",void 0),groupName:"choices",buttonsType:L,background:v,buttons:g,space:B,click:y,eventEmitter:this.eventEmitter,setValueCallback:gM(e,"choicesSetValueCallback",void 0),setValueCallbackScope:gM(e,"choicesSetValueCallbackScope",void 0)};R===GO&&(D.orientation=fM(_,"x")?0:1),i=new R(t,D),t.add.existing(i);var j=gM(e,"space.choices",0);S={left:gM(e,"space.choicesLeft",0),right:gM(e,"space.choicesRight",0),bottom:f?j:0},T=gM(e,"align.choices","center"),P=gM(e,"proportion.choices",0),M=gM(e,"expand.choices",!0),this.add(i,{align:T,padding:S,proportion:P,expand:M}),this.buttonsType=L}f&&(s=new GO(t,{groupName:"actions",background:m,buttons:f,orientation:0,space:{item:gM(e,"space.action",0)},expand:gM(e,"expand.actions",!1),align:gM(e,"align.actions","center"),click:y,eventEmitter:this.eventEmitter}),t.add.existing(s),S={left:gM(e,"space.actionsLeft",0),right:gM(e,"space.actionsRight",0),bottom:gM(e,"space.actionsBottom",0)},P=gM(e,"proportion.action",0),this.add(s,{align:"center",padding:S,proportion:P,expand:!0})),yM(this,"click"),yM(this,"over"),yM(this,"out"),yM(this,"enable"),yM(this,"disable"),this.addChildrenMap("background",a),this.addChildrenMap("title",o),this.addChildrenMap("toolbar",h),this.addChildrenMap("leftToolbar",d),this.addChildrenMap("content",u),this.addChildrenMap("description",p),this.addChildrenMap("choices",i?i.buttons:void 0),this.addChildrenMap("actions",s?s.buttons:void 0),this.addChildrenMap("choicesSizer",i),this.addChildrenMap("actionsSizer",s),this.addChildrenMap("toolbarSizer",r),this.addChildrenMap("leftToolbarSizer",n)}}var fM=function(t,e){return-1!==t.indexOf(e)},mM={actions:"action",choices:"choice",toolbar:"toolbar",leftToolbar:"leftToolbar"},yM=function(t,e){t.on(`button.${e}`,(function(i,s,r,n,a){mM.hasOwnProperty(s)&&t.emit(`${mM[s]}.${e}`,i,r,n,a)}))};Object.assign(vM.prototype,pM),t.register("dialog",(function(t){var e=new vM(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.Dialog",vM);var bM=function(t,e,i){var s=new UT(t,e,i);return t.add.existing(s),s},xM=function(t){var e=this.childrenMap.title;null===(t=t.title)?e.hide():(e.show(),e.resetDisplayContent(t))},CM=function(t){var e=this.childrenMap.content;if(null===(t=t.content))e.hide();else if(e.show(),e.resetDisplayContent)e.resetDisplayContent(t);else{var i=t||"";e.setText(i)}},kM=function(t){var e=this.childrenMap.actions;if(e){var i=t.buttons;if(i){for(var s=this.scene,r=this.defaultActionConfig,n=this.defaultActionButtonCreator,a=0,o=i.length;a=0&&t=0&&i0&&s)){if(0===n)return 2===e&&(i+=1),i;if(1===e){var a=i;(s=(i+=1)>=0&&i=this.colCount?null:e*this.colCount+t}rowIndexToHeight(t,e){if(this.defaultCellHeightMode)return(e-t+1)*this.defaultCellHeight;for(var i=0,s=t;s<=e;s++)i+=this.getRowHeight(s);return i}colIndexToWidth(t,e){return(e-t+1)*this.defaultCellWidth}getRowHeight(t){var e=this.colCount;if(e<=1)return this.getCellHeight(this.colRowToCellIndex(0,t));for(var i,s=0,r=0;rthis.topTableOY,n=tthis.leftTableOX,n=tt?this.removeCells(t,e-t):this.insertNewCells(e,t-e)),this},insertNewCells:function(t,e){return"object"==typeof t&&(t=t.index),void 0===e&&(e=1),e<=0||(t=_E(t,0,this.cellsCount),this.table.insertNewCells(t,e)),this},removeCells:function(t,e){if("object"==typeof t&&(t=t.index),void 0===e&&(e=1),t<0&&(e+=t,t=0),e<=0)return this;if(t>this.cellsCount)return this;for(var i,s=t,r=t+e;sthis.topChildOY}childOYExeceedBottom(t){return void 0===t&&(t=this.childOY),tthis.leftChildOX}childOXExeceedRight(t){return void 0===t&&(t=this.childOX),tthis.childHeight?t=0:s?t=e:r&&(t=i)),this._childOY!==t&&(this._childOY=t,this.resetChildPosition()),s&&(this.execeedTopState||this.emit("execeedtop",this,t,e)),this.execeedTopState=s,r&&(this.execeedBottomState||this.emit("execeedbottom",this,t,i)),this.execeedBottomState=r}get childOX(){return this._childOX}set childOX(t){var e=this.leftChildOX,i=this.rightChildOX,s=this.childOXExceedLeft(t),r=this.childOXExeceedRight(t);this.clampChildOX&&(this.childVisibleWidth>this.childWidth?t=0:s?t=e:r&&(t=i)),this._childOX!==t&&(this._childOX=t,this.resetChildPosition()),s&&(this.execeedLeftState||this.emit("execeedleft",this,t,e)),this.execeedLeftState=s,r&&(this.execeedRightState||this.emit("execeedright",this,t,i)),this.execeedRightState=r}setChildOY(t){return this.childOY=t,this}setChildOX(t){return this.childOX=t,this}set t(t){this.childOY=-this.visibleHeight*t}get t(){var t=this.visibleHeight;return 0===t?0:this.childOY/-t}set s(t){this.childOX=-this.visibleWidth*t}get s(){var t=this.visibleWidth;return 0===t?0:this.childOX/-t}setChildOYByPercentage(t){return this.t=t,this}setChildOXByPercentage(t){return this.s=t,this}}Object.assign(w_.prototype,b_);const S_=["top","bottom","centerY","center"],P_=["left","right","centerX","center"];var T_=function(t,e,i){var s,r="Y"===(e=e.toUpperCase()),n=this.childrenMap.child;if(r){if(i)for(var a=0,o=S_.length;a=0?0:Math.abs(l)<=Math.abs(d)?l:d}}else{if(i)for(a=0,o=P_.length;a=0?0:Math.abs(c)<=Math.abs(u)?c:u}}switch(this.scrollMode){case 0:case 1:this.childOY+=s;break;default:this[`childO${e}`]+=s}};const O_=Phaser.Utils.Objects.GetValue;class M_ extends xT{constructor(t,e){void 0===e&&(e={});var i=mP(e),s=O_(e,"panel",void 0);void 0===s&&(s={}),s.scrollMode=i,s.clampChildOY=O_(e,"clampChildOY",!1),s.clampChildOX=O_(e,"clampChildOX",!1);var r,n,a=new w_(t,s);switch(t.add.existing(a),i){case 0:r=O_(e,"expand.panel",!0),n=!0;break;case 1:r=!0,n=O_(e,"expand.panel",!0);break;default:r=!0,n=!0}e.type="rexScrollablePanel",e.child={gameObject:a,expandWidth:r,expandHeight:n,align:O_(e,"align.panel","center")};var o=O_(e,"space",void 0);o&&(o.child=O_(o,"panel",0)),super(t,e),this.addChildrenMap("panel",a.child),this.addChildrenMap("panelLayer",a.maskLayer),this.addChildrenMap("mask",a.maskGameObject),this.addChildrenMap("scrollableBlock",a)}setChildrenInteractive(t){return void 0===t&&(t={}),t.hasOwnProperty("eventEmitter")||(t.eventEmitter=this),t.hasOwnProperty("targets")||(t.targets=[this.childrenMap.panel]),yb(this.childrenMap.child,t),this}}var E_={scrollToChild:function(t,e){if(!this.hasChild(t))return this;switch(this.scrollMode){case 0:T_.call(this,t,"y",e);break;case 1:T_.call(this,t,"x",e);break;default:T_.call(this,t,"y",e),T_.call(this,t,"x",e)}return this}};Object.assign(M_.prototype,E_);const __=Phaser.Utils.Objects.GetValue;var R_=function(){var t,e=this.scene,i=this.listCreateBackgroundCallback;i&&(t=i.call(this,e),e.add.existing(t));var s=[],r=this.listCreateButtonCallback;if(r)for(var n=this.options,a=0,o=n.length;a0||this.listMaxHeight>0)){if(s=L_(e,u),this.listMaxHeight>0&&(s.layout(),s.height<=this.listMaxHeight&&(d=s)),!d){0===c&&(c=this.listMaxHeight);var p=B_(e,this.listCreateSliderTrackCallback),g=B_(e,this.listCreateSliderThumbCallback);d=new M_(e,{height:c,scrollMode:0,panel:{child:s,mask:{padding:1}},slider:{track:p,thumb:g,adaptThumbSize:this.listSliderAdaptThumbSizeEnable},scrollDetectionMode:1,scroller:this.listScrollerConfig,mouseWheelScroller:this.listMouseWheelScrollerConfig,space:{panel:__(this.listSpace,"panel",0)}}),e.add.existing(d)}}else u.height=c,s=L_(e,u),d=s;return t&&d.addBackground(t,"background"),this.listDraggable&&d.setDraggable(!0),d!==s&&s.on("button.over",(function(t,e,i,s){d.emit("button.over",t,e,i,s)})).on("button.out",(function(t,e,i,s){d.emit("button.out",t,e,i,s)})).on("button.click",(function(t,e,i,s){d.emit("button.click",t,e,i,s)})),d},L_=function(t,e,i){var s;return i?(e.orientation="x",s=new oM(t,e)):(e.orientation="y",s=new GO(t,e)),t.add.existing(s),s},B_=function(t,e,i){var s;return e&&(s=e.call(i,t),t.add.existing(s)),s};const I_=Phaser.Utils.Objects.GetValue;var D_=function(t,e){var i=I_(e,"expandDirection",void 0);"string"==typeof i&&(i=j_[i]);var s,r,n,a,o,h,l,d=(n="alignTargetX",Td(s=e,r="alignTarget")?J(s,r):n&&Td(s,n)?J(s,n):a&&Td(s,a)?J(s,a):o),c=I_(e,"alignTargetY",d),u=I_(e,"alignOffsetX",0),p=I_(e,"alignOffsetY",0),g=I_(e,"alignSide","").includes("right"),v=I_(e,"bounds"),f=0===i,m=!(f||1===i),y=g?1:0,b=f||m?0:1;t.setOrigin(y,b),h=g?d.getTopRight().x:d.getTopLeft().x,l=c.getBottomLeft().y,t.setPosition(h+u,l+p);var x=v;x||(x=aa(t.scene)),m&&t.getBottomLeft().y>x.bottom&&(l=c.getTopLeft().y,t.setOrigin(0,1).setPosition(h+u,l+p))};const j_={down:0,up:1},A_=Phaser.Utils.Objects.GetValue;class z_ extends im{constructor(t,e){void 0===e&&(e={}),null==e.transitIn&&(e.transitIn=function(t,e){Zv(t,e,"y","Cubic")}),null==e.transitOut&&(e.transitOut=function(t,e){!function(t,e,i,s,r){void 0===s&&(s="Linear");var n={mode:0};switch(i){case 0:case"x":n.end={x:0};break;case 1:case"y":n.end={y:0};break;default:n.end=0}n.duration=e,n.ease=s,void 0===r?r=new Jv(t,n):r.resetFromJSON(n),r.restart()}(t,e,"y","Linear")}),e.manualClose=!0,e.clickOutsideClose=!0,e.destroy=!0,super(t,e),D_(t,e),t.isRexSizer&&t.layout();var i=A_(e,"touchOutsideClose",!1),s=A_(e,"anyTouchClose",!1);s&&(i=!1),s?this.once("open",this.anyTouchClose,this):i&&this.once("open",this.touchOutsideClose,this),this.requestOpen()}shutdown(t){this.isShutdown||(this.scene.input.off("pointerup",this.touchCloseCallback,this),super.shutdown(t))}touchOutsideClose(){return this.scene.input.on("pointerup",this.touchCloseCallback,this),this.clickOutsideTest=!0,this}anyTouchClose(){return this.scene.input.once("pointerup",this.touchCloseCallback,this),this}touchCloseCallback(t){this.clickOutsideTest&&pm(this.parent,t.worldX,t.worldY)||this.requestClose()}onOpen(){this.emit("open",this.parent,this),super.onOpen()}onClose(){this.emit("close",this.parent,this),super.onClose()}}var F_={focusNextButton(){if(!this.isOpened)return this;var t,e=this.currentOverIndex;return t=void 0===e?0:(e+1)%this.listPanel.getButtons().length,this.emitButtonOver(t),this},focusPrevButton(){if(!this.isOpened)return this;var t,e=this.currentOverIndex;if(void 0===e)t=0;else{var i=this.listPanel.getButtons().length;t=(e-1+i)%i}return this.emitButtonOver(t),this}},Y_={openListPanel:function(){if(this.listPanel)return this;if(0===this.options.length)return this;var t,e=R_.call(this);e.on("button.over",(function(t,i,s,r){this.currentOverIndex=i,this.listOnButtonOver&&this.listOnButtonOver.call(this,t,i,s,r),this.emit("button.over",this,e,t,i,s,r)}),this).on("button.out",(function(t,i,s,r){this.currentOverIndex===i&&(this.currentOverIndex=void 0),this.listOnButtonOut&&this.listOnButtonOut.call(this,t,i,s,r),this.emit("button.out",this,e,t,i,s,r)}),this),t=this.listAlignMode&&"label"!==this.listAlignMode?this.getElement(this.listAlignMode):this;var i=new z_(e,{duration:{in:this.listEaseInDuration,out:this.listEaseOutDuration},transitIn:this.listTransitInCallback,transitOut:this.listTransitOutCallback,expandDirection:this.listExpandDirection,alignTargetX:t,alignTargetY:this,alignSide:this.listAlignSide,bounds:this.listBounds}).on("open",(function(){e.on("button.click",(function(t,i,s,r){this.listOnButtonClick&&this.listOnButtonClick.call(this,t,i,s,r),this.emit("button.click",this,e,t,i,s,r),this.dropDownBehavior.requestClose()}),this),this.emit("list.open",this,e)}),this).on("close",(function(){this.listPanel=void 0,this.dropDownBehavior=void 0,this.emit("list.close",this)}),this);return e.onClickOutside((function(){i.requestClose()})),this.listPanel=e,this.dropDownBehavior=i,this.pin(e),this},closeListPanel:function(){return this.dropDownBehavior?(this.dropDownBehavior.requestClose(),this.currentOverIndex=void 0,this):this},toggleListPanel:function(){return this.listPanel?this.closeListPanel():this.openListPanel(),this},emitButtonClick:function(t){if(void 0===t&&(t=this.currentOverIndex),void 0===t)return this;var e=this.listPanel,i=e?e.getButton(t):this.options[t];return this.listOnButtonClick&&this.listOnButtonClick.call(this,i,t),this.emit("button.click",this,e,i,t),this},emitButtonOver:function(t){var e=this.listPanel;return e?(e.emitButtonOver(t),this):this}};Object.assign(Y_,m_,F_);const X_=Phaser.Utils.Objects.GetValue;class W_ extends Ww{constructor(t,e){super(t,e),this.type="rexDropDownList",this.timer=void 0,this.listPanel=void 0,this.currentOverIndex=void 0,this.setOptions(X_(e,"options"));var i=X_(e,"list");this.setWrapEnable(X_(i,"wrap",!1)),this.setCreateButtonCallback(X_(i,"createButtonCallback")),this.setCreateListBackgroundCallback(X_(i,"createBackgroundCallback")),this.setCreateListSliderTrackCallback(X_(i,"createTrackCallback")),this.setCreateListSliderThumbCallback(X_(i,"createThumbCallback")),this.setListSliderAdaptThumbSizeEnable(X_(i,"sliderAdaptThumbSize",!1)),this.setListScrollerConfig(X_(i,"scroller")),this.setListMouseWheelScrollerConfig(X_(i,"mouseWheelScroller")),this.setButtonClickCallback(X_(i,"onButtonClick")),this.setButtonOverCallback(X_(i,"onButtonOver")),this.setButtonOutCallback(X_(i,"onButtonOut")),this.setListExpandDirection(X_(i,"expandDirection")),this.setListEaseInDuration(X_(i,"easeIn",500)),this.setListEaseOutDuration(X_(i,"easeOut",100)),this.setListTransitInCallback(X_(i,"transitIn")),this.settListTransitOutCallback(X_(i,"transitOut")),this.setListMaxHeight(X_(i,"maxHeight",0)),this.setListSize(X_(i,"width"),X_(i,"height",0)),this.setListAlignmentMode(X_(i,"alignParent","text")),this.setListAlignmentSide(X_(i,"alignSide","")),this.setListBounds(X_(i,"bounds")),this.setListSpace(X_(i,"space")),this.setListDraggable(X_(i,"draggable",!1)),this.setValueChangeCallback(X_(e,"setValueCallback"),X_(e,"setValueCallbackScope")),this.setValue(X_(e,"value")),this.onClick(this.toggleListPanel,this)}destroy(t){this.scene&&!this.ignoreDestroy&&(this.listPanel&&(this.listPanel.destroy(t),this.listPanel=void 0),super.destroy(t))}get isOpened(){return!!this.listPanel}setOptions(t){return void 0===t&&(t=[]),this.options=t,this}setValueChangeCallback(t,e){return this.valueChangeCallback=t,this.valueChangeCallbackScope=e,this}setValue(t){return this.value=t,this}get value(){return this._value}set value(t){if(this._value!==t){var e=this._value;this._value=t;var i=this.valueChangeCallback,s=this.valueChangeCallbackScope;i&&(s?i.call(s,this,t,e):i(this,t,e)),this.emit("valuechange",this,t,e)}}}Object.assign(W_.prototype,Y_),t.register("dropDownList",(function(t){var e=new W_(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.DropDownList",W_);var V_=function(t,e,s){void 0===s&&(s={});var r=(e=e?i(e):{}).label||e.button,n=e.button||e.label;delete e.label,delete e.button;var a=s.label||s.button||s,o=s.button||s.label||s,h=HT(t,r,a);h.list=e.list||{},h.list.createButtonCallback=function(t,e){var i=bM(t,n,o).resetDisplayContent(e);return e.hasOwnProperty("value")&&(i.value=e.value),i};var l=e.track;l&&(h.list.createTrackCallback=function(t){return vP(t,l)},delete e.track);var d=e.thumb;return d&&(h.list.createThumbCallback=function(t){return vP(t,d)},delete e.thumb),h.list.onButtonOver=function(t,e,i,s){t.setHoverState&&t.setHoverState(!0)},h.list.onButtonOut=function(t,e,i,s){t.setHoverState&&t.setHoverState(!1)},h};class G_ extends W_{constructor(t,e,i){super(t,e=V_(t,e,i)),this.type="rexSimpleDropDownList"}setOptions(t){void 0===t&&(t=[]);for(var e=0,i=t.length;e0?Math.ceil(s/this.pageLinesCount):1;for(var r=0;r0?t+i:this.totalLinesCount}var s;switch(e>this.totalLinesCount&&(e=this.totalLinesCount),this.textObjectType){case 0:case 2:s=this.lines.slice(t,e).join("\n");break;case 1:var r=this.lines.getLineStartIndex(t),n=this.lines.getLineEndIndex(e-1);((s=this.lines.getSliceTagText(r,n,!0)).match(/\n/g)||[]).length>e-t-1&&(s=s.substring(0,s.length-1))}return s}};Object.assign(K_,H_,N_,$_);const J_=Phaser.Utils.Objects.GetValue;Phaser.Math.Clamp;class q_ extends Ra{constructor(t,e){super(t,{eventEmitter:!1}),this.textObjectType=Ew(this.parent),this.pageStartIndexes=[],this.lines=kT(this.parent,""),this.sections=[],this.resetFromJSON(e)}resetFromJSON(t){this.setMaxLines(J_(t,"maxLines",void 0)),this.setPageBreak(J_(t,"pageBreak","\f\n")),this.setText(J_(t,"text","")),this.startLineIndex=J_(t,"start",-1),this.endLineIndex=J_(t,"end",void 0);var e=J_(t,"page");return void 0===e?this.resetIndex():this.setPageIndex(e),this}toJSON(){return{maxLines:this.maxLines,text:this.content,start:this.startLineIndex,end:this.endLineIndex,page:this.pageIndex,pageBreak:this.pageBreak}}shutdown(t){if(!this.isShutdown){switch(this.textObjectType){case 0:case 2:this.lines.length=0;break;case 1:this.lines.destroy()}this.pageStartIndexes.length=0,this.sections.length=0,this.lines=void 0,this.pageStartIndexes=void 0,this.sections=void 0,super.shutdown(t)}}setMaxLines(t){return this.maxLines=t,this}setPageBreak(t){return this.pageBreak=t,this}get pageCount(){return this.pageStartIndexes.length}get lastPageIndex(){return this.pageCount-1}get isFirstPage(){return this.pageIndex<=0}get isLastPage(){return this.pageIndex>=this.pageCount-1}get totalLinesCount(){return this.lines?this.lines.length:0}get pageLinesCount(){if(void 0!==this.maxLines)return this.maxLines;var t;switch(this.textObjectType){case 0:case 1:var e=this.parent.style.maxLines;t=e>0?e:Math.floor(function(t){var e,i,s;switch(Ew(t)){case 0:case 1:e=t.height-t.padding.top-t.padding.bottom,i=t.lineSpacing,s=t.style.metrics.fontSize+t.style.strokeThickness;break;case 2:e=t.height,i=0;var r=t.fontSize/t.fontData.size;s=t.fontData.lineHeight*r}return(e-i)/(s+i)}(this.parent));break;case 2:t=this.totalLinesCount}return t}get isFirstLine(){return this.startLineIndex<=0}get isLastLine(){return this.endLineIndex===this.totalLinesCount}get content(){return this.sections.join(this.pageBreak)}}Object.assign(q_.prototype,K_);var Z_={setText(t){this.setTextCallback&&(t=this.setTextCallbackScope?this.setTextCallback.call(this.setTextCallbackScope,t,this.isLastChar,this.insertIndex):this.setTextCallback(t,this.isLastChar,this.insertIndex)),this.textWrapEnable?TT(this.parent,t):this.parent.setText(t)},appendText(t){var e=this.text.concat(Ae(t));return this.isTyping?this.setTypingContent(e):this.start(e,void 0,this.textLength),this}},Q_=function(t,e){return t.getPlainText&&(e=t.getPlainText(e)),e},tR=function(t,e){for(var i=void 0,s=0;s0?eR(n,t,a=(o=i)-d,o):"";var c,u=e-d;u>0?(o=(a=0)+u,this.insertIndex=o,c=eR(n,t,a,o)):(c="",this.insertIndex=0),r=c+l}return this.insertChar=r.charAt(this.insertIndex-1),r},sR={start:function(t,e,i,s){return void 0!==t&&this.setTypingContent(t),void 0!==e&&(this.speed=e),void 0===i&&(i=0),this.typingIndex=i+1,0===this.speed?this.stop(!0):(this.setText(""),this.startTimer(s)),this},startFromLine:function(t,e,i,s,r){var n;if(e>0){void 0===s&&(s=0);var a=Q_(this.parent,t);n=tR(a,e)+s}return this.start(t,i,n,r)},stop:function(t){if(this.getTimer()&&this.freeTimer(),t){for(;!this.isLastChar;)iR.call(this,this.text,this.typingIndex,this.textLength,this.typeMode),this.emit("typechar",this.insertChar),this.typingIndex++;this.setText(this.text),this.emit("type"),this.emit("complete",this,this.parent)}return this},pause:function(){var t=this.getTimer();return t&&(t.paused=!0),this},resumeTyping:function(){var t=this.getTimer();return t&&(t.paused=!1),this}};Object.assign(sR,Z_);const rR=Phaser.Utils.Objects.GetFastValue,nR=Phaser.Utils.Objects.GetValue;class aR extends Ra{constructor(t,e){super(t,e),this.timer=null,this.resetFromJSON(e)}resetFromJSON(t){this.setTextWrapEnable(nR(t,"wrap",!1)),this.setTypeMode(nR(t,"typeMode",0)),this.setTypingSpeed(nR(t,"speed",333)),this.setTextCallback=rR(t,"setTextCallback",null),this.setTextCallbackScope=rR(t,"setTextCallbackScope",null),this.setTypingContent(rR(t,"text","")),this.typingIndex=rR(t,"typingIndex",0),this.insertIndex=null,this.insertChar=null;var e=rR(t,"elapsed",null);return null!==e&&this.start(void 0,void 0,this.typingIndex,e),this}shutdown(t){this.isShutdown||(this.freeTimer(),super.shutdown(t))}setTypeMode(t){return"string"==typeof t&&(t=oR[t]),this.typeMode=t,this}setTypeSpeed(t){return this.speed=t,this}setTypingSpeed(t){return this.speed=t,this}setTextWrapEnable(t){return void 0===t&&(t=!0),this.textWrapEnable=t,this}set text(t){var e=Ae(t);this.textWrapEnable&&(e=function(t,e){switch(Ew(t)){case 0:t.style.syncFont(t.canvas,t.context),e=t.runWordWrap(e);break;case 1:e=t.getText(e,void 0,void 0,!0);break;case 2:e=t.setText(e).getTextBounds().wrappedText}return e}(this.parent,e)),this._text=e}get text(){return this._text}get isTyping(){return null!==this.getTimer()}get isLastChar(){return this.typingIndex===this.textLength}setTypingContent(t){return this.text=t,this.textLength=Q_(this.parent,this.text).length,this}onTyping(){var t=iR.call(this,this.text,this.typingIndex,this.textLength,this.typeMode);this.setText(t),this.emit("typechar",this.insertChar),this.emit("type"),this.isLastChar?(this.freeTimer(),this.scene.sys.events.once("preupdate",(function(){this.emit("complete",this,this.parent)}),this)):(this.timer.delay=this.speed,this.typingIndex++)}startTimer(t){var e;return this.timer&&this.freeTimer(),void 0===t?e=0:(this.speed,e=t),this.timer=this.scene.time.addEvent({delay:1e-4,startAt:e,loop:!0,callback:this.onTyping,callbackScope:this}),this}getTimer(){return this.timer}freeTimer(){return this.timer&&(this.timer.remove(),this.timer=null),this}setText(t){this.setTextCallback&&(t=this.setTextCallbackScope?this.setTextCallback.call(this.setTextCallbackScope,t,this.isLastChar,this.insertIndex):this.setTextCallback(t,this.isLastChar,this.insertIndex)),this.textWrapEnable?TT(this.parent,t):this.parent.setText(t)}}const oR={"left-to-right":0,"right-to-left":1,"middle-to-sides":2,"sides-to-middle":3};Object.assign(aR.prototype,sR);const hR=Phaser.Utils.Objects.GetValue,lR={page:0,line:1};class dR extends(function(t,e){return void 0===e&&(e="rexTextBox"),class extends t{constructor(t,i){super(t,i),this.type=e,this.isRunning=!1,this._isPageEnd=!1;var s=this.childrenMap.text,r=hR(i,"expandTextWidth",!1),n=hR(i,"expandTextHeight",!1);if(r||n){var a=Ew(s);switch(a){case 0:case 1:if(s.resize=function(t,e){var i=r?t:0,a=n?e:0;s.setFixedSize(i,a),i>0&&s.setWordWrapWidth(i)},1===a){var o=s.style;0===o.wrapMode&&(o.wrapMode=1)}}r&&(s._minWidth=0),n&&(s._minHeight=0)}this.setTypingMode(hR(i,"typingMode","page")),this.page=new q_(s,hR(i,"page",void 0)),this.typing=new aR(s,hR(i,"typing",i.type)),this.typing.on("complete",this.onTypingComplete,this).on("type",this.onType,this).on("typechar",this.onTypeChar,this),this.textWidthSave=s.width,this.textHeightSave=s.height}setTypingMode(t){return"string"==typeof t&&(t=lR[t]),this.typingMode=t,this}start(t,e){return void 0!==e&&this.setTypingSpeed(e),this.isRunning=!0,this.page.setText(t),this.emit("start"),0===this.typingMode?this.typeNextPage():this.typeNextLine(),this}more(t,e){if(void 0!==e&&this.setTypingSpeed(e),!this.isRunning){if(this.isRunning=!0,this.page.appendText(t),this.emit("start"),0===this.typingMode){this._isPageEnd=!1;var i=this.page.getPage(),s=this.typing.textLength;this.typing.start(i,void 0,s)}return this}this.page.appendText(t),this.typing.appendText(t)}typeNextPage(){if(!this.isRunning)return this;if(this.isLastPage)this.emit("complete");else{this._isPageEnd=!1;var t=this.page.getNextPage();this.typing.start(t)}return this}typeNextLine(){if(!this.isRunning)return this;if(this.isLastLine)this.isRunning=!1,this.emit("pageend"),this.emit("complete");else{var t,e=this.page.getPageOfNextLine();t=this.isFirstLine?0:this.page.pageLinesCount-1,this.typing.startFromLine(e,t)}}pause(){return this.isRunning?(this.isTyping&&(this.typing.pause(),this.emit("pause")),this):this}resume(){return this.isRunning?(this.isTyping||(this.emit("resume"),this.typing.resume()),this):this}stop(t){return this.isRunning?(this.typing.stop(t),this):this}showLastPage(){return this.isRunning?(this.typing.stop(),0===this.typingMode?this.page.showLastPage():this.page.showLastLine(),this.emit("type"),this.onTypingComplete(),this):this}setTypeSpeed(t){return this.typing.setTypingSpeed(t),this}setTypingSpeed(t){return this.typing.setTypingSpeed(t),this}get isTyping(){return this.typing.isTyping}get isPageEnd(){return this._isPageEnd}get isLastPage(){return this.page.isLastPage}get isFirstPage(){return this.page.isFirstPage}get pageCount(){return this.page.pageCount}get pageIndex(){return this.page.pageIndex}get isLastLine(){return this.page.isLastLine}get isFirstLine(){return this.page.isFirstLine}get lineCound(){return this.page.totalLinesCount}get startLineIndex(){return this.page.startLineIndex}get endLineIndex(){return this.page.endLineIndex}get typingSpeed(){return this.typing.speed}onType(){var t=this.childrenMap.text;this.textWidthSave===t.width&&this.textHeightSave===t.height||(this.textWidthSave=t.width,this.textHeightSave=t.height,this.getTopmostSizer().layout()),this.emit("type")}onTypeChar(t){this.emit("typechar",t)}onTypingComplete(){if(0===this.typingMode){this._isPageEnd=!0;var t=this.isLastPage;this.isRunning=!t,this.emit("pageend"),t&&this.emit("complete")}else this.typeNextLine()}}}(ZT)){constructor(t,e){void 0===e&&(e={}),e.hasOwnProperty("layoutMode")||(e.layoutMode=1),super(t,e)}}t.register("textBox",(function(t){var e=new dR(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.TextBox",dR);class cR extends dR{constructor(t,e,i){super(t,e=tO(t,e,i))}}t.register("simpleTextBox",(function(t){var e=new cR(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.SimpleTextBox",cR);const uR=Phaser.Utils.Objects.GetValue;class pR extends xw{constructor(t,e){super(t,e),this.type="rexNumberBar";var i,s,r,n=uR(e,"background",void 0),a=uR(e,"icon",void 0),o=uR(e,"iconMask",void 0),h=uR(e,"slider",void 0),l=uR(e,"text",void 0),d=uR(e,"space.icon",0),c=uR(e,"space.slider",0);(n&&this.addBackground(n),a&&(0===this.orientation?(h||l)&&(s={right:d}):(h||l)&&(s={bottom:d}),this.add(a,{proportion:0,align:"center",padding:s}),o&&(o=Sw.call(this,a,a,1))),h)&&(h.orientation=this.orientation,h.eventEmitter=this,h.value=null,h.hasOwnProperty("input")||(h.input=-1),i=new GP(t,h),t.add.existing(i),0===this.orientation?l&&(s={right:c}):l&&(s={bottom:c}),r=0===this.orientation?void 0===uR(h,"width",void 0)?1:0:void 0===uR(h,"height",void 0)?1:0,this.add(i,{proportion:r,align:"center",padding:s}));l&&this.add(l),this.addChildrenMap("background",n),this.addChildrenMap("icon",a),this.addChildrenMap("iconMask",o),this.addChildrenMap("slider",i),this.addChildrenMap("text",l);var u=uR(e,"valuechangeCallback",null);if(null!==u){var p=uR(e,"valuechangeCallbackScope",void 0);this.on("valuechange",u,p)}this.setEnable(uR(e,"enable",void 0)),this.setValue(uR(e,"value",0))}get enable(){return!!this.childrenMap.slider&&this.childrenMap.slider.enable}set enable(t){this.childrenMap.slider&&this.childrenMap.slider.setEnable(t)}setEnable(t){return void 0===t&&(t=!0),this.enable=t,this}get value(){return this.childrenMap.slider?this.childrenMap.slider.value:0}set value(t){this.childrenMap.slider&&(this.childrenMap.slider.value=t)}setValue(t,e,i){return this.childrenMap.slider&&this.childrenMap.slider.setValue(t,e,i),this}addValue(t,e,i){return this.childrenMap.slider&&this.childrenMap.slider.addValue(t,e,i),this}getValue(t,e){return this.childrenMap.slider?this.childrenMap.slider.getValue(t,e):0}easeValueTo(t,e,i){return this.childrenMap.slider&&this.childrenMap.slider.easeValueTo(t,e,i),this}stopEaseValue(){return this.childrenMap.slider&&this.childrenMap.slider.stopEaseValue(),this}setEaseValueDuration(t){return this.childrenMap.slider&&this.childrenMap.slider.setEaseValueDuration(t),this}setEaseValueFunction(t){return this.childrenMap.slider&&this.childrenMap.slider.setEaseValueFunction(t),this}get text(){var t=this.childrenMap.text;return void 0===t?"":t.text?t.text:t.getData("text")}set text(t){var e=this.childrenMap.text;void 0!==e&&(e.setText?e.setText(t):e.setData("text",t))}setText(t){return this.text=t,this}}t.register("numberBar",(function(t){var e=new pR(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.NumberBar",pR),t.register("scrollBar",(function(t){var e=new $P(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ScrollBar",$P);const gR=Phaser.Utils.Objects.GetValue,vR={leftTop:"left-top",centerTop:"center-top",rightTop:"right-top",leftCenter:"left-center",center:"center",rightCenter:"right-center",leftBottom:"left-bottom",centerBottom:"center-bottom",rightBottom:"right-bottom"};class fR extends Yb{constructor(t,e){super(t,e),this.type="rexBadge";var i=gR(e,"background",void 0);i&&this.addBackground(i),this.addChildrenMap("background",i);var s=gR(e,"main",void 0);for(var r in s&&this.add(s,{key:"main",align:"center",expand:!1}),this.addChildrenMap("main",s),vR){var n=gR(e,r,void 0);n&&(this.add(n,{key:r,align:vR[r],expand:!1}),this.addChildrenMap(r,n))}}}t.register("badgeLabel",(function(t){var e=new fR(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.BadgeLabel",fR);const mR=Yb.prototype.add;var yR=function(t,e,i,s,r,n,a,o,h){return t.setVisible(!1),mR.call(this,t,e,i,s,r,n,a,o,h),this},bR={add:yR,addPage:yR};const xR=Dg.prototype.setChildVisible;var CR={getPage:function(t){return void 0===t?null:this.sizerChildren.hasOwnProperty(t)?this.sizerChildren[t]:null},swapPage:function(t,e){this._previousKey=this._currentKey;var i=this.previousPage;i&&(0===this.swapMode?(xR.call(this,i,!1),this.emit("pageinvisible",i,this._previousKey,this)):i.destroy()),t&&!this.sizerChildren.hasOwnProperty(t)&&this.emit("createpage",t,this),this._currentKey=t;var s=this.currentPage;return s&&(xR.call(this,s,!0),this.emit("pagevisible",s,this._currentKey,this),void 0===e&&(e=this.fadeInDuration),e>0&&s.setAlpha(0).fadeIn(e,1)),this},hasPage:function(t){return this.sizerChildren.hasOwnProperty(t)}};Object.assign(CR,bR);const kR=Phaser.Utils.Objects.GetValue;class wR extends Yb{constructor(t,e){super(t,e),this.type="rexPages",this.childrenMap=this.sizerChildren,this._previousKey=void 0,this._currentKey=void 0,this.setSwapMode(kR(e,"swapMode",0)),this.setFadeInDuration(kR(e,"fadeIn",0))}setSwapMode(t){return"string"==typeof t&&(t=SR[t]),this.swapMode=t,this}setFadeInDuration(t){return this.fadeInDuration=t,this}get previousKey(){return this._previousKey}get currentKey(){return this._currentKey}set currentKey(t){this.swapPage(t)}get currentPage(){return this.getPage(this.currentKey)}get previousPage(){return this.getPage(this.previousKey)}get keys(){return Object.keys(this.sizerChildren)}}Object.assign(wR.prototype,CR);const SR={invisible:0,destroy:1};t.register("pages",(function(t){var e=new wR(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.Pages",wR);const PR=Phaser.GameObjects.Mesh;class TR extends PR{get tint(){return 0===this.vertices.length?16777215:this.vertices[0].color}forceUpdate(){return this.dirtyCache[10]=1,this}}const OR=Phaser.Math.Vector3,MR=Phaser.Math.Matrix4;var ER=new OR,_R=new OR,RR=new MR;const LR=Phaser.Utils.Objects.IsPlainObject,BR=Phaser.Utils.Objects.GetValue,IR=Phaser.Geom.Mesh.GenerateGridVerts,DR=Phaser.Math.RadToDeg,jR=Phaser.Math.DegToRad,AR=1+1/Math.sin(jR(45));let zR=class extends TR{constructor(t,e,i,s,r,n){LR(e)&&(e=BR(n=e,"x",0),i=BR(n,"y",0),s=BR(n,"key",null),r=BR(n,"frame",null)),super(t,e,i,s,r),this.type="rexPerspectiveImage",this.setSizeToFrame(),this.resetPerspective(),this.panZ(AR),this.hideCCW=BR(n,"hideCCW",!0);var a=BR(n,"gridWidth",0),o=BR(n,"gridHeight",a);this.resetVerts(a,o),this.prevFrame=this.frame}preUpdate(t,e){this.prevFrame!==this.frame&&(this.prevFrame=this.frame,this.syncSize()),super.preUpdate(t,e)}get originX(){return.5}get originY(){return.5}resetPerspective(){return this.setPerspective(this.width,this.height,45),this}resetVerts(t,e){if(void 0!==t&&(this.gridWidth=t),void 0!==e&&(this.gridHeight=e),this.clear(),this.dirtyCache[9]=-1,0===this.width||0===this.height)return this;var i=this.frame.cutWidth,s=this.frame.cutHeight;0===this.gridWidth?t=Math.max(i/8,32):e=this.gridWidth,e=0===this.gridHeight?Math.max(s/8,32):this.gridHeight,IR({mesh:this,width:i/this.height,height:s/this.height,widthSegments:Math.ceil(i/t),heightSegments:Math.ceil(s/e)});var r=this.transformInfo;return r&&this.transformVerts(r.x,r.y,r.z,r.rotateX,r.rotateY,r.rotateZ),this}syncSize(){return this.setSizeToFrame(),this.resetPerspective(),this.resetVerts(),this}get rotationX(){return this.modelRotation.x}set rotationX(t){this.modelRotation.x=t}get angleX(){return DR(this.rotationX)}set angleX(t){this.rotationX=jR(t)}get rotationY(){return this.modelRotation.y}set rotationY(t){this.modelRotation.y=t}get angleY(){return DR(this.rotationY)}set angleY(t){this.rotationY=jR(t)}get rotationZ(){return this.modelRotation.z}set rotationZ(t){this.modelRotation.z=t}get angleZ(){return DR(this.rotationZ)}set angleZ(t){this.rotationZ=jR(t)}transformVerts(t,e,i,s,r,n){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===r&&(r=0),void 0===n&&(n=0),this.transformInfo||(this.transformInfo={}),this.transformInfo.x=t,this.transformInfo.y=e,this.transformInfo.rotateX=s,this.transformInfo.rotateY=r,this.transformInfo.rotateZ=n,function(t,e,i,s,r,n,a){void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===r&&(r=0),void 0===n&&(n=0),void 0===a&&(a=0),ER.set(e,i,s),_R.set(r,n,a),RR.fromRotationXYTranslation(_R,ER,!0);for(var o=0,h=t.vertices.length;o=0;i--)this.removePage(e[i].name,t);return this}},SL={top:1,left:3,right:5,bottom:7},PL={top:"bottom",left:"right",right:"left",bottom:"top"},TL={setTabsPadding(t,e){return this.childrenMap.tabs.setOuterPadding(t,e),this},getTabsPadding(t){return this.childrenMap.tabs.getOuterPadding(t)}},OL={getPageKey:function(t){var e=this.getElement("tabs.buttons");if(!(t>=e.length))return e[t].name},getPageIndex:function(t){for(var e=this.getElement("tabs.buttons"),i=0,s=e.length;i=a.y)continue;break;case 2:if(n.x<=a.x)continue;break;case 3:if(n.x>=a.x)continue}MB.call(r,s,a.x,a.y)}}(t,s,r,i),t.transitInCallback(e,i,t)},RB={showMessage(t){var e=function(t,e,i){var s=e(t.scene,i,t);if(TB.call(s,(function(){t.removeMessage(s)})),t.displayTime){var r=t.transitInTime+t.displayTime+10;OB.call(s,r,(function(){t.removeMessage(s)}))}return s}(this,this.createMessageLabelCallback,t);return _B(this,e,this.transitInTime),this},removeMessage(t){if(this.getParentSizer(t)!==this)return this;if(!t.__isDestroying){t.__isDestroying=!0;var e=this.transitOutTime;return this.transitOutCallback(t,e,this),OB.call(t,e+10,(function(){delete t.__isDestroying,t.destroy()})),this}},removeAllMessages(){for(var t=this.childrenMap.items,e=0,i=t.length;e0&&{height:this.colorComponentsHeight,formatLabel:this.colorComponentsFormatLabelConfig,inputText:this.colorComponentsInputTextConfig,space:this.colorComponentsSpace};var a=new TI(t,{width:s,height:n,background:e,space:this.colorPickerSpace,hPalette:{position:this.colorPickerHPalettePosition},colorComponents:r,value:this.value});return t.add.existing(a),a},MI={openColorPicker:function(){if(!this.colorPicker){var t=OI.call(this).layout(),e=new z_(t,{duration:{in:this.colorPickerEaseInDuration,out:this.colorPickerEaseOutDuration},transitIn:this.colorPickerTransitInCallback,transitOut:this.colorPickerTransitOutCallback,expandDirection:this.colorPickerExpandDirection,alignTargetX:this,alignTargetY:this,bounds:this.colorPickerBounds,touchOutsideClose:!0}).on("open",(function(){t.on("valuechange",(function(t){this.setValue(t)}),this)}),this).on("close",(function(){this.colorPicker=void 0,this.dropDownBehavior=void 0}),this);return this.colorPicker=t,this.dropDownBehavior=e,this.pin(t),this}}};Object.assign(MI,KB);const EI=Phaser.Utils.Objects.GetValue;class _I extends $B{constructor(t,e){void 0===e&&(e={}),super(t,e),this.type="rexColorInput",e.hasOwnProperty("colorPicker")||(e.colorPicker={background:{color:0}});var i=e.colorPicker,s=!1!==i&&null!==i;if(s){var r;this.setColorPickerSize(EI(i,"width",160),EI(i,"height",170));var n=EI(i,"background");r=n?function(t){return vP(t,n)}:EI(i,"createBackgroundCallback"),this.setCreateColorPickerBackgroundCallback(r),this.setColorPickerHPalettePosition(EI(i,"hPalettePosition",0)),this.setColorPickerExpandDirection(EI(i,"expandDirection")),this.setColorPickerEaseInDuration(EI(i,"easeIn",200)),this.setColorPickerEaseOutDuration(EI(i,"easeOut",200)),this.setColorPickerTransitInCallback(EI(i,"transitIn")),this.setColorPickerTransitOutCallback(EI(i,"transitOut")),this.setColorPickerBounds(EI(i,"bounds"));var a=EI(i,"space");void 0===a&&(a={left:10,right:10,top:10,bottom:10,item:8}),this.setColorPickerSpace(a)}var o=e.colorComponents;if(s&&!1!==o&&null!==o){this.setColorComponentsHeight(EI(o,"height",30)),this.setColorComponentsFormatLabelConfig(EI(o,"formatLabel"));var h=EI(o,"inputText");h||(h=EI(e,"inputText")),this.setColorComponentsInputTextConfig(h);var l=EI(o,"space");void 0===l&&(l={item:8}),this.setColorComponentsSpace(l)}var d=this.childrenMap.swatch;d&&s&&this.onClick(d,this.openColorPicker,this)}}Object.assign(_I.prototype,MI),t.register("colorInput",(function(t){var e=new _I(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ColorInput",_I),t.register("colorInputLite",(function(t){var e=new $B(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ColorInputBase",$B),t.register("colorPicker",(function(t){var e=new mI(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ColorPicker",mI),t.register("colorComponents",(function(t){var e=new SI(this.scene,t);return this.scene.add.existing(e),e})),P(window,"RexPlugins.UI.ColorComponents",SI);var RI=function(t){for(var e,i=t.scene.input,s=i.manager,r=s.pointersTotal,n=s.pointers,a=0;a0&&c0&&u0&&b0&&x * @copyright 2019 Photon Storm Ltd. diff --git a/docs/site/search/search_index.json b/docs/site/search/search_index.json index e10b5758d6..3c0b6c7ca7 100644 --- a/docs/site/search/search_index.json +++ b/docs/site/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Home","text":""},{"location":"#phaser","title":"Phaser","text":"

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

"},{"location":"#links","title":"Links","text":""},{"location":"#phaser3","title":"Phaser3","text":"
  • FAQ
  • Official discord channel
  • API document
  • Examples
  • Bug report
"},{"location":"#rex-plugins","title":"Rex plugins","text":"
  • Plugin list
    • Demos
  • Discord channel
  • Bug report
  • Feature suggestion & discussion
"},{"location":"achievements/","title":"CSV Achievements","text":""},{"location":"achievements/#introduction","title":"Introduction","text":"

Achievements in a csv table.

  • Author: Rex
  • Member of scene
"},{"location":"achievements/#usage","title":"Usage","text":"

Sample code

"},{"location":"achievements/#install-plugin","title":"Install plugin","text":""},{"location":"achievements/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexachievementsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexachievementsplugin.min.js', true);\n
  • Add conditions-table object
    var achievements = scene.plugins.get('rexachievementsplugin').add();\n
"},{"location":"achievements/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import AchievementsPlugin from 'phaser3-rex-plugins/plugins/achievements-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAchievements',\nplugin: AchievementsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add conditions-table object
    var achievements = scene.plugins.get('rexAchievements').add();\n
"},{"location":"achievements/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Achievements from 'phaser3-rex-plugins/plugins/achievements.js';\n
  • Add conditions-table object
    var achievements = new Achievements();\n
"},{"location":"achievements/#create-instance","title":"Create instance","text":"
var achievements = scene.plugins.get('rexAchievements').add();\n
"},{"location":"achievements/#load-table-from-csv-string","title":"Load table from csv string","text":"
achievements.loadCSV(csvString, {\n// delimiter: ','\n});\n

For exameple, csv string

A A Lv1 Ach1 >= 10 < 20 Lv1 Ach2 >= 20 < 50 Lv1 Ach3 >= 50
,A,A\nLv1,Ach1,>= 10,<= 20,\nLv1,Ach2,>= 20,< 50,\nLv1,Ach3,>= 50,,\n
  • 1st column : Level names
  • 2nd column : Achievement names
  • Other columns : Condtions
  • 1st row : Variable names of conditions.

means that:

Lv1, Ach1: (A>=10) && (A<20)\nLv1, Ach2: (A>=20) && (A<50)\nLv1, Ach3: (A>=50)\n
"},{"location":"achievements/#test","title":"Test","text":"
  1. Run test
    var achievements.runTest(levelName, values);\n
    • levelName : Level name, in 1st column of achievements table.
    • values : Inputs in Key-value pairs
  2. Get obtained states
    var states = achievements.getObtainedState(levelName);\n
    • states : Obtained states of levelName
      {\nachievementName: {\nwasObtained: boolean,\njustObtained: boolean\n}\n}\n
      • wasObtained : Obtained this achievement achievementName before last testing.
      • justObtained : Obtained this achievement achievementName at last testing.

or

var states = achievements.getTestResults(levelName, values);\n
"},{"location":"achievements/#get-obtained-states","title":"Get obtained states","text":"
  • Get obtained states of an achievement in a level
    var state = achievements.getObtainedState(levelName, achievementName);\n
    • state : Obtained states of achievementName, in level levelName
      {\nwasObtained: boolean,\njustObtained: boolean\n}\n
      • wasObtained : Obtained this achievement achievementName before last testing.
      • justObtained : Obtained this achievement achievementName at last testing.
  • Get obtained states of a level
    var state = achievements.getObtainedState(levelName);\n
    • states : Obtained states of levelName
      {\nachievementName: {\nwasObtained: boolean,\njustObtained: boolean\n}\n}\n
  • Get obtained states of all levels
    var state = achievements.getObtainedState();\n// var state = achievements.getObtainedStates();\n
    • states : Obtained states of all levels
      {\nlevelName: {\nachievementName: {\nwasObtained: boolean,\njustObtained: boolean\n}\n}\n}\n
  • For each obtained state in a level
    achievements.forEachObtainedState(levelName, function(levelName, achievementName, state) {\n\n}, scope)\n
    • state : Obtained states of achievementName, in level levelName
      {\nwasObtained: boolean,\njustObtained: boolean\n}\n
"},{"location":"achievements/#get-name","title":"Get name","text":"
  • Name of levels
    var names = achievements.getLevelNames();\n// var names = achievements.getLevelNames(out);\n
  • Name of achievements in a level
    var names = achievements.getAchievementNames(levelName);\n// var names = achievements.getAchievementNames(levelName, out);\n
"},{"location":"achievements/#save-load-obtained-states","title":"Save & load obtained states","text":"
  • Get obtained states
    var states = achievements.getObtainedStates();\n
  • Load obtained states
    achievements.loadObtainedStates(states);\n
"},{"location":"achievements/#set-obtained-state","title":"Set obtained state","text":"
  • Set wasObtained, justObtained properties to true.
    achievements.setObtainedState(levelName, achievementName);\n
  • Set wasObtained, justObtained properties to false.
    achievements.clearObtainedState(levelName, achievementName);\n// achievements.setObtainedState(levelName, achievementName, false);\n
"},{"location":"alphamaskimage/","title":"Alpha mask image","text":""},{"location":"alphamaskimage/#introduction","title":"Introduction","text":"

Load a texture, then apply an alpha mask from another texture. Extended from canvas plugin.

  • Author: Rex
  • Game object
"},{"location":"alphamaskimage/#live-demos","title":"Live demos","text":"
  • Alpha-mask-image
"},{"location":"alphamaskimage/#usage","title":"Usage","text":"

Sample code

"},{"location":"alphamaskimage/#install-plugin","title":"Install plugin","text":""},{"location":"alphamaskimage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexalphamaskimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexalphamaskimageplugin.min.js', true);\n
  • Add alpha-mask-image object
    var image = scene.add.rexAlphaMaskImage(x, y, key, frame, config);\n
"},{"location":"alphamaskimage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import AlphaMaskImagePlugin from 'phaser3-rex-plugins/plugins/alphamaskimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAlphaMaskImagePlugin',\nplugin: AlphaMaskImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add alpha-mask-image object
    var image = scene.add.rexAlphaMaskImage(x, y, key, frame, config);\n
"},{"location":"alphamaskimage/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import AlphaMaskImage from 'phaser3-rex-plugins/plugins/alphamaskimage.js';\n
  • Add alpha-mask-image object
    var image = new AlphaMaskImage(scene, x, y, key, frame, config);\nscene.add.existing(image);\n
"},{"location":"alphamaskimage/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAlphaMaskImagePlugin',\nplugin: AlphaMaskImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"alphamaskimage/#create-instance","title":"Create instance","text":"
var image = scene.add.rexAlphaMaskImage(x, y, key, frame, {\nmask: {\nkey: textureKey,\n// frame: frameName,\n// invertAlpha: false,\n// scale: undefined,\n}\n\n// backgroundColor: undefined,\n});\n

or

var image = scene.add.rexAlphaMaskImage(x, y, key, {\nmask: {\nkey: textureKey,\n// frame: frameName,\n// invertAlpha: false,\n// scale: undefined,\n}\n\n// backgroundColor: undefined,\n});\n
  • key, frame : Texture key, frame name of target texture.
  • mask.key, mask.frame : Texture key, frame name of the mask texture.
  • mask.invertAlpha :
    • false : Mask non-alpha (alpha === 0) area. Default behavior.
    • true : Mask alpha (alpha > 0) area.
  • mask.scale :
    • undefined : Expand mask texture size to fit target texture.
    • A number : Scale mask texture size.
  • backgroundColor : Background color filled with masked area.
    • undefiined : No background color.

Add image from JSON

var image = scene.make.rexAlphaMaskImage({\nx: 0,\ny: 0,\nkey: key,\nframe: name,\nmask: {\nkey: textureKey,\n// frame: frameName,\n// invertAlpha: false,\n// scale: undefined,\n}\n\n// backgroundColor: undefined,\n\nadd: true\n});\n
"},{"location":"alphamaskimage/#custom-class","title":"Custom class","text":"
  • Define class
    class MyImage extends AlphaMaskImage {\nconstructor(scene, x, y, key, frame, config) {\nsuper(scene, x, y, key, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyImage(scene, key, frame, config);\n
"},{"location":"alphamaskimage/#set-texture","title":"Set texture","text":"
image.setTexture(key, frame);\n// image.setTexture(key, frame, mask);\n

or

image.setTexture(key, frame, {\nmask: {\nkey: textureKey,\n// frame: frameName,\n// invertAlpha: false,\n// scale: undefined,\n}\n\n// backgroundColor: undefined,\n});\n
  • mask.key, mask.frame : Texture key, frame name of the mask texture.
  • mask.invertAlpha :
    • false : Mask non-alpha (alpha === 0) area. Default behavior.
    • true : Mask alpha (alpha > 0) area.
  • mask.scale :
    • undefined : Expand mask texture size to fit target texture.
    • A number : Scale mask texture size.
  • backgroundColor : Background color filled with masked area.
    • undefiined : No background color.
"},{"location":"alphamaskimage/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"alphamaskimage/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"alphamaskimage/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"anchor/","title":"Anchor","text":""},{"location":"anchor/#introduction","title":"Introduction","text":"

Set size and position based on visible window.

Note

Visible window will be changed when scale mode is ENVELOP, WIDTH_CONTROLS_HEIGHT, or HEIGHT_CONTROLS_WIDTH.

  • Author: Rex
  • Behavior of game object
"},{"location":"anchor/#live-demos","title":"Live demos","text":"
  • Anchor
  • Resize
  • Camera zoom/scroll
"},{"location":"anchor/#usage","title":"Usage","text":"

Sample code

"},{"location":"anchor/#install-plugin","title":"Install plugin","text":""},{"location":"anchor/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexanchorplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexanchorplugin.min.js', true);\n
  • Add anchor behavior
    var anchor = scene.plugins.get('rexanchorplugin').add(gameObject, config);\n
"},{"location":"anchor/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import AnchorPlugin from 'phaser3-rex-plugins/plugins/anchor-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAnchor',\nplugin: AnchorPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add anchor behavior
    var anchor = scene.plugins.get('rexAnchor').add(gameObject, config);\n
"},{"location":"anchor/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Anchor from 'phaser3-rex-plugins/plugins/anchor.js';\n
  • Add anchor behavior
    var anchor = new Anchor(gameObject, config);\n
"},{"location":"anchor/#create-instance","title":"Create instance","text":"
var anchor = scene.plugins.get('rexAnchor').add(gameObject, {\n// left: '0%+0',\n// right: '0%+0',\n// centerX: '0%+0',\n// x: '0%+0',\n\n// top: '0%+0',\n// bottom: '0%+0',\n// centerY: '0%+0',\n// y: '0%+0',\n\n// width: '100%+0',\n// height: '100%+0',\n// onResizeCallback: function(width, height, gameObject, anchor) {},\n// onResizeCallbackScope: undefined,\n\n// onUpdateViewportCallback: function(viewport, gameObject, anchor) {},\n// onUpdateViewportCallbackScope: undefined,\n\n// enable: true\n});\n
  • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
    • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • 'left'(=0%), 'center'(=50%), 'right'(=100%)
      • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
    • Offset : '+n', or '-n'.

For example, anchor game object's left bound to viewport's left+10, centerY to viewport's center

{\nleft: 'left+10',\ncenterY: 'center'\n}\n
  • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
    • Percentage of visible width/height : 'p%', p: 0 ~ 100.
    • Padding : '+n', or '-n'.
  • onResizeCallback, onResizeCallbackScope : Callback of resizing game object
    • undefined : Default resize method.
    • Custom method
      function(width, height, gameObject, anchor) {\n// gameObject.setSize(width, height);\n// gameObject.setDisplaySize(width, height);\n// ...\n}\n
    • null or false : No callback
  • onUpdateViewportCallback, onUpdateViewportCallback : Callback invoked when viewport changed (anchor)

    fucntion(viewport, gameObject, anchor) {\n// Can change properties of viewport here\n// var centerX = viewport.centerX,\n//     centerY = viewport.centerY;\n// viewport.width *= 0.8;\n// viewport.height *= 0.9;\n// viewport.centerX = centerX;\n// viewport.centerY = centerY;\n}\n

    • viewport\uff1a A rectangle object
  • enable :

    • undefined, or true : Anchor game object under 'resize' event of scale manager.
    • false : Won't anchor game object automatially.
"},{"location":"anchor/#reset-config","title":"Reset config","text":"
anchor.resetFromJSON({\n// left: '0%+0',\n// right: '0%+0',\n// centerX: '0%+0',\n// x: '0%+0',\n\n// top: '0%+0',\n// bottom: '0%+0',\n// centerY: '0%+0',\n// y: '0%+0',\n\n// width: '100%+0',\n// height: '100%+0',    \n\n// onUpdateViewportCallback: function(viewport, gameObject, anchor) {}\n// onUpdateViewportCallbackScope: undefined,\n})\n
  • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
    • Percentage of visible width/height : 'p%', p: 0~100
      • 'left'(=0%), 'center'(=50%), 'right'(=100%)
      • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
    • Offset : '+n', or '-n'
  • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
    • Percentage of visible width/height : 'p%', p: 0 ~ 100.
    • Padding : '+n', or '-n'.
  • onResizeCallback, onResizeCallbackScope : Callback of resizing game object
    function(width, height, gameObject, anchor) {\n// gameObject.setSize(width, height);\n// gameObject.setDisplaySize(width, height);\n// ...\n}\n
"},{"location":"anchor/#set-onupdateviewport-callback","title":"Set OnUpdateViewport callback","text":"
anchor.setUpdateViewportCallback(callback, scope);\n
  • callback :
    fucntion(viewport, gameObject, anchor) {\n// Can change properties of viewport here\n// var centerX = viewport.centerX,\n//     centerY = viewport.centerY;\n// viewport.width *= 0.8;\n// viewport.height *= 0.9;\n// viewport.centerX = centerX;\n// viewport.centerY = centerY;\n}\n
    • viewport\uff1a A rectangle object
"},{"location":"anchor/#manual-anchor","title":"Manual anchor","text":"
anchor.anchor();\n
"},{"location":"anchor/#auto-anchor","title":"Auto anchor","text":"
  • Anchor game object under 'resize' event of scale manager.
    anchor.autoAnchor();\n// anchor.autoAnchor(true);\n
  • Disable auto-anchor
    anchor.autoAnchor(false);\n
"},{"location":"angle/","title":"Angle","text":""},{"location":"angle/#introduction","title":"Introduction","text":"

Convert angle value, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"angle/#usage","title":"Usage","text":""},{"location":"angle/#degree-radians","title":"Degree <-> Radians","text":"
  • Degree to radians
    var rad = Phaser.Math.DegToRad(deg);\n
  • Radians to degree
    var deg = Phaser.Math.RadToDeg(rad);  // deg : -180 ~ 180\n
"},{"location":"angle/#wrap","title":"Wrap","text":"
  • Wrap angle (radians) in the range of -PI to PI
    var rad = Phaser.Math.Angle.Wrap(angle);\n
  • Wrap angle (radians) in the range of 0 to 2*PI
    var rad = Phaser.Math.Angle.Normalize(angle);\n
  • Wrap angle (degrees) in the range of -180 to 180
    var deg = Phaser.Math.Angle.WrapDegrees(angle);\n
"},{"location":"angle/#angle-between-points","title":"Angle between points","text":"
  • Angle from (0,0) to vector (x2 - x1 , y2 - y1)
    var rad = Phaser.Math.Angle.Between(x1, y1, x2, y2);\n
    var rad = Phaser.Math.Angle.BetweenPoints(point1, point2);\n
"},{"location":"angle/#angle-between-angles","title":"Angle between angles","text":"
  • Shortest angle (degrees) between 2 angles
    var deg = Phaser.Math.Angle.ShortestBetween(angle1, angle2)\n
    • angle1, angle2 : Angle in degrees in the range of -180 to 180
    • deg : Shortest angle in degrees
      • deg > 0 : Counter-ClockWise rotation
      • deg < 0 : ClockWise rotation
"},{"location":"angle/#rotate-around-position","title":"Rotate around position","text":"
  • Rotate a point around x and y by the given angle.
    var out = Phaser.Math.RotateAround(point, x, y, angle);\n
  • Rotate a point around x and y by the given angle and distance.
    var out = Phaser.Math.RotateAroundDistance(point, x, y, angle, distance);\n
"},{"location":"angle/#rotate-to-angle","title":"Rotate to angle","text":"
var rad = Phaser.Math.Angle.RotateTo(currentAngle, targetAngle, lerp)\n
  • currentAngle, : The current angle, in radians.
  • targetAngle : The target angle to rotate to, in radians.
  • lerp : The lerp value to add to the current angle.
"},{"location":"angle/#random-angle","title":"Random angle","text":"
  • Returns a random angle in the range [-pi, pi].
    var angle = Phaser.Math.Angle.Random();\n
  • Returns a random angle in the range [-180, 180].
    var angle = Phaser.Math.Angle.RandomDegrees();\n
"},{"location":"animation/","title":"Animation","text":""},{"location":"animation/#introduction","title":"Introduction","text":"

Animation and animations manager.

  • Author: Richard Davey
"},{"location":"animation/#usage","title":"Usage","text":""},{"location":"animation/#animation-manager","title":"Animation manager","text":""},{"location":"animation/#add-animation","title":"Add animation","text":"
var animationConfig = {\nkey: '',\n\nframes: [],\n\nsortFrames: true,\ndefaultTextureKey: null,\nskipMissedFrames: true,\nrandomFrame: false,\n\n// time\ndelay: 0,\nduration: null,\nframeRate: null,\ntimeScale: 1,\n\n// repeat\nrepeat: 0,              // set to (-1) to repeat forever\nrepeatDelay: 0,\nyoyo: false,\n\n// visible\nshowBeforeDelay: false,\nshowOnStart: false,\nhideOnComplete: false\n};\n\nscene.anims.create(animationConfig);\n
  • key : Unique key of this animation data
  • frames : An array of {key, frame}
    • Properties
      {\nkey: '',\nframe: '', // string, or number\nduration: 0\n}\n
      • duration : The duration, in ms, of this frame of the animation.
    • A string : Texture key.
    • Every frame in the atlas
      scene.anims.generateFrameNames(key);\n
    • Frame sequence indexing from start to end
      var config = ;\nscene.anims.generateFrameNames(key,\n{\nprefix: '',\nstart: 0,\nend: 0,\nsuffix: '',\nzeroPad: 0,\n// outputArray: [], // Append frames into this array\n});\n
      • prefix + Pad(i, zeroPad, '0', 1) + suffix, i: start ~ end
    • Custom frame sequence
      var config = ;\nscene.anims.generateFrameNames(key,\n{\nprefix: '',\nsuffix: '',\nzeroPad: 0,\nframes: [ ... ]\n// outputArray: [], // Append frames into this array\n});\n
      • prefix + Pad(frames[i], zeroPad, '0', 1) + suffix
  • sortFrames : Frame names numerically sorted. Default value is true.
  • defaultTextureKey : The key of the texture all frames of the animation will use. Can be overridden on a per frame basis.
  • skipMissedFrames : Skip frames if the time lags, or always advanced anyway? Default value is true.
  • randomFrame : Start playback of this animation from a randomly selected frame? Default value is false.
  • delay : Delay before starting playback. Value given in milliseconds.
  • duration : How long the animation should play for in milliseconds. If not given its derived from frameRate.
  • frameRate : The frame rate of playback in frames per second. Default value is 24.
  • timeScale : The time scale to be applied to playback of this animation. Default value is 1.
  • repeat : Number of times to repeat the animation. Default value is 0.
    • -1 : Infinity
  • repeatDelay : Delay before the animation repeats. Value given in milliseconds.
  • yoyo : Should the animation yoyo? (reverse back down to the start) before repeating? Default value is false.
  • showBeforeDelay : If this animation has a delay, should it show the first frame immediately (true), or only after the delay (false)
  • showOnStart : Should sprite.visible = true when the animation starts to play? This happens after any delay, if set. Default value is false.
  • hideOnComplete : Should sprite.visible = false when the animation finishes? Default value is false.
"},{"location":"animation/#add-from-aseprite","title":"Add from Aseprite","text":"

Aseprite

scene.anims.createFromAseprite(key);\n// scene.anims.createFromAseprite(key, tags, target);\n
  • key : The key of the loaded Aseprite atlas.
  • tags :
    • undefined : Load all tags.
    • Array of string tag : Load these tags.
  • target : Create the animations on this target Sprite.
    • undefined : Created globally in this Animation Manager. Default behavior.
"},{"location":"animation/#remove-animation","title":"Remove animation","text":"
scene.anims.remove(key);\n
"},{"location":"animation/#delay-between-two-animations","title":"Delay between two animations","text":"
  • Add
    scene.anims.addMix(animA, animB, delay);\n
    • animA, animB : String key of an animation, or an instance of animation.
  • Remove
    scene.anims.removeMix(animA, animB);\n// scene.anims.removeMix(animA);\n
  • Get
    var delay = scene.anims.getMix(animA, animB);\n
"},{"location":"animation/#play-animation","title":"Play animation","text":"
  • Play
    scene.anims.play(key, children);\n
  • Stagger play (delay play)
    scene.anims.staggerPlay(key, children, stagger, staggerFirst);\n
    • children : An array of Game Objects to play the animation on
    • stagger : The amount of time, in milliseconds, to offset each play time by
    • staggerFirst : Set true to apply delay on 1st child
"},{"location":"animation/#pause-all-animations","title":"Pause all animations","text":"
scene.anims.pauseAll();\n
"},{"location":"animation/#resume-all-animations","title":"Resume all animations","text":"
scene.anims.resumeAll();\n
"},{"location":"animation/#global-time-scale","title":"Global time scale","text":"
  • Get
    var timeScale = scene.anims.globalTimeScale;\n
  • Set
    scene.anims.globalTimeScale = timeScale;\n
"},{"location":"animation/#has-animation","title":"Has animation","text":"
var hasAnim = scene.anims.exists(key);\n
"},{"location":"animation/#exportload","title":"Export/load","text":"
  • Export JSON
    var json = scene.anims.toJSON();\n
  • Load from JSON
    scene.anims.fromJSON(json);\n// scene.anims.fromJSON(json, clearCurrentAnimations);\n
    • Load JSON in preload stage javascript scene.load.json(key, url);
    • Load animation in preload stage
      scene.load.animation(key, url);\n
"},{"location":"animation/#events","title":"Events","text":"
  • On add animation
    scene.anims.on('add', function(key, anim) {});\n
  • On remove animation
    scene.anims.on('remove', function(key, anim) {});\n
  • On pause all animations
    scene.anims.on('pauseall', function() {});\n
  • On resume all animations
    scene.anims.on('resumeall', function() {});\n
"},{"location":"animation/#animation-object","title":"Animation object","text":"
var anim = scene.anims.get(key);\n
"},{"location":"animation/#add-frame","title":"Add frame","text":"
  • Append frames
    anim.addFrame(frame);\n
    • frame : scene.anims.generateFrameNames(key, config)
  • Insert frames at index
    anim.addFrameAt(index, frame);\n
    • frame : scene.anims.generateFrameNames(key, config)
"},{"location":"animation/#remove-frame","title":"Remove frame","text":"
  • Remove frame at
    anim.removeFrameAt(index);\n
  • Remove frame
    anim.removeFrame(frame);\n
"},{"location":"animation/#get-frame","title":"Get frame","text":"
  • Has frame index
    var HasFrameAt = anim.checkFrame(index);\n
  • Get frame at index
    var frame = anim.getFrameAt(index);\n
  • Get last frame
    var frame = anim.getLastFrame();\n
"},{"location":"animation/#export","title":"Export","text":"
  • Export JSON
    var json = anim.toJSON();\n
    or
    var jsonString = JSON.stringify(anim);\n
"},{"location":"arcade-body/","title":"Body","text":""},{"location":"arcade-body/#introduction","title":"Introduction","text":"

Arcade physics body.

  • Author: Richard Davey
"},{"location":"arcade-body/#usage","title":"Usage","text":""},{"location":"arcade-body/#get-physics-body","title":"Get physics body","text":"
  1. Enable physics world
  2. Add existing game object(s) to physics world
    • Add a game object
      var gameObject = scene.physics.add.existing(gameObject, bodyType);\n
      • bodyType :
        • 0 : Dynamic body
        • 1 : Static body
    • Add game objects
      scene.physics.world.enable(gameObjects, bodyType);\n
      • gameObjects : An array of game objects, or a group object
      • bodyType :
        • 0 : Dynamic body
        • 1 : Static body
  3. Get physics body
    var body = gameObject.body;\n
"},{"location":"arcade-body/#enable","title":"Enable","text":"

Whether this Body is updated by the physics simulation.

  • Enable (default)
    body.setEnable();\n
    or
    body.enable = true;\n
  • Disable
    body.setEnable(false);\n
    or
    body.enable = false;\n
"},{"location":"arcade-body/#direct-control","title":"Direct control","text":"

Enable directControl when game object is controlled by tween or dragging. Default behavior is disable.

  • Enable
    body.setDirectControl();\n// body.setDirectControl(true);\n
    or
    body.directControl = true;\n
  • Disable
    body.setDirectControl(false);\n
    or
    body.directControl = false;\n
"},{"location":"arcade-body/#immovable","title":"Immovable","text":"

Whether this Body can be moved by collisions with another Body.

  • Enable
    body.setImmovable();\n// body.immovable = true;\n
  • Disable (defalut)
    body.setImmovable(false);\n// body.immovable = false;\n
  • Get
    var immovable = body.immovable;\n
"},{"location":"arcade-body/#pushable","title":"Pushable","text":"

Sets if this Body can be pushed by another Body.

  • Enable (default value of dynamic body)
    body.pushable = true;\n
  • Disable, reflect back all of the velocity it is given to the colliding body.
    body.pushable = false;\n
  • Get
    var pushable = body.pushable;\n
"},{"location":"arcade-body/#moveable","title":"Moveable","text":"

Whether the Body's position and rotation are affected by its velocity, acceleration, drag, and gravity.

  • Enable (default)
    body.moves = true;\n
  • Disable
    body.moves = false;\n
  • Get
    var moves = body.moves;\n
"},{"location":"arcade-body/#destroy","title":"Destroy","text":"

Physics body will be destroyed automatically when game object is destroyed.

"},{"location":"arcade-body/#movement","title":"Movement","text":""},{"location":"arcade-body/#velocity","title":"Velocity","text":"
  • Set
    body.setVelocity(x,y);\n
    or
    body.setVelocityX(x);\nbody.setVelocityY(x);\n
  • Get
    var vx = body.velocity.x;\nvar vy = body.velocity.y;\n
"},{"location":"arcade-body/#max-speed","title":"Max speed","text":"
  • Set
    body.setMaxSpeed(speed);\n
  • Get
    var speed = body.maxSpeed;\n
"},{"location":"arcade-body/#max-velocity","title":"Max velocity","text":"
  • Set
    body.setMaxVelocity(x, y);\n
    or
    body.setMaxVelocityX(x);\nbody.setMaxVelocityY(y);\n
  • Get
    var vx = body.maxVelocity.x;\nvar vy = body.maxVelocity.y;\n
"},{"location":"arcade-body/#acceleration","title":"Acceleration","text":"
  • Set
    body.setAcceleration(x, y);\n
    or
    body.setAccelerationX(x);\nbody.setAccelerationY(y);\n
  • Get
    var ax = body.acceleration.x;\nvar ay = body.acceleration.y;\n
"},{"location":"arcade-body/#gravity","title":"Gravity","text":"
  • Set
    body.setGravity(x, y);\n
    or
    body.setGravityX(x);\nbody.setGravityY(y);\n
  • Get
    var gx = body.gravity.x;\nvar gy = body.gravity.y;\n
  • Enables (default)
    body.setAllowGravity();\n
  • Disable
    body.setAllowGravity(false);\n
"},{"location":"arcade-body/#drag","title":"Drag","text":"

Reduces speed per second.

  • Set
    body.setDrag(x, y);\n
    or
    body.setDragX(x);\nbody.setDragY(y);\n
  • Get
    var dx = body.drag.x;\nvar dy = body.drag.y;\n
  • Enables (default)
    body.setAllowDrag();\n
  • Disable
    body.setAllowDrag(false);\n
  • Enable Damping (default: disable)
    body.setDamping(true);\n// body.useDamping = true;\n
"},{"location":"arcade-body/#slide-factor","title":"Slide factor","text":"

The Slide Factor controls how much velocity is preserved when this Body is pushed by another Body.

body.slideFactor.set(x, y);\n
  • x, y :
    • 1 : Take on all velocity given in the push. Default value.
    • 0 : Allow this Body to be pushed but then remain completely still after the push ends, such as you see in a game like Sokoban.
    • Other value between 0 ~ 1 : Keep x/y of the original velocity when the push ends.
      • Combine this with the setDrag() method to create deceleration.
"},{"location":"arcade-body/#reset-position","title":"Reset position","text":"
body.reset(x, y);\n
"},{"location":"arcade-body/#stop","title":"Stop","text":"

Sets acceleration, velocity, and speed to zero.

body.stop();\n
"},{"location":"arcade-body/#friction","title":"Friction","text":"

If this Body is immovable and in motion, this the proportion of this Body's movement received by the riding body on each axis.

  • Set
    body.setFriction(x, y);\n
    or
    body.setFrictionX(x);\nbody.setFrictionY(y);\n
  • Get
    var fx = body.friction.x;\nvar fy = body.friction.y;\n
"},{"location":"arcade-body/#speed","title":"Speed","text":"
  • The absolute (non-negative) change in this Body's horizontal/vertical position from the previous step.
    var dx = body.deltaAbsX();\nvar dy = body.deltaAbsY();\n
"},{"location":"arcade-body/#rotation","title":"Rotation","text":""},{"location":"arcade-body/#allow-rotation","title":"Allow rotation","text":"

Whether this Body's rotation is affected by its angular acceleration and velocity.

  • Enable (default)
    body.setAllowRotation();\n
  • Disable
    body.setAllowRotation(false);\n
  • Get
    var allowRotation = body.allowRotation;\n
"},{"location":"arcade-body/#angular-velocity","title":"Angular velocity","text":"
  • Set
    body.setAngularVelocity(v);\n
  • Get
    var av = body.angularVelocity;\n
"},{"location":"arcade-body/#angular-acceleration","title":"Angular acceleration","text":"
  • Set
    body.setAngularAcceleration(v);\n
  • Get
    var aa = body.angularAcceleration;\n
"},{"location":"arcade-body/#angular-drag","title":"Angular drag","text":"

Reduces angular speed per second.

  • Set
    body.setAngularDrag(v);\n
  • Get
    var ad = body.angularDrag;\n
"},{"location":"arcade-body/#collision","title":"Collision","text":""},{"location":"arcade-body/#collision-category","title":"Collision category","text":"

A body is only below to one collision category. A body can collide with multiple collision categories. The default is that all bodies collide with all others.

  • Collision category
    • Get
      var collisionCategory = body.collisionCategory;\n
    • Set
      body.setCollisionCategory(category);\n
      • category :
        • (1 << 0)
        • (1 << 1)
        • (1 << 2)
        • ...
        • (1 << 31)
    • Reset collision category, to default behavior (all bodies collide with all others)
      body.resetCollisionCategory();\n
      • Set collisionCategory to 1.
      • Set collisionMask to 1
  • Collision mask
    • Get
      var collisionMask = body.collisionMask;\n
    • Set
      body.setCollidesWith(categories);\n
      • categories : A single category value, or an array of them.
    • Add
      body.addCollidesWith(category):\n
      • category : A single category value.
    • Remove
      body.removeCollidesWith(category);\n
      • category : A single category value.
"},{"location":"arcade-body/#collision-bound","title":"Collision bound","text":"
  • Rectangle
    body.setSize(width, height, center);\n
    • center : false to set body's offset to (0, 0).
      • Not work in Graphics object.
  • Circle
    body.setCircle(radius, offsetX, offsetY);\n
"},{"location":"arcade-body/#offset","title":"Offset","text":"
body.setOffset(x, y);\n
"},{"location":"arcade-body/#push-out","title":"Push out","text":"
scene.physics.add.collider(objectsA, objectsB);\n
  • objectsA, objectsB :
    • A game object
    • Game objects in array (Add or remove game objects)
    • Physics group (Add or remove game objects)
    • Group (Add or remove game objects)
"},{"location":"arcade-body/#callbacks","title":"Callbacks","text":"

Add collider

"},{"location":"arcade-body/#point-inside","title":"Point inside","text":"
var hit = body.hitTest(x, y);\n
"},{"location":"arcade-body/#is-colliding","title":"Is colliding","text":"
  • Is colliding this tick
    var isColliding = body.touching;\n
    • isColliding :
      {\nnone: true,\nup: true,\ndown: true,\nleft: true,\nright: true\n}\n
  • Was colliding previous tick
    var wasColliding = body.wasTouching;\n
    • wasColliding :
      {\nnone: true,\nup: true,\ndown: true,\nleft: true,\nright: true\n}\n
"},{"location":"arcade-body/#bounce","title":"Bounce","text":"
  • Set
    body.setBounce(x, y);\n
    or
    body.setBounceX(x);\nbody.setBounceY(y);\n
  • Get
    var bx = body.bounce.x;\nvar by = body.bounce.y;\n
"},{"location":"arcade-body/#world-bounds","title":"World bounds","text":"
  • Default world bounds
  • Custom world bounds :
    body.setBoundsRectangle(bounds);\n
    • bounds : A rectangle object.
  • Enable
    body.setCollideWorldBounds();\n
  • Disable (default)
    body.setCollideWorldBounds(false);\n
  • Get world bounds rectangle
    var top = body.world.bounds.top;\nvar bottom = body.world.bounds.bottom;\nvar left = body.world.bounds.left;\nvar right = body.world.bounds.right;\n
"},{"location":"arcade-body/#blocked","title":"Blocked","text":"

Whether this Body is colliding with a tile or the world boundary.

  • Blocked when moveing down
    var onFloor = body.onFloor(); // blocked.down\n
  • Blocked when moveing up
    var onCeiling = body.onCeiling();  // blocked.up\n
  • Blocked when moveing left or right
    var onWall = body.onWall();  // blocked.left || this.blocked.right\n
  • State
    var blocked = body.blocked;\n
    • blocked :
      {\nnone: true,\nup: false,\ndown: false,\nleft: false,\nright: false\n}\n
"},{"location":"arcade-body/#mass","title":"Mass","text":"
  • Set
    body.setMass(m);\n
  • Get
    var m = body.mass;\n
"},{"location":"arcade-body/#static-body","title":"Static body","text":""},{"location":"arcade-body/#sync","title":"Sync","text":"

Syncs the Bodies position and size with its parent Game Object.

body.updateFromGameObject();\n
"},{"location":"arcade-body/#debug","title":"Debug","text":"
  • Bounds of Body
    • Enable drawing body
      body.debugShowBody = true;\n
    • Color
      body.debugBodyColor = 0xff00ff;\n
  • Direction and magnitude of velocity
    • Enable drawing body
      body.debugShowVelocity = true;\n
"},{"location":"arcade-gameobject/","title":"Game object","text":""},{"location":"arcade-gameobject/#introduction","title":"Introduction","text":"

Arcade physics Image/Sprite/Group object.

  • Author: Richard Davey
"},{"location":"arcade-gameobject/#usage","title":"Usage","text":""},{"location":"arcade-gameobject/#add-physics-object","title":"Add physics object","text":"

Enable physics world

"},{"location":"arcade-gameobject/#image-object","title":"Image object","text":"
  • Static object, extends from Image object
    var image = scene.physics.add.staticImage(x, y, key);\n
  • Dynamic object, extends from Image object
    var image = scene.physics.add.image(x, y, key);\n
"},{"location":"arcade-gameobject/#sprite-object","title":"Sprite object","text":"
  • Static object, extends from Sprite object
    var image = scene.physics.add.staticSprite(x, y, key, frame);\n
  • Dynamic object, extends from Sprite object
    var image = scene.physics.add.sprite(x, y, key, frame);\n
"},{"location":"arcade-gameobject/#group","title":"Group","text":"
  • Static sprite objects, extends from Group object
    var group = scene.physics.add.staticGroup(children, config);\n// var group = scene.physics.add.staticGroup(config);\n
  • Dynamic sprite objects, extends from Group object
    var group = scene.physics.add.group(children, config);\n// var group = scene.physics.add.staticGroup(config);\n
    • config
      var config = {\nclassType: ArcadeSprite,\nenable: true,\ncollideWorldBounds: false,\ncustomBoundsRectangle: null,\naccelerationX: 0,\naccelerationY: 0,\nallowDrag: true,\nallowGravity: true,\nallowRotation: true,\nuseDamping: false,\nbounceX: 0,\nbounceY: 0,\ndragX: 0,\ndragY: 0,\ngravityX: 0,\ngravityY: 0,\nfrictionX: 0,\nfrictionY: 0,\nmaxSpeed: -1,\nvelocityX: 0,\nvelocityY: 0,\nmaxVelocityX: 10000,\nmaxVelocityY: 10000,\nangularVelocity: 0,\nangularAcceleration: 0,\nangularDrag: 0,\nmass: 0,\nimmovable: false,\n\nmaxSize: -1,\nrunChildUpdate: false\n};\n
"},{"location":"arcade-gameobject/#enable","title":"Enable","text":"
  • Enable body
    gameObject.enableBody();\n// gameObject.enableBody(false, 0, 0, enableGameObject, showGameObject);\n
    • Enable and reset position
      gameObject.enableBody(true, x, y);\n// gameObject.enableBody(true, x, y, enableGameObject, showGameObject);\n
    • enableGameObject : Also activate this Game Object.
    • showGameObject : Also show this Game Object.
  • Disable body
    gameObject.disableBody();\n// gameObject.disableBody(disableGameObject, hideGameObject);\n
    • disableGameObject : Also deactivate this Game Object.
    • hideGameObject : Also hide this Game Object.
"},{"location":"arcade-gameobject/#movement","title":"Movement","text":""},{"location":"arcade-gameobject/#velocity","title":"Velocity","text":"
  • Set
    gameObject.setVelocity(x, y);\n
    or
    gameObject.setVelocityX(x);\ngameObject.setVelocityY(y);\n
  • Get
    var vx = gameObject.body.velocity.x;\nvar vy = gameObject.body.velocity.y;\n
"},{"location":"arcade-gameobject/#max-velocity","title":"Max velocity","text":"
  • Set
    gameObject.setMaxVelocity(x, y);\n
  • Get
    var vx = gameObject.body.maxVelocity.x;\nvar vy = gameObject.body.maxVelocity.y;\n
"},{"location":"arcade-gameobject/#acceleration","title":"Acceleration","text":"
  • Set
    gameObject.setAcceleration(x, y);\n
    or
    gameObject.setAccelerationX(x);\ngameObject.setAccelerationY(y);\n
  • Get
    var ax = gameObject.body.acceleration.x;\nvar ay = gameObject.body.acceleration.y;\n
"},{"location":"arcade-gameobject/#gravity","title":"Gravity","text":"
  • Set
    gameObject.setGravity(x, y);\n
    or
    gameObject.setGravityX(x);\ngameObject.setGravityY(y);\n
  • Get
    var gx = gameObject.body.gravity.x;\nvar gy = gameObject.body.gravity.y;\n
"},{"location":"arcade-gameobject/#drag","title":"Drag","text":"
  • Set
    gameObject.setDrag(x, y);\n
    or
    gameObject.setDragX(x);\ngameObject.setDragY(y);\n
  • Get
    var dx = gameObject.body.drag.x;\nvar dy = gameObject.body.drag.y;\n
  • Enable damping
    gameObject.setDamping(value);\n
"},{"location":"arcade-gameobject/#immovable","title":"Immovable","text":"
  • Enable
    gameObject.setImmovable();\n
  • Disable
    gameObject.setImmovable(false);\n
  • Get
    var immovable = gameObject.body.immovable;\n
"},{"location":"arcade-gameobject/#pushable","title":"Pushable","text":"
  • Enable
    gameObject.setPushable();\n
  • Disable
    gameObject.setPushable(false);\n
  • Get
    var pushable = gameObject.body.pushable;\n
"},{"location":"arcade-gameobject/#slide-factor","title":"Slide factor","text":"

The Slide Factor controls how much velocity is preserved when this Body is pushed by another Body.

gameObject.setSlideFactor(x, y);\n
  • x, y :
    • 1 : Take on all velocity given in the push. Default value.
    • 0 : Allow this Body to be pushed but then remain completely still after the push ends, such as you see in a game like Sokoban.
    • Other value between 0 ~ 1 : Keep x/y of the original velocity when the push ends.
      • Combine this with the setDrag() method to create deceleration.
"},{"location":"arcade-gameobject/#friction","title":"Friction","text":"

If this Body is immovable and in motion, this the proportion of this Body's movement received by the riding body on each axis.

  • Set
    gameObject.setFriction(x, y);\n
    or
    gameObject.setFrictionX(x);\ngameObject.setFrictionY(y);\n
  • Get
    var fx = gameObject.body.friction.x;\nvar fy = gameObject.body.friction.y;\n
"},{"location":"arcade-gameobject/#direct-control","title":"Direct control","text":"

Enable directControl when game object is controlled by tween or dragging. Default behavior is disable.

  • Enable
    gameObject.setDirectControl();\n// gameObject.setDirectControl(true);\n
  • Disable
    gameObject.setDirectControl(false);\n

Use case

Enable setDirectControl when game object is controlled by tween or dragging.

"},{"location":"arcade-gameobject/#rotation","title":"Rotation","text":""},{"location":"arcade-gameobject/#allow-rotation","title":"Allow rotation","text":"

Whether this Body's rotation is affected by its angular acceleration and velocity.

  • Enable (default)
    body.setAllowRotation();\n
  • Disable
    body.setAllowRotation(false);\n
  • Get
    var allowRotation = gameObject.body.allowRotation;\n
"},{"location":"arcade-gameobject/#angular-velocity","title":"Angular velocity","text":"
  • Set
    gameObject.setAngularVelocity(v);\n
  • Get
    var av = gameObject.body.angularVelocity;\n
"},{"location":"arcade-gameobject/#angular-acceleration","title":"Angular acceleration","text":"

-Set

gameObject.setAngularAcceleration(v);\n
- Get
var aa = gameObject.body.angularAcceleration;\n

"},{"location":"arcade-gameobject/#angular-drag","title":"Angular drag","text":"
  • Set
    gameObject.setAngularDrag(v);\n
  • Get
    var ad = gameObject.body.angularDrag;\n
"},{"location":"arcade-gameobject/#collision","title":"Collision","text":""},{"location":"arcade-gameobject/#collision-category","title":"Collision category","text":"

A body is only below to one collision category. A body can collide with multiple collision categories. The default is that all bodies collide with all others.

  • Collision category
    • Get
      var collisionCategory = gameObject.body.collisionCategory;\n
    • Set
      gameObject.setCollisionCategory(category);\n
      • category :
        • (1 << 0)
        • (1 << 1)
        • (1 << 2)
        • ...
        • (1 << 31)
    • Reset collision category, to default behavior (all bodies collide with all others)
      gameObject.resetCollisionCategory();\n
      • Set collisionCategory to 1.
      • Set collisionMask to 1
  • Collision mask
    • Get
      var collisionMask = gameObject.body.collisionMask;\n
    • Set
      gameObject.setCollidesWith(categories);\n
      • categories : A single category value, or an array of them.
    • Add
      gameObject.addCollidesWith(category):\n
      • category : A single category value.
    • Remove
      gameObject.removeCollidesWith(category);\n
      • category : A single category value.
"},{"location":"arcade-gameobject/#collision-bound","title":"Collision bound","text":"
  • Rectangle
    gameObject.setBodySize(width, height, center);\n
    • center : false to set body's offset to (0, 0)
  • Circle
    gameObject.setCircle(radius, offsetX, offsetY);\n
"},{"location":"arcade-gameobject/#offset","title":"Offset","text":"
gameObject.setOffset(x, y);\n
"},{"location":"arcade-gameobject/#push-out","title":"Push out","text":"
scene.physics.add.collider(objectsA, objectsB);\n
  • objectsA, objectsB :
    • A game object
    • Game objects in array (Add or remove game objects)
    • Physics group (Add or remove game objects)
    • Group (Add or remove game objects)
"},{"location":"arcade-gameobject/#callbacks","title":"Callbacks","text":"

Add collider

"},{"location":"arcade-gameobject/#point-inside","title":"Point inside","text":"
var hit = gameObject.hitTest(x, y);\n
"},{"location":"arcade-gameobject/#bounce","title":"Bounce","text":"
  • Set
    gameObject.setBounce(x, y);\n
    or
    gameObject.setBounceX(x);\ngameObject.setBounceY(y);\n
  • Get
    var bx = gameObject.body.bounce.x;\nvar by = gameObject.body.bounce.y;\n
  • Enable bounce when colliding with the world boundary
    gameObject.setCollideWorldBounds();\n
  • Disable bounce when colliding with the world boundary
    gameObject.setCollideWorldBounds(false);\n
"},{"location":"arcade-gameobject/#mass","title":"Mass","text":"
  • Set
    gameObject.setMass(m);\n
  • Get
    var m = gameObject.body.mass;\n
"},{"location":"arcade-gameobject/#static-game-object","title":"Static game object","text":""},{"location":"arcade-gameobject/#sync","title":"Sync","text":"

Syncs the Bodies position and size in static game object.

gameObject.refreshBody();\n
"},{"location":"arcade-gameobject/#methods-of-group","title":"Methods of group","text":"
group.setVelocity(x, y, step);\n
group.setVelocityX(value, step);\n
group.setVelocityY(value, step);\n
group.refresh();  // call this method when position of game objects were changed in static object group\n
"},{"location":"arcade-gameobject/#debug","title":"Debug","text":"
gameObject.setDebug(showBody, showVelocity, bodyColor);\n
gameObject.setDebugBodyColor(bodyColor);\n
"},{"location":"arcade-tcrp-player/","title":"Player","text":""},{"location":"arcade-tcrp-player/#introduction","title":"Introduction","text":"

Player of T ime-C ommand-R ecorder-P layer with Arcade physics engine, to run commands on time.

  • Author: Rex
  • Member of scene

Arcade physics engine is fixed-step based, not tick time based.

This Arcade-TCRP has better result of replaying, which store step count via WORLD_STEP(worldstep) event.

"},{"location":"arcade-tcrp-player/#live-demos","title":"Live demos","text":"
  • Player
"},{"location":"arcade-tcrp-player/#usage","title":"Usage","text":"

Sample code

"},{"location":"arcade-tcrp-player/#install-plugin","title":"Install plugin","text":""},{"location":"arcade-tcrp-player/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexarcadetcrpplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexarcadetcrpplugin.min.js', true);\n
  • Create instance
    var player = scene.plugins.get('rexarcadetcrpplugin').addPlayer(scene, config);\n
"},{"location":"arcade-tcrp-player/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TCRPPlugin from 'phaser3-rex-plugins/plugins/arcadetcrp-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTCRP',\nplugin: TCRPPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var player = scene.plugins.get('rexTCRP').addPlayer(scene, config);\n
"},{"location":"arcade-tcrp-player/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TCRP from 'phaser3-rex-plugins/plugins/arcadetcrp.js';\n
  • Create instance
    var player = new TCRP.Player(scene, config);\n
"},{"location":"arcade-tcrp-player/#create-instance","title":"Create instance","text":"
var player = scene.plugins.get('rexTCRP').addPlayer(scene, {\n// commands: [],       // [[time, command], [time, command], ...]\n// timeScale: 1,\n// scope: undefined\n});\n
  • commands : see next section
  • timeScale : An integer equal or larger than 1
"},{"location":"arcade-tcrp-player/#load-commands","title":"Load commands","text":"
player.load(commands, scope);\n
  • Commands : see also Run commands
    [\n[time, command],\n[time, command],\n...\n]\n
    • Format of each row :
      [time, fnName, param0, param1, ...]\n// [time, callback, param0, param1, ...]\n
      [time, [fnName, param0, param1, ...]]\n// [time, [callback, param0, param1, ...]]\n
      [time, [command0, command1, ...]]\n
    • time : Time in step-count
"},{"location":"arcade-tcrp-player/#start-playing","title":"Start playing","text":"
player.start();\n// player.start(startAt);  // Start-at time in step-count\n
"},{"location":"arcade-tcrp-player/#events","title":"Events","text":"
  • Complete
    player.on('complete', function(player){});\n
  • Run command
    player.on('runcommand', function(commands, scope){});\n
"},{"location":"arcade-tcrp-player/#pause-resume-stop-playing","title":"Pause, Resume, stop playing","text":"
player.pause();\nplayer.resume();\nplayer.stop();\n
"},{"location":"arcade-tcrp-player/#seek-elapsed-time","title":"Seek elapsed time","text":"
player.seek(time);   // Elapsed time in step-count\n
"},{"location":"arcade-tcrp-player/#state-of-player","title":"State of player","text":"
var isPlaying = player.isPlaying;\nvar completed = player.completed;\nvar now = player.now;\n
"},{"location":"arcade-tcrp-player/#time-scale","title":"Time-scale","text":"
  • Set
    player.setTimeScale(value);\n// player.timeScale = value;\n
    • timeScale : An integer equal or larger than 1
  • Get
    var timeScale = player.timeScale;\n
"},{"location":"arcade-tcrp-recorder/","title":"Recoder","text":""},{"location":"arcade-tcrp-recorder/#introduction","title":"Introduction","text":"

Recorder of T ime-C ommand-R ecorder-P layer with Arcade physics engine, to store commands with time.

  • Author: Rex
  • Member of scene

Arcade physics engine is fixed-step based, not tick time based.

This Arcade-TCRP has better result of replaying, which store step count via WORLD_STEP(worldstep) event.

"},{"location":"arcade-tcrp-recorder/#live-demos","title":"Live demos","text":"
  • Player
"},{"location":"arcade-tcrp-recorder/#usage","title":"Usage","text":"

Sample code

"},{"location":"arcade-tcrp-recorder/#install-plugin","title":"Install plugin","text":""},{"location":"arcade-tcrp-recorder/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexarcadetcrpplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexarcadetcrpplugin.min.js', true);\n
  • Create instance
    var recorder = scene.plugins.get('rexarcadetcrpplugin').addRecorder(scene);\n
"},{"location":"arcade-tcrp-recorder/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TCRPPlugin from 'phaser3-rex-plugins/plugins/arcadetcrp-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTCRP',\nplugin: TCRPPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var recorder = scene.plugins.get('rexTCRP').addRecorder(scene);\n
"},{"location":"arcade-tcrp-recorder/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TCRP from 'phaser3-rex-plugins/plugins/arcadetcrp.js';\n
  • Create instance
    var recorder = new TCRP.Recorder(scene);\n
"},{"location":"arcade-tcrp-recorder/#create-instance","title":"Create instance","text":"
var recorder = scene.plugins.get('rexTCRP').addRecorder(scene);\n
"},{"location":"arcade-tcrp-recorder/#start-recording","title":"Start recording","text":"
recorder.start();\n// recorder.start(startAt);  // start-at in step-count\n
"},{"location":"arcade-tcrp-recorder/#push-commands","title":"Push commands","text":"
recorder.addCommand([fnName, param0, param1, ...]);\n// recorder.addCommand([command0, command1, ...]);\n// recorder.addCommand([fnName, param0, param1, ...], offset);  // time-offset in step-count\n

See also Run commands

"},{"location":"arcade-tcrp-recorder/#get-commands","title":"Get commands","text":"
var commands = recorder.getCommands();        // Get a shallow copy of commands\n// var commands = recorder.getCommands(true); // Get reference of commands\n

Format of return commands:

[\n[time, [command]],\n[time, [command0,command1]],\n...\n]\n
  • time : Time in step-count
"},{"location":"arcade-tcrp-recorder/#pause-resume-stop-recording","title":"Pause, Resume, stop recording","text":"
recorder.pause();\nrecorder.resume();\nrecorder.stop();\n
"},{"location":"arcade-tcrp-recorder/#seek-elapsed-time","title":"Seek elapsed time","text":"
recorder.seek(time);   // elapsed time in step-count\n
"},{"location":"arcade-tcrp-recorder/#state-of-recorder","title":"State of recorder","text":"
var isRecording = recorder.isRecording;\nvar now = recorder.now;\n
  • now : Now time in step-count.
"},{"location":"arcade-tcrp-recorder/#time-scale","title":"Time-scale","text":"
  • Set
    recorder.setTimeScale(value);\n// recorder.timeScale = value;\n
    • timeScale : An integer equal or larger than 1
  • Get
    var timeScale = recorder.timeScale;\n
"},{"location":"arcade-tcrp-step-runner/","title":"Step runner","text":""},{"location":"arcade-tcrp-step-runner/#introduction","title":"Introduction","text":"

Execute command in next WORLD_STEP(worldstep) event, to synchronize command execution with step-counter of Recorder of Arcade-TCRP.

  • Author: Rex
  • Member of scene

Command might be executed before or after WORLD_STEP(worldstep) event, which is emitted in scene's update event.

  • Before: Command is executed in any input(touch/keyboard) event, or in scene's preupdate event.
  • After: Command is executed in scene.updat() method.
"},{"location":"arcade-tcrp-step-runner/#live-demos","title":"Live demos","text":"
  • Player
"},{"location":"arcade-tcrp-step-runner/#usage","title":"Usage","text":"

Sample code

"},{"location":"arcade-tcrp-step-runner/#install-plugin","title":"Install plugin","text":""},{"location":"arcade-tcrp-step-runner/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexarcadetcrpplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexarcadetcrpplugin.min.js', true);\n
  • Create instance
    var stepRunner = scene.plugins.get('rexarcadetcrpplugin').addStepRunner(scene);\n
"},{"location":"arcade-tcrp-step-runner/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TCRPPlugin from 'phaser3-rex-plugins/plugins/arcadetcrp-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTCRP',\nplugin: TCRPPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var stepRunner = scene.plugins.get('rexTCRP').addStepRunner(scene);\n
"},{"location":"arcade-tcrp-step-runner/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TCRP from 'phaser3-rex-plugins/plugins/arcadetcrp.js';\n
  • Create instance
    var stepRunner = new TCRP.StepRunner(scene);\n
"},{"location":"arcade-tcrp-step-runner/#create-instance","title":"Create instance","text":"
var stepRunner = scene.plugins.get('rexTCRP').addStepRunner(scene);\n
"},{"location":"arcade-tcrp-step-runner/#push-commands","title":"Push commands","text":"
stepRunner.add(commands, scope);\n

See also Run commands

"},{"location":"arcade-tcrp-step-runner/#offset-recorder","title":"Offset recorder","text":"

Since commands will be executed in next WORLD_STEP(worldstep) event, recorder have to add 1 step-count offset.

  • Offset at recording start
    recorder.start(1);\n
  • Add offset when pushing commands
    recorder.addCommand([fnName, param0, param1, ...], 1);\n
"},{"location":"arcade-world/","title":"World","text":""},{"location":"arcade-world/#introduction","title":"Introduction","text":"

World of Arcade physics engine in phaser.

  • Author: Richard Davey
"},{"location":"arcade-world/#usage","title":"Usage","text":""},{"location":"arcade-world/#configuration","title":"Configuration","text":"
var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n//    x: 0,\n//    y: 0,\n//    width: scene.sys.scale.width,\n//    height: scene.sys.scale.height,\n//    gravity: {\n//        x: 0,\n//        y: 0\n//    },\n//    checkCollision: {\n//        up: true,\n//        down: true,\n//        left: true,\n//        right: true\n//    },\n//    customUpdate: false,\n//    fixedStep: true,\n//    fps: 60,\n//    timeScale: 1,     // 2.0 = half speed, 0.5 = double speed\n//    customUpdate: false,\n//    overlapBias: 4,\n//    tileBias: 16,\n//    forceX: false,\n//    isPaused: false,\n//    debug: false,\n//    debugShowBody: true,\n//    debugShowStaticBody: true,\n//    debugShowVelocity: true,\n//    debugBodyColor: 0xff00ff,\n//    debugStaticBodyColor: 0x0000ff,\n//    debugVelocityColor: 0x00ff00,\n//    maxEntries: 16,\n//    useTree: true   // set false if amount of dynamic bodies > 5000\n}\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"arcade-world/#update","title":"Update","text":"
  • Default updating : World updating every tick
  • Custom updating :
    1. Set customUpdate of arcade config to false.
      • Enable world updating : scene.physics.enableUpdate()
      • Disable world updating : scene.physics.disableUpdate()
    2. Run world updating manually
      scene.physics.world.update(time, delta);\n
    3. Enable/disable world updating
      • Enable : scene.physics.enableUpdate()
      • Disable : scene.physics.disableUpdate()
"},{"location":"arcade-world/#step","title":"Step","text":"
  • Advances the simulation by a single step.
    scene.physics.world.singleStep();\n
  • Advances the simulation by a time increment.
    scene.physics.world.step(delta);\n
"},{"location":"arcade-world/#events","title":"Events","text":"
  • World step
    scene.physics.world.on('worldstep', function(delta) { /* ... */ });\n
    • delta : The delta time amount of this step, in seconds.
"},{"location":"arcade-world/#control","title":"Control","text":""},{"location":"arcade-world/#pause","title":"Pause","text":"
scene.physics.pause();\n
"},{"location":"arcade-world/#resume","title":"Resume","text":"
scene.physics.resume();\n
"},{"location":"arcade-world/#events_1","title":"Events","text":"
  • Pause world
    scene.physics.world.on('pause', function() { /* ... */ });\n
  • Resume world
    scene.physics.world.on('resume', function() { /* ... */ });\n
"},{"location":"arcade-world/#duration-per-frame","title":"Duration per frame","text":"
  • Time scale
    scene.physics.world.timeScale = timeScale;\n
    • 1.0 = normal speed
    • 2.0 = half speed
    • 0.5 = double speed
  • FPS
    scene.physics.world.setFPS(framerate);\n
"},{"location":"arcade-world/#tile-filter-options","title":"Tile filter options","text":"
var option = scene.physics.world.tileFilterOptions;\n
  • option
    {\nisColliding: true,\nisNotEmpty: true,\nhasInterestingFace: true\n}\n
"},{"location":"arcade-world/#body","title":"Body","text":""},{"location":"arcade-world/#enable","title":"Enable","text":"
scene.physics.world.enable(gameObject);\n// scene.physics.world.enable(gameObject, bodyType);\n
  • gameObject : A game object, or array of game objects, or game objects in a Group
  • bodyType :
    • 0 : Dynamic body. Default value.
    • 1 : Static body.

Or

scene.physics.add.existing(gameObject, bodyType);\n

See arcade-body

"},{"location":"arcade-world/#disable","title":"Disable","text":"
scene.physics.world.disable(gameObject);\n
  • gameObject : A game object, or array of game objects, or game objects in a Group
"},{"location":"arcade-world/#addremove-body","title":"Add/remove body","text":"
  • Add body to the local search trees.
    scene.physics.world.add(body);\n
  • Remove body from the local search trees.
    scene.physics.world.disableBody(body);\n
"},{"location":"arcade-world/#collision","title":"Collision","text":""},{"location":"arcade-world/#set-bound","title":"Set bound","text":"

See bound in body object, or game object.

"},{"location":"arcade-world/#collider-callback","title":"Collider & callback","text":"
  • Add collider
    • Push out
      scene.physics.add.collider(objectsA, objectsB);\n
    • Performs a collision check and separation between the two physics enabled objects given.
      var collider = scene.physics.add.collider(objectsA, objectsB, collideCallback);\n// var collider = scene.physics.add.collider(objectsA, objectsB, collideCallback, processCallback, callbackContext);\n
    • If you don't require separation then use overlap instead.
      var collider = scene.physics.add.overlap(objectsA, objectsB, collideCallback);\n// var collider = scene.physics.add.overlap(objectsA, objectsB, collideCallback, processCallback, callbackContext);\n
    • Parameters
      • objectsA, objectsB :
        • A game object
        • An array contains Game objects (Add or remove game objects)
        • Physics group/Group (Add or remove game objects)
        • An array contains Physics group/Group
      • collideCallback :
        var collideCallback = function(gameObject1, gameObject2) {\n// ...\n}\n
      • processCallback : Fired when gameObject1 intersects gameObject2, optional.
        var processCallback = function(gameObject1, gameObject2) {\nreturn true;  // return false will discard remaining collision checking\n}\n
  • Remove collider
    scene.physics.world.removeCollider(collider);\n
  • Deactivate collider
    collider.active = false;  // Set true to activate again\n
  • Name of collider (unused by engine)
    collider.name = name;\n
"},{"location":"arcade-world/#testing-wo-collider","title":"Testing wo collider","text":"
  • Test overlapping
    var isOverlapping = scene.physics.world.overlap(object1, object2);\n
    or
    var isOverlapping = scene.physics.world.overlap(object1, object2, collideCallback);\n// var isOverlapping = scene.physics.world.overlap(object1, object2, collideCallback, processCallback, callbackContext);\n
  • Test colliding, also push out
    var isCollided = scene.physics.world.collide(object1, object2);\n
    or
    var isCollided = scene.physics.world.collide(object1, object2, collideCallback);\n// var isCollided = scene.physics.world.collide(object1, object2, collideCallback, processCallback, callbackContext);\n
"},{"location":"arcade-world/#events_2","title":"Events","text":"
  • Two bodies overlap and at least one of them has their onOverlap property set to true.
    scene.physics.world.on('overlap', function(gameObject1, gameObject2, body1, body2) { /* ... */ });\n
  • Two bodies overlap and at least one of them has their onCollide property set to true.
    scene.physics.world.on('collide', function(gameObject1, gameObject2, body1, body2) { /* ... */ });\n
  • A body overlaps with a Tile and has its onOverlap property set to true.
    scene.physics.world.on('tileoverlap', function(gameObject, tile, body) { /* ... */ });\n
  • A body overlaps with a Tile and has its onCollide property set to true.
    scene.physics.world.on('tilecollide', function(gameObject, tile, body) { /* ... */ });\n
"},{"location":"arcade-world/#world-bounds","title":"World bounds","text":""},{"location":"arcade-world/#enable_1","title":"Enable","text":"
  • Body : Set body.setCollideWorldBounds() to enable worldBounds property.
  • World :
    • Set bounds rectangle and enable bounds
      scene.physics.world.setBounds(x, y, width, height);\n// scene.physics.world.setBounds(x, y, width, height, checkLeft, checkRight, checkUp, checkDown);\n
    • Set bounds rectangle
      scene.physics.world.bounds.setTo(x, y, width, height);\n
      or
      scene.physics.world.bounds.x = x;\nscene.physics.world.bounds.y = y;\nscene.physics.world.bounds.width = width;\nscene.physics.world.bounds.height = height;\n
    • Enable bounds
      scene.physics.world.setBoundsCollision();\n// scene.physics.world.setBoundsCollision(left, right, up, down);\n
      or
      scene.physics.world.checkCollision.left = left;\nscene.physics.world.checkCollision.right = right;\nscene.physics.world.checkCollision.up = up;\nscene.physics.world.checkCollision.down = down;\n
    • Get bounds rectangle
      var top = scene.physics.world.bounds.top;\nvar bottom = scene.physics.world.bounds.bottom;\nvar left = scene.physics.world.bounds.left;\nvar right = scene.physics.world.bounds.right;\n
"},{"location":"arcade-world/#bodies-inside-an-area","title":"Bodies inside an area","text":"
  • Overlap a rectangle area
    var bodies = scene.physics.overlapRect(x, y, width, height, includeDynamic, includeStatic);\n
    • includeDynamic : Set true to search Dynamic Bodies
    • includeStatic : Set true to search Static Bodies
  • Overlap a circle area
    var bodies = scene.physics.overlapCirc(x, y, radius, includeDynamic, includeStatic);\n
    • includeDynamic : Set true to search Dynamic Bodies
    • includeStatic : Set true to search Static Bodies
"},{"location":"arcade-world/#events_3","title":"Events","text":"
  • World bounds
    scene.physics.world.on('worldbounds', function(body, blockedUp, blockedDown, blockedLeft, blockedRight) { /* ... */ });\n
"},{"location":"arcade-world/#wrap","title":"Wrap","text":"
scene.physics.world.wrap(gameObject, padding);\n
  • gameObject:
    • game object
    • group
    • array of game objects
"},{"location":"arcade-world/#move-to","title":"Move to","text":"
  • Move to position with a steady velocity
    scene.physics.moveTo(gameObject, x, y, speed, maxTime);\n
  • Move to object with a steady velocity
    scene.physics.moveToObject(gameObject, destination, speed, maxTime);\n
"},{"location":"arcade-world/#accelerate-to","title":"Accelerate to","text":"
  • Accelerate to position
    scene.physics.accelerateTo(gameObject, x, y, acceleration, xSpeedMax, ySpeedMax);\n
  • Accelerate to object
    scene.physics.accelerateToObject(gameObject, destination, acceleration, xSpeedMax, ySpeedMax);\n
"},{"location":"arcade-world/#gravity","title":"Gravity","text":"
  • Set
    scene.physics.world.gravity.x = gx;\nscene.physics.world.gravity.y = gy;\n
  • Get
    var gx = scene.physics.world.gravity.x;\nvar gy = scene.physics.world.gravity.y;\n

Total Gravity = world.gravity + body.gravity

"},{"location":"arcade-world/#bodies","title":"Bodies","text":""},{"location":"arcade-world/#closestfurthest","title":"Closest/furthest","text":"
  • Closest
    var body = scene.physics.closest(point);  // point: {x,y}\n// var body = scene.physics.closest(point, targets);\n
    • targets : Array of Arcade Physics Game Object, Body or Static Body.
  • Furthest
    var body = scene.physics.furthest(point);  // point: {x,y}\n// var body = scene.physics.furthest(point, targets);\n
    • targets : Array of Arcade Physics Game Object, Body or Static Body.
"},{"location":"arcade-world/#debug","title":"Debug","text":""},{"location":"arcade-world/#draw-body-velocity","title":"Draw body & velocity","text":"
  • Bounds of dynamic Body
    • Enable drawing body
      scene.physics.world.defaults.debugShowBody = true;\n
    • Color
      scene.physics.world.defaults.bodyDebugColor = 0xff00ff;\n
  • Bounds of static Body
    • Enable drawing body
      scene.physics.world.defaults.debugShowStaticBody = true;\n
    • Color
      scene.physics.world.defaults.staticBodyDebugColor = 0x0000ff;\n
  • Direction and magnitude of velocity
    • Enable drawing body
      scene.physics.world.defaults.debugShowVelocity = true;\n
    • Color
      scene.physics.world.defaults.velocityDebugColor = 0x00ff00;\n
"},{"location":"arcade-world/#graphics","title":"Graphics","text":"

Draw debug body & velocity on a Graphics object.

var graphics = scene.physics.world.debugGraphic;\n
  • Set visible
    scene.physics.world.debugGraphic.setVisible();\n
  • Set invisible
    scene.physics.world.debugGraphic.setVisible(false);\n
"},{"location":"arcade-world/#update-loop","title":"Update loop","text":"
  1. scene.sys.events: update
    1. Update position & angle of each body
    2. Process each collider
    3. Update final position of each body
    4. Emit worldstep event
  2. scene.sys.events: postupdate
    1. Draw debug graphics
graph TB\n\nSceneEventUpdate>\"scene.sys.events: update<br><br>Update arcade world<br>gameObject.preUpdate()\"]\nSceneUpdate[\"scene.update()\"]\nSceneEventPostUpdate>\"scene.sys.events: postupdate<br><br>Post update arcade world\"]\nRender\n\nSceneEventUpdate --> SceneUpdate\nSceneUpdate --> SceneEventPostUpdate\nSceneEventPostUpdate --> Render
"},{"location":"array-addremove/","title":"Add/remove","text":""},{"location":"array-addremove/#introduction","title":"Introduction","text":"

Add/insert/remove item(s) of an array, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"array-addremove/#usage","title":"Usage","text":""},{"location":"array-addremove/#add-item","title":"Add item","text":"
Phaser.Utils.Array.Add(arr, item);\n// Phaser.Utils.Array.Add(arr, item, limit, callback, context);\n
  • item : An item, or an array of items.
  • limit : Optional limit which caps the size of the array.
  • callback : A callback to be invoked for each item successfully added to the array.
  • context : The context in which the callback is invoked.
"},{"location":"array-addremove/#insert-item-at","title":"Insert item at","text":"
Phaser.Utils.Array.AddAt(arr, item, index);\n// Phaser.Utils.Array.AddAt(arr, item, index, limit, callback, context);\n
  • index : The index in the array where the item will be inserted.
  • item : An item, or an array of items.
  • limit : Optional limit which caps the size of the array.
  • callback : A callback to be invoked for each item successfully added to the array.
  • context : The context in which the callback is invoked.
"},{"location":"array-addremove/#remove-item","title":"Remove item","text":"
Phaser.Utils.Array.Remove(arr, item);\n// Phaser.Utils.Array.Remove(arr, item, callback, context);\n
  • item : An item, or an array of items.
  • callback : A callback to be invoked for each item successfully removed from the array.
  • context : The context in which the callback is invoked.
"},{"location":"array-addremove/#remove-item-at","title":"Remove item at","text":"
var removed = Phaser.Utils.Array.RemoveAt(arr, index);\n// var removed = Phaser.Utils.Array.RemoveAt(arr, index, callback, context);\n
  • removed : Removed item.
  • index : The array index to remove the item from. The index must be in bounds or it will throw an error.
  • callback : A callback to be invoked for each item successfully removed from the array.
  • context : The context in which the callback is invoked.
"},{"location":"array-addremove/#remove-items-between","title":"Remove items between","text":"
var removed = Phaser.Utils.Array.RemoveBetween(arr, startIndex, endIndex);\n// var removed = Phaser.Utils.Array.RemoveBetween(arr, startIndex, endIndex, callback, context);\n
  • removed : Removed items.
  • startIndex : The start index to remove from.
  • callback : The end index to remove to.
  • callback : A callback to be invoked for each item successfully removed from the array.
  • context : The context in which the callback is invoked.
"},{"location":"array-addremove/#remove-random-item","title":"Remove random item","text":"
var item = Phaser.Utils.Array.RemoveRandomElement(arr);\n
"},{"location":"array-addremove/#replace-item","title":"Replace item","text":"

Replaces an element of the array with the new element. The new element cannot already be a member of the array.

Phaser.Utils.Array.Replace(arr, oldItem, newItem);\n
  • oldItem : An item in array.
  • newItem : Another item, which is not in array.
"},{"location":"array-filter/","title":"Filter/Map","text":""},{"location":"array-filter/#introduction","title":"Introduction","text":"

Built-in javascript object.

  • Author: Built-in javascript function
"},{"location":"array-filter/#usage","title":"Usage","text":""},{"location":"array-filter/#run-function-for-each-element","title":"Run function for each element","text":"
arr.forEach(function(element, index, arr) {\n//\n}, scope);\n
"},{"location":"array-filter/#filter-elements","title":"Filter elements","text":"

Creates a new array with all elements that pass the test function.

var result = arr.filter(function(element, index, arr) {\nreturn true; // false\n}, scope);\n
"},{"location":"array-filter/#find-one-element","title":"Find one element","text":"
var element = arr.find(function(element, index, arr) {\nreturn true; // false\n}, scope);\n
"},{"location":"array-filter/#map-elements-to-a-new-array","title":"Map elements to a new array","text":"
var newArray = arr.map(function(element, index, arr) {\nreturn newElement;\n}, scope);\n
"},{"location":"array-random/","title":"Random","text":""},{"location":"array-random/#introduction","title":"Introduction","text":"

Random operation of an array, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"array-random/#usage","title":"Usage","text":""},{"location":"array-random/#get-random-item","title":"Get random item","text":"
var item = Phaser.Utils.Array.GetRandom(arr);\n// var item = Phaser.Utils.Array.GetRandom(arr, startIndex, length);\n
"},{"location":"array-random/#remove-random-item","title":"Remove random item","text":"
var item = Phaser.Utils.Array.RemoveRandomElement(arr);\n// var item = Phaser.Utils.Array.RemoveRandomElement(arr, startIndex, length);\n
"},{"location":"array-random/#shuffle","title":"Shuffle","text":"
var arr = Phaser.Utils.Array.Shuffle(arr);\n
"},{"location":"array-sort/","title":"Sort","text":""},{"location":"array-sort/#introduction","title":"Introduction","text":"

Array sorting, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"array-sort/#usage","title":"Usage","text":""},{"location":"array-sort/#built-in-array-sort","title":"Built-in array sort","text":"
var out = arr.sort(compareFunction);\n
  • compareFunction : A function that defines an alternative sort order.
    function(a, b) {\n// return a - b;\n}\n
    • Return a negative value
    • Return 0
    • Return a positive value
"},{"location":"array-sort/#stable-array-sort","title":"Stable array sort","text":"
var out = Phaser.Utils.Array.StableSort(arr, compareFunction);\n
"},{"location":"array-sort/#shuffle","title":"Shuffle","text":"
var arr = Phaser.Utils.Array.Shuffle(arr);\n
"},{"location":"array-sort/#move-item","title":"Move item","text":"
  • Moves the given element to the top of the array.
    Phaser.Utils.Array.BringToTop(arr, item);\n
  • Moves the given element to the bottom of the array.
    Phaser.Utils.Array.SendToBack(arr, item);\n
  • Moves the given array element up.
    Phaser.Utils.Array.MoveUp(array, item);\n
  • Moves the given array element down.
    Phaser.Utils.Array.MoveDown(array, item);\n
  • Moves an element in an array to a new position.
    Phaser.Utils.Array.MoveTo(array, item, index);\n
  • Swaps the position of two elements.
    Phaser.Utils.Array.Swap(array, item1, item2);\n
  • Moves the element at the start of the array to the end, shifting all items in the process.
    Phaser.Utils.Array.RotateLeft(array, steps);\n
    • steps : The number of times to shift the array.
  • Moves the element at the end of the array to the start, shifting all items in the process.
    Phaser.Utils.Array.RotateRight(array, steps);\n
    • steps : The number of times to shift the array.
"},{"location":"audio/","title":"Audio","text":""},{"location":"audio/#introduction","title":"Introduction","text":"

Play sounds, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"audio/#usage","title":"Usage","text":""},{"location":"audio/#configuration","title":"Configuration","text":""},{"location":"audio/#web-audio","title":"Web audio","text":"

Web audio is the default audio context.

"},{"location":"audio/#html5-audio","title":"Html5 audio","text":"
var config = {\n// ....\naudio: {\ndisableWebAudio: true\n}\n// ....\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"audio/#no-audio","title":"No audio","text":"
var config = {\n// ....\naudio: {\nnoAudio: true\n}\n// ....\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"audio/#load-audio-file","title":"Load audio file","text":"
scene.load.audio(key, urls);  // urls: an array of file url\n// scene.load.audio(key, urls, {instances: 1}, xhrSettings);\n

See loader

"},{"location":"audio/#decode-audio","title":"Decode audio","text":"
scene.sound.decodeAudio(key, audioData);\n
  • audioData : Audio data
    • A base64 encoded string
    • An audio media-type data uri
    • An ArrayBuffer instance

Or

scene.sound.decodeAudio(audioFiles);\n
  • audioFiles : An array of {key, data}
    • data : Audio data
      • A base64 encoded string
      • An audio media-type data uri
      • An ArrayBuffer instance
"},{"location":"audio/#decoded-events","title":"Decoded events","text":"
  • Finished decoding an audio data
    scene.sound.on('decoded', key);\n
  • Finished decoding all audio data
    scene.sound.on('decodedall');\n
"},{"location":"audio/#unlock-audio","title":"Unlock audio","text":"

Unlocks Web Audio API/HTML5 Audio loading on the initial input event.

scene.sound.unlock();\n
"},{"location":"audio/#play-sound","title":"Play sound","text":"

Sound instance will be destroyed when playback ends.

scene.sound.play(key);\n

or

scene.sound.play(key, config);\n/*\nvar sound = scene.sound.add(key);\nsound.play(config);\n*/\n
"},{"location":"audio/#position-of-the-spatial-audio-listener","title":"Position of the Spatial Audio listener","text":"
scene.sound.setListenerPosition(x, y)\n
  • x, y : The x/y position of the Spatial Audio listener. Default value is center of the game canvas.

Note

Web audio only

"},{"location":"audio/#sound-instance","title":"Sound instance","text":""},{"location":"audio/#create-sound-instance","title":"Create sound instance","text":"
var music = scene.sound.add(key);\n
var music = scene.sound.add(key, config);\n
"},{"location":"audio/#configuration_1","title":"Configuration","text":"
{\nmute: false,\nvolume: 1,\nrate: 1,\ndetune: 0,\nseek: 0,\nloop: false,\ndelay: 0,\n\n// source of the spatial sound\nsource: {\nx: 0,\ny: 0,\nz: 0,\npanningModel: 'equalpower',\ndistanceModel: 'inverse',\norientationX: 0,\norientationY: 0,\norientationZ: -1,\nrefDistance: 1,\nmaxDistance: 10000,\nrolloffFactor: 1,\nconeInnerAngle: 360,\nconeOuterAngle: 0,\nconeOuterGain: 0,\nfollow: undefined\n}\n}\n
  • source : Source of the spatial sound
    • x, y : The horizontal/vertical position of the audio in a right-hand Cartesian coordinate system.
    • z : Represents the longitudinal (back and forth) position of the audio in a right-hand Cartesian coordinate system.
    • panningModel : An enumerated value determining which spatialization algorithm to use to position the audio in 3D space.
      • 'equalpower'
      • 'HRTF'
    • orientationX, orientationY : The horizontal/vertical position of the audio source's vector in a right-hand Cartesian coordinate system.
    • orientationZ : Represents the longitudinal (back and forth) position of the audio source's vector in a right-hand Cartesian coordinate system.
    • refDistance : A double value representing the reference distance for reducing volume as the audio source moves further from the listener. For distances greater than this the volume will be reduced based on rolloffFactor and distanceModel.
    • maxDistance : The maximum distance between the audio source and the listener, after which the volume is not reduced any further.
    • rolloffFactor : A double value describing how quickly the volume is reduced as the source moves away from the listener. This value is used by all distance models.
    • coneInnerAngle : The angle, in degrees, of a cone inside of which there will be no volume reduction.
    • coneOuterAngle : The angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the coneOuterGain property.
    • coneOuterGain : The amount of volume reduction outside the cone defined by the coneOuterAngle attribute. Its default value is 0, meaning that no sound can be heard. A value between 0 and 1.
    • follow : Set this Sound object to automatically track the x/y position of this object. Can be a Phaser Game Object, Vec2 or anything that exposes public x/y properties.
"},{"location":"audio/#play-sound-instance","title":"Play sound instance","text":"
  • Start playing
    music.play();\n
  • Start playing with configuration
    music.play(config);\n
    • config
  • Stop
    music.stop();\n
  • Pause
    music.pause();\n
  • Resume
    music.resume();\n
"},{"location":"audio/#methods","title":"Methods","text":""},{"location":"audio/#mute","title":"Mute","text":"
  • Set
    music.setMute(mute); // mute: true/false\n// music.mute = mute;\n
  • Get
    var mute = music.mute;\n
"},{"location":"audio/#volume","title":"Volume","text":"
  • Set
    music.setVolume(volume); // volume: 0 to 1\n// music.volume = volume;\n
  • Get
    var volume = music.volume;\n
"},{"location":"audio/#detune","title":"Detune","text":"
  • Set
    music.setDetune(detune); // detune: -1200 to 1200\n// music.detune = detune;\n
  • Get
    var detune = music.detune;\n
"},{"location":"audio/#play-rate","title":"Play-rate","text":"
  • Set
    music.setRate(rate); // rate: 1.0(normal speed), 0.5(half speed), 2.0(double speed)\n// music.rate = rate;\n
  • Get
    var rate = music.rate;\n
"},{"location":"audio/#seek-to","title":"Seek to","text":"
  • Seek to
    music.setSeek(time); // seek: playback time\n// music.seek = seek;\n
  • Get current playback time
    var time = music.seek;  // return 0 when playback ends\n
"},{"location":"audio/#loop","title":"Loop","text":"
  • Set
    music.setLoop(loop); // loop: true/false\n// music.loop = loop;\n
  • Get
    var loop = music.loop;\n
"},{"location":"audio/#properties","title":"Properties","text":"
  • Duration : duration of this sound
    var duration = music.duration;\n
  • Is playing
    var isPlaying = music.isPlaying;\n
  • Is paused
    var isPaused = music.isPaused;\n
  • Asset key
    var key = music.key;\n
"},{"location":"audio/#events","title":"Events","text":"
  • Start playing
    music.once('play', function(music){});\n
  • Playback end
    music.once('complete', function(music){});\n
  • Looping
    music.once('looped', function(music){});\n
  • Pause
    music.once('pause', function(music){});\n
  • Resume
    music.once('resume', function(music){});\n
  • Stop
    music.once('stop', function(music){});\n
  • Set mute
    music.once('mute', function(music, mute){});\n
  • Set volume
    music.once('volume', function(music, volume){});\n
  • Set detune
    music.once('detune', function(music, detune){});\n
  • Set play-rate
    music.once('rate', function(music, rate){});\n
  • Seek to
    music.once('seek', function(music, time){});\n
  • set loop
    music.once('loop', function(music, loop){});\n
"},{"location":"audio/#play-marked-sound","title":"Play marked sound","text":"

Sound instance will be destroyed when playback ends.

scene.sound.play(key, marker);\n
"},{"location":"audio/#marker","title":"Marker","text":"
{\nname: '',\nstart: 0,\nduration: music.duration,\nconfig: {\nmute: false,\nvolume: 1,\nrate: 1,\ndetune: 0,\nseek: 0,\nloop: false,\ndelay: 0\n}\n}\n
"},{"location":"audio/#markers-in-sound-instance","title":"Markers in sound instance","text":""},{"location":"audio/#add-marker","title":"Add marker","text":"
music.addMarker(marker);\n

Marker

"},{"location":"audio/#play-marked-sound_1","title":"Play marked sound","text":"
music.play(markerName);\n
music.play(markerName, config);\n

config

"},{"location":"audio/#audio-sprite","title":"Audio sprite","text":""},{"location":"audio/#load-audio-sprite","title":"Load audio sprite","text":"
scene.load.audioSprite(key, urls, markersConfig, config);\n

See loader

Format of markersConfig

{\nresources: urls, // an array of audio files\nspritemap: {\nmarkerName0: {\nstart: 0,\nend: 0\n},\nmarkerName1: {\nstart: 0,\nend: 0\n}\n// ...\n}\n}\n

"},{"location":"audio/#play-sound_1","title":"Play sound","text":"

Create a sound instance then play the marked section, this sound instance will be destroyed when playback ends.

scene.sound.playAudioSprite(key, markerName, config);\n

config

"},{"location":"audio/#sound-instance_1","title":"Sound instance","text":"

Create a sound instance with markers.

var music = scene.sound.addAudioSprite(key, config);\n

config

"},{"location":"audio/#play-sound-instance_1","title":"Play sound instance","text":"
music.play(markerName);\n
music.play(markerName, config);\n

config

"},{"location":"audio/#sound-manager","title":"Sound manager","text":""},{"location":"audio/#mute_1","title":"Mute","text":"
  • Set
    scene.sound.setMute(mute); // mute: true/false\n// scene.sound.mute = mute;\n
  • Get
    var mute = scene.sound.mute;\n
"},{"location":"audio/#volume_1","title":"Volume","text":"
  • Set
    scene.sound.setVolume(volume); // volume: 0 to 1\n// scene.sound.volume = volume;\n
  • Get
    var volume = scene.sound.volume;\n
"},{"location":"audio/#detune_1","title":"Detune","text":"
  • Set
    scene.sound.setDetune(detune); // detune: -1200 to 1200\n// scene.sound.detune = detune;\n
  • Get
    var detune = scene.sound.detune;\n
"},{"location":"audio/#play-rate_1","title":"Play-rate","text":"
  • Set
    scene.sound.setRate(rate); // rate: 1.0(normal speed), 0.5(half speed), 2.0(double speed)\n// scene.sound.rate = rate;\n
  • Get
    var rate = scene.sound.rate;\n
"},{"location":"audio/#get-music-instance","title":"Get music instance","text":"
  • Get first by key
    var music = scene.sound.get(key); // music instance, or null\n
  • Get all by key
    var musicArray = scene.sound.getAll(key); // music instance, or null\n
  • Get all
    var musicArray = scene.sound.getAll();\n
  • Get all playing
    var musicArray = scene.sound.getAllPlaying();\n
"},{"location":"audio/#is-playing","title":"Is playing","text":"
  • Is any sound playing
    var isPlaying = scene.sound.isPlaying();\n
  • Is any sound playing by key
    var isPlaying = scene.sound.isPlaying(key);\n
"},{"location":"audio/#remove-music-instance","title":"Remove music instance","text":"
  • Remove by key
    var removed = scene.sound.removeByKey(key);\n
    • removed : The number of matching sound objects that were removed.
  • Remove all
    scene.sound.removeAll();\n
"},{"location":"audio/#stop-music-instance","title":"Stop music instance","text":"
  • Stop by key
    var stopped = scene.sound.stopByKey(key);\n
    • stopped : How many sounds were stopped.
  • Stop all
    scene.sound.stopAll();\n
"},{"location":"audio/#analyser","title":"Analyser","text":"

Analyser node is only available in Web audio mode.

  1. Create analyser node
    var analyser = scene.sound.context.createAnalyser();\n
  2. Configure analyser node
    analyser.smoothingTimeConstant = 1;\nanalyser.fftSize = 8192;\nanalyser.minDecibels = -90;\nanalyser.maxDecibels = -10;\n
    • smoothingTimeConstant : Averaging constant with the last analysis frame.
      • 0(no time averaging) ~ 1. Default value is 0.8.
    • fftSize : Window size.
      • 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, and 32768. Defaults to 2048.
    • minDecibels : Minimum decibel value for scaling the FFT analysis data.
      • 0 dB is the loudest possible sound, -10 dB is a 10th of that, etc. The default value is -100 dB
    • maxDecibels : Maximum decibel value for scaling the FFT analysis data.
      • The default value is -30 dB.
  3. Set source of analyser node
    • Global volume nodee -> analyser node
      scene.sound.masterVolumeNode.connect(analyser);\n
    • A sound instance -> analyser node
      music.volumeNode.connect(analyser);\n
  4. Ouput analyser node to audio context
    analyser.connect(scene.sound.context.destination);\n
  5. Create output data array
    var dataArrayLength = analyser.frequencyBinCount;\nvar dataArray = new Uint8Array(dataArrayLength);\n
  6. Get output data
    analyser.getByteTimeDomainData(dataArray);\n
    • Retrieve output data
      for(var i= 0; i < dataArrayLength; i++) {\nvar data = dataArray[i];\n}\n
"},{"location":"awaitloader/","title":"Await loader","text":""},{"location":"awaitloader/#introduction","title":"Introduction","text":"

Await custom task in preload stage.

  • Author: Rex
  • Custom File of loader
"},{"location":"awaitloader/#live-demos","title":"Live demos","text":"
  • Wait 1000ms
"},{"location":"awaitloader/#usage","title":"Usage","text":"

Sample code

"},{"location":"awaitloader/#install-plugin","title":"Install plugin","text":""},{"location":"awaitloader/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    var sceneConfig = {\n// ....\npack: {\nfiles: [{\ntype: 'plugin',\nkey: 'rexawaitloaderplugin',\nurl: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/    rexawaitloaderplugin.min.js',\nstart: true\n}]\n}\n};\nclass MyScene extends Phaser.Scene {\nconstructor() {\nsuper(sceneConfig)\n}\n// ....\n\npreload() {\n// rexawaitloaderplugin will be installed before preload(), but not added to loader yet\n// Call addToScene(scene) to add this await loader to loader of this scene\nthis.plugins.get('rexawaitloaderplugin').addToScene(this);\n\nthis.load.rexAwait(function(successCallback, failureCallback) { // successCallback()\n});\n}\n}\n
"},{"location":"awaitloader/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import AwaitLoaderPlugin from 'phaser3-rex-plugins/plugins/awaitloader-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAwaitLoader',\nplugin: AwaitLoaderPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • In preload stage
    scene.load.rexAwait(function(successCallback, failureCallback) { // successCallback()\n});\n
"},{"location":"awaitloader/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Awaitloader from 'phaser3-rex-plugins/plugins/awaitloader.js';\n
  • Start loading task
    Awaitloader.call(scene.load, function(successCallback, failureCallback) {\n// successCallback();\n}, scope)\n
"},{"location":"awaitloader/#start-loading-task","title":"Start loading task","text":"

In preload stage:

scene.load.rexAwait(function(successCallback, failureCallback) {\n// successCallback();\n}, scope);\n

or

var callback = function(successCallback, failureCallback) {\n// successCallback();\n};\nscene.load.rexAwait(key, {\ncallback: callback,\n// scope: scope\n});\n
  1. This plugin runs callback to start custom task.
  2. Calls successCallback when custom task completed, or failureCallback if error.
"},{"location":"awaytime/","title":"Away time","text":""},{"location":"awaytime/#introduction","title":"Introduction","text":"

Get time from previous closing application to now.

  • Author: Rex
  • Standalone object
"},{"location":"awaytime/#usage","title":"Usage","text":"

Sample code

"},{"location":"awaytime/#install-plugin","title":"Install plugin","text":""},{"location":"awaytime/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexawaytimeplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexawaytimeplugin.min.js', true);\n
  • Get away-time
    var awayTime = scene.plugins.get('rexawaytimeplugin').awayTime;\n
"},{"location":"awaytime/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import AwayTimePlugin from 'phaser3-rex-plugins/plugins/awaytime-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAwayTime',\nplugin: AwayTimePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Get away-time
    var awayTime = scene.plugins.get('rexAwayTime').awayTime;\n
"},{"location":"awaytime/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import AwayTime from 'phaser3-rex-plugins/plugins/awaytime.js';\n
  • Get away-time
    var awayTime = (new AwayTime()).awayTime;\n
"},{"location":"awaytime/#default-away-timer","title":"Default away-timer","text":""},{"location":"awaytime/#get-away-time","title":"Get away-time","text":"
var awayTime = scene.plugins.get('rexAwayTime').awayTime;\n// var awayTime = scene.plugins.get('rexAwayTime').setKey(key).setPeriod(time).awayTime;\n
  • awayTime : Time in millisecond.
  • key : Save curent time-stamp in key of localstorage. Default value is 'away'.
  • time : Period of saving current time-stamp. Default value is 1000.

Note

This action also starts saving current time-stamp periodically into localstorage.

"},{"location":"awaytime/#set-key","title":"Set key","text":"
scene.plugins.get('rexAwayTime').setKey(key);\n
  • key : Save curent time-stamp in key of localstorage
"},{"location":"awaytime/#set-period","title":"Set period","text":"
scene.plugins.get('rexAwayTime').setPeriod(time);\n
  • time : Period of saving current time-stamp.
"},{"location":"awaytime/#add-away-timer-object","title":"Add away timer object","text":"
var awayTimer = scene.plugins.get('rexAwayTime').add({\nkey: 'away',\nperiod: 1000\n})\n
"},{"location":"awaytime/#get-away-time_1","title":"Get away-time","text":"
var awayTime = awayTimer.awayTime;\n

Will also start timer.

"},{"location":"awaytime/#stop-timer","title":"Stop timer","text":"
awayTimer.stop();\n
"},{"location":"base64/","title":"Base64","text":""},{"location":"base64/#introduction","title":"Introduction","text":"

Decode a base64 string to an array buffer, or create a base64 string from an array buffer, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"base64/#usage","title":"Usage","text":""},{"location":"base64/#base64-array-buffer","title":"Base64 -> Array buffer","text":"
var arrayBuffer = Phaser.Utils.Base64.Base64ToArrayBuffer(base64);\n
"},{"location":"base64/#array-buffer-base64","title":"Array buffer -> Base64","text":"
var base64 = Phaser.Utils.Base64.ArrayBufferToBase64(arrayBuffer, mediaType);\n
  • mediaType : An optional media type, i.e. audio/ogg or image/jpeg
"},{"location":"bbcodetext/","title":"BBCode Text","text":""},{"location":"bbcodetext/#introduction","title":"Introduction","text":"

Drawing text with BBCode protocol.

  • Author: Rex
  • Game object
"},{"location":"bbcodetext/#live-demos","title":"Live demos","text":"
  • BBCode text
  • Hit area of words
  • Align
  • Escape
  • Page, typing
  • Wrap
    • Mix wrap
  • Measure margin of text
  • Generate texture
  • Image height
  • RTL
"},{"location":"bbcodetext/#usage","title":"Usage","text":"

Sample code

"},{"location":"bbcodetext/#install-plugin","title":"Install plugin","text":""},{"location":"bbcodetext/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbbcodetextplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbbcodetextplugin.min.js', true);\n
  • Add text object
    var txt = scene.add.rexBBCodeText(x, y, content, config);\n
"},{"location":"bbcodetext/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BBCodeTextPlugin from 'phaser3-rex-plugins/plugins/bbcodetext-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBBCodeTextPlugin',\nplugin: BBCodeTextPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text object
    var txt = scene.add.rexBBCodeText(x, y, content, config);\n
"},{"location":"bbcodetext/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import BBCodeText from 'phaser3-rex-plugins/plugins/bbcodetext.js';\n
  • Add text object
    var txt = new BBCodeText(scene, x, y, content, config);\nscene.add.existing(txt);\n
"},{"location":"bbcodetext/#bbcode","title":"BBCode","text":"
  • Bold : [b]text[/b]
  • Weight : [weight=900]text[/weight]
    • Valid when text does not have bold tag.
  • Italic : [i]text[/i]
  • Color :
    • [color=red]text[/color]
    • [color=#FF0000]text[/color]
    • [color=rgb(255,0,0)]text[/color]
    • [color=rgba(255,0,0,1)]text[/color]
  • Size : [size=18]text[/size]
  • Stroke : [stroke]text[/stroke]
    • Stroke with color setting : [stroke=red]text[/stroke]
  • Shadow : [shadow]text[/shadow]
    • Shadow with color setting : [shadow=red]text[/shadow]
  • Underline : [u]text[/u]
    • Underline with color setting : [u=red]text[/u]
  • Strikethrough : [s]text[/s]
    • Strikethrough with color setting : [s=red]text[/s]
  • Background color :
    • [bgcolor=red]text[/bgcolor]
    • [bgcolor=#FF0000]text[/bgcolor]
    • [bgcolor=rgb(255,0,0)]text[/bgcolor]
    • [bgcolor=rgba(255,0,0,1)]text[/bgcolor]
  • Superscript, subscript : [y=-12]text[y]
  • Image : [img=imgKey]
  • Hit area of words : [area=key]text[/area]
  • Url link : [url=http...]text[/url]
    • Click this area to open web page on a new tab (window.open(url, '_blank'))
    • Will register hit area with key url:http...
  • Line alignment :
    • [align=left]text[/align],
    • [align=center]text[/align],
    • [align=right]text[/align]
  • Escape : Tags between [esc] ... [/esc] or [raw] ... [/raw] will be treated as content.
    • [esc][color=yellow]Text[/color][/esc]
    • [esc][raw]Text[/raw][/esc]
    • [raw][esc]Text[/esc][/raw]
    • [raw][b]Text[/b][/raw]
  • Do nothing, just a marker :
    • [id=0][color=red]Text[/id]TextText[/color]

Note

Can set delimiter [] to another custom value in style of constructor.

"},{"location":"bbcodetext/#add-text-object","title":"Add text object","text":"
var txt = scene.add.rexBBCodeText(x, y, '[b]h[/b]ello');\n// var txt = scene.add.rexBBCodeText(x, y, '[b]h[/b]ello', { fontFamily: 'Arial', fontSize: 64, color: '#00ff00' });\n

Default style

{\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,  // null, css string, or number\nbackgroundColor2: null,  // null, css string, or number\nbackgroundHorizontalGradient: true,\nbackgroundStrokeColor: null,  // null, css string, or number\nbackgroundStrokeLineWidth: 2,\n\nbackgroundCornerRadius: 0,  // 0   : no round corner, \n// > 0 : convex round corner\n// < 0 : concave round corner\n\nbackgroundCornerIteration: null,    color: '#fff',  // null, css string, or number\nstroke: '#fff',  // null, css string, or number\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',  // css string, or number\nblur: 0,\nstroke: false,\nfill: false\n},\nunderline: {\ncolor: '#000',  // css string, or number\nthickness: 0,\noffset: 0\n},\nstrikethrough: {\ncolor: '#000',  // css string, or number\nthickness: 0,\noffset: 0\n},\n// align: 'left',  // Equal to halign\nhalign: 'left', // 'left'|'center'|'right'\nvalign: 'top',  // 'top'|'center'|'bottom'\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\nmaxLines: 0,\nlineSpacing: 0,\nfixedWidth: 0,\nfixedHeight: 0,\ntestString: '|M\u00c9qgy',\n\nwrap: {\nmode: 'none',     // 0|'none'|1|'word'|2|'char'|'character'|3|'mix'\nwidth: null\n},\n// wordWrap: { width: 0 },   // Compatible with Text game object\n\n// rtl: false,\nmetrics: false,\n// metrics: {\n//     ascent: 0,\n//     descent: 0,\n//     fontSize: 0\n// },\n\n// images: {\n//     imgKey: {y: -8}\n// },\n\n// delimiters: '[]',\n\n// sharedPool: true,\n\n// urlTagCursorStyle: 'pointer',\n// interactive: false\n}\n

or

var txt = scene.add.rexBBCodeText({\nx: 0,\ny: 0,\ntext: '',\nstyle: {\nfontSize: '64px',\nfontFamily: 'Arial',\ncolor: '#ffffff',\nalign: 'center',\nbackgroundColor: '#ff00ff',\n// ...\n},\n})\n

or

var txt = scene.make.rexBBCodeText({\nx: 0,\ny: 0,\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n//x: 32,    // 32px padding on the left/right\n//y: 16     // 16px padding on the top/bottom\n},\ntext: 'Text\\nGame Object\\nCreated from config',\nstyle: {\nfontSize: '64px',\nfontFamily: 'Arial',\ncolor: '#ffffff',\nalign: 'center',\nbackgroundColor: '#ff00ff',\n// ...\n},\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
  • Alignment
    • halign, or align : Horizontal alignment.
      • 'left', 'center', 'right'
    • valign : Vertical alignment.
      • 'top', 'center', 'bottom'
  • images : See Image
  • delimiters : Delimiters of tags, default value is [].
    • Don't use () as delimiters, which is preserved for color value.
  • sharedPool :
    • true : Use shared resouce pools during game. Default behavior.
    • false : Use local resource pools, will be free when game object destroying.
  • urlTagCursorStyle : Cursor style when cursor moving over a url tag. Default value is 'pointer'.
  • interactive :
    • true : Invoke txt.setInteractive() for hit-area tag, or url tag.
    • false : Do nothing. Default behavior.
"},{"location":"bbcodetext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyText extends BBCodeText {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyText(scene, x, y, '[b]h[/b]ello');\n
"},{"location":"bbcodetext/#wrap","title":"Wrap","text":"
  • Wrap by word or character.
    var txt = scene.make.rexBBCodeText({\nx: 400,\ny: 100,\ntext: 'The sky above the port was the color of television, tuned to a dead channel.',\norigin: { x: 0.5, y: 0.5 },\nstyle: {\nfont: 'bold 25px Arial',\nfill: 'white',\nwrap: {\nmode: 'none',    // 0|'none'|1|'word'|2|'char'|'character'|3|'mix'\nwidth: 0\n}\n}\n});\n
    • wrap.mode :
      • 0, or 'none' : No wrapping, default behavior.
      • 1, or 'word' : Word wrapping.
      • 2, or 'char', or 'character' : Character wrapping.
      • 3, or 'mix' : Word wrapping for ASCII word, Character wrapping for other (unicode) word.
    • wrap.width : Maximun wrapping width of a line.
      • Wrap-fit : Set wrapping width to fixedWidth - padding.left - padding.right if fixedWidth > 0
  • Wrap mode
    • Get
      var mode = txt.style.wrapMode;\n
    • Set
      txt.setWrapMode(mode);\n
      • 0, or 'none' : No wrapping.
      • 1, or 'word' : Word wrapping.
      • 2, or 'char', or 'character' : Character wrapping.
      • 3, or 'mix' : Word wrapping for ASCII word, Character wrapping for other (unicode) word.
  • Wrap width
    • Get
      var width = txt.style.wrapWidth;\n
    • Set
      txt.setWrapWidth(width);\n// txt.setWordWrapWidth(width);\n
      • width : Maximun wrapping width of a line.
        • Wrap-fit : Set wrapping width to fixedWidth - padding.left - padding.right if fixedWidth > 0
"},{"location":"bbcodetext/#content","title":"Content","text":"
  • Get source text
    var curContent = txt.text;\n
  • Get plain text
    var plainText = txt.getPlainText();\n
    var plainText = txt.getPlainText(content);\n
  • Get sub-string
    var text = txt.getText(start, end);\n
  • Get wrapped lines
    var linesArray = txt.getWrappedText();\n
    var linesArray = txt.getWrappedText(content);\n
  • Set
    txt.setText('[b]h[/b]ello');\n// txt.text = '[b]h[/b]ello';\n
  • Append
    txt.appendText(text);\n// txt.text += '\\n' + text;\n
    or
    txt.appendText(text, false);\n// txt.text += text;\n
"},{"location":"bbcodetext/#set-style","title":"Set style","text":"
txt.setStyle(style);\ntxt.setFont(font);  // font: {fontFamily, fontSize, fontStyle}\ntxt.setFontFamily(family);\ntxt.setFontSize(size);\ntxt.setFontStyle(style);\n
"},{"location":"bbcodetext/#color","title":"Color","text":"
  • Text color
    • Get
      var color = txt.style.color;\n
    • Set
      txt.setColor(color);\n
      or
      txt.setFill(color);\n
      • color : null, css string, or number.
  • Stroke color, thickness
    • Get
      var color = txt.style.stroke;\nvar thickness = txt.style.strokeThickness;\n
    • Set
      txt.setStroke(color, thickness);\n
      • color : null, css string, or number.
    • Clear
      txt.setStroke();\n
  • Underline color, thickness
    • Get
      var color = txt.style.underlineColor;\nvar thickness = txt.style.underlineThickness;\nvar offset = txt.style.underlineOffset;\n
    • Set
      txt.setUnderline(color, thickness, ofset);\ntxt.setUnderlineColor(color);\ntxt.setUnderlineThinkness(thickness);\ntxt.setUnderlineOffset(ofset);\n
      • color : null, css string, or number.
  • Strikethrough color, thickness
    • Get
      var color = txt.style.strikethroughColor;\nvar thickness = txt.style.strikethroughThickness;\nvar offset = txt.style.strikethroughOffset;\n
    • Set
      txt.setStrikethrough(color, thickness, ofset);\ntxt.setStrikethroughColor(color);\ntxt.setStrikethroughThinkness(thickness);\ntxt.setStrikethroughOffset(ofset);\n
      • color : null, css string, or number.
  • Background
    • Color, or gradient color
      • Get
        var color = txt.style.backgroundColor;\nvar color2 = txt.style.backgroundColor2;\nvar isHorizontalGradient = txt.style.backgroundHorizontalGradient;\n
      • Set
        txt.setBackgroundColor(color);\n// txt.setBackgroundColor(color, color2, isHorizontalGradient);\n
        • color, color2 : null, css string, or number.
    • Stroke color
      • Get
        var color = txt.style.backgroundStrokeColor;\nvar lineWidth = txt.style.backgroundStrokeLineWidth;\n
      • Set
        txt.setBackgroundStrokeColor(color, lineWidth);\n
        • color : null, css string, or number.
    • Round rectangle
      • Get
        var radius = txt.style.backgroundCornerRadius;\nvar iteration = txt.style.backgroundCornerIteration;\n
        • radius :
          • 0 : No round corner
          • > 0 : Convex round corner
          • < 0 : Concave round corner
      • Set
        txt.setBackgroundCornerRadius(radius);\n// txt.setBackgroundCornerRadius(radius, iteration);\n
        • iteration :
          • undefined : Round rectangle
          • 0 : Octagon
  • Shadow
    • Get
      var color = txt.style.shadowColor;\nvar offsetX = txt.style.shadowOffsetX;\nvar offsetY = txt.style.shadowOffsetY;\nvar blur = txt.style.shadowBlur;\nvar stroke = txt.style.shadowStroke;\nvar enabled = txt.style.shadowFill;\n
    • Set
      txt.setShadow(x, y, color, blur, shadowStroke, shadowFill);\ntxt.setShadowOffset(x, y);\ntxt.setShadowColor(color);\ntxt.setShadowBlur(blur);\ntxt.setShadowStroke(enabled);\ntxt.setShadowFill(enabled);\n
      • color : null, css string, or number.
"},{"location":"bbcodetext/#align","title":"Align","text":"
  • Horizontal align
    • Get
      var align = txt.style.halign;\n
      • align : 'left', 'center', 'right'
    • Set
      txt.setHAlign(align);    
      or
      txt.setAlign(align);    
      • align : 'left', 'center', 'right'
  • Vertical align
    • Get
      var align = txt.style.valign;\n
      • align : 'top', 'center', 'bottom'
    • Set
      txt.setVAlign(align);    
      • align : 'top', 'center', 'bottom'
"},{"location":"bbcodetext/#image","title":"Image","text":"
  • Uses texture key as image key by default.
  • Add image render information
    txt.addImage(imgKey, {\nkey: textureKey,\nframe: frameName,\nwidth: undefined,\nheight: undefined,\ny: 0,\nleft: 0,\nright: 0,\noriginX: 0,\noriginY: 0,\ntintFill: false,\n});\n
    • imgKey : Image key used in text content, i.e. [img=imgKey].
    • key : Texture key.
    • frame : Frame name.
    • width : Render width, set undefined to use the cut width of frame.
    • height : Render height, set undefined to use the cut height of frame.
    • y : Extra offset y.
    • left : Left padding space.
    • Right : Right padding space.
    • originX : Offset x via frame width * originX
    • originY : Offset y via frame height * originY
    • tintFill :
      • false : Keep original color. Default behavior.
      • true : Change fill-color by color tag. [color=...][img=...].
  • Add some image render informations
    txt.addImage(data);\n
    • data : {imgKey, config}
"},{"location":"bbcodetext/#hit-area-of-words","title":"Hit area of words","text":"

Size of hit-area is word-width x line-height, or image-width x line-height.

"},{"location":"bbcodetext/#hitting-events","title":"Hitting events","text":"
  • Pointer down
    txt.on('areadown', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areadown-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
  • Pointer click : pointer down then up, without pointer out
    txt.on('areaclick', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areaclick-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
  • Pointer up
    txt.on('areaup', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areaup-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
  • Pointer over
    txt.on('areaover', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areaover-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
  • Pointer out
    txt.on('areaout', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areaout-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
"},{"location":"bbcodetext/#draw-hit-areas","title":"Draw hit-areas","text":"
txt.drawAreaBounds(graphics, color);\n
  • graphics : Graphics game object
  • color : Default value is 0xffffff
"},{"location":"bbcodetext/#line-spacing","title":"Line spacing","text":"

This value is added to the height of the font when calculating the overall line height.

  • Get
    var lineSpacing = txt.style.lineSpacing;\n
  • Set
    txt.setLineSpacing(value);\n
"},{"location":"bbcodetext/#padding","title":"Padding","text":"
  • Get
    var left = txt.padding.left;\nvar top = txt.padding.top;\nvar right = txt.padding.right;\nvar bottom = txt.padding.bottom;\n
  • Set
    txt.setPadding(left, top, right, bottom);\n// txt.setPadding(padding); // padding: {left, top, right, bottom}\n
"},{"location":"bbcodetext/#max-lines","title":"Max lines","text":"
  • Get
    var maxLines = txt.style.maxLines;\n
  • Set
    txt.setMaxLines(max);\n
"},{"location":"bbcodetext/#fixed-size","title":"Fixed size","text":"
  • Get
    var width = txt.style.fixedWidth;\nvar height = txt.style.fixedHeight;\n
  • Set
    txt.setFixedSize(width, height);\n
"},{"location":"bbcodetext/#margin-of-text","title":"Margin of text","text":"
var leftMargin = txt.measureTextMargins(testString).left;\n
  • testString : Measure left margin of this text.
"},{"location":"bbcodetext/#shift-start-position-of-text","title":"Shift start position of text","text":"
txt.setXOffset(value);\n
"},{"location":"bbcodetext/#resolution","title":"Resolution","text":"
  • Get
    var resolution = txt.style.resolution;\n
  • Set
    txt.setResolution(resolution);\n
"},{"location":"bbcodetext/#test-string","title":"Test string","text":"

Set the test string to use when measuring the font.

txt.setTestString(text);\n
"},{"location":"bbcodetext/#save-texture","title":"Save texture","text":"
txt.generateTexture(key);\n// txt.generateTexture(key, x, y, width, height);\n
"},{"location":"bbcodetext/#delimiters","title":"Delimiters","text":"
txt.setDelimiters(delimiters);  // '<>', or ['<', '>']\n

or

txt.setDelimiters(delimiterLeft, delimiterRight); // '<', '>'\n

Warning

Don't use () as delimiters, which is preserved for color value.

"},{"location":"bbcodetext/#rtl","title":"RTL","text":"
  • Set rtl in style config when creating this text game object
  • Change rtl during runtime
    txt.setRTL(rtl).setText(newContent);\n
    • Invoke setRTL method before setting new content.
"},{"location":"bbcodetext/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"bbcodetext/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"bbcodetext/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"bitmaptext/","title":"Static bitmap text","text":""},{"location":"bitmaptext/#introduction","title":"Introduction","text":"

Drawing text by texture, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"bitmaptext/#usage","title":"Usage","text":""},{"location":"bitmaptext/#load-bitmap-font","title":"Load bitmap font","text":"
  • Load bitmap font from texture and xml configuration
    scene.load.bitmapFont(key, textureURL, xmlURL);\n
    • Reference: load bitmap font
    • Loaded texture also can be used for Image, Sprite, or Arcade Image, Arcade Sprite
      scene.add.image(x, y, key, char);\n
  • Load retro bitmap font from texture and JSON configuration
    1. Load texture in preload stage
      scene.load.image(key, url);\n
      Reference: load image
    2. Add retro bitmap font
      var config = {\n// image\nimage: '',\noffset: {\nx: 0,\ny: 0\n},\n// characters\nwidth: 32,\nheight: 32,\nchars: '',\ncharsPerRow: 10,\n// spacing\nspacing: {\nx: 0,\ny: 0\n},\nlineSpacing: 0\n}\nscene.cache.bitmapFont.add(key, Phaser.GameObjects.RetroFont.Parse(scene, config));\n
      • Image :
        • image : The key of the image containing the font.
        • offset : If the font set doesn't start at the top left of the given image, specify the X/Y coordinate offset here.
      • Characters :
        • width : The width of each character in the font set.
        • height : The height of each character in the font set.
        • chars : The characters used in the font set, in display order.
          • Default characters set
        • charsPerRow : The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth.
      • Spacing :
        • spacing : If the characters in the font set have horizontal/vertical spacing between them set the required amount here.
        • lineSpacing : The amount of vertical space to add to the line height of the font.
"},{"location":"bitmaptext/#add-bitmap-text-object","title":"Add bitmap text object","text":"
var txt = scene.add.bitmapText(x, y, key, text);\n// var txt = scene.add.bitmapText(x, y, key, text, size, align);\n
  • size : The size of the font
  • align : The alignment of the text in a multi-line BitmapText object.
    • 0 : Left aligned (default)
    • 1 : Middle aligned
    • 2 : Right aligned

Add text from JSON

var txt = scene.make.bitmapText({\nx: 0,\ny: 0,\ntext: 'Text\\nGame Object\\nCreated from config',\nfont: '',\nsize: false,\nalign: 0,\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
"},{"location":"bitmaptext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyText extends Phaser.GameObjects.BitmapText {\nconstructor(scene, x, y, key, text, size, align) {\nsuper(scene, x, y, key, text, size, align);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyText(scene, x, y, key, text);\n
"},{"location":"bitmaptext/#set-text","title":"Set text","text":"
txt.setText('...');\n

or

txt.text = '...';\n
"},{"location":"bitmaptext/#set-align","title":"Set align","text":"
  • Left aligned
    txt.setLeftAlign();\n
  • Middle aligned
    txt.setCenterAlign();\n
  • Right aligned
    txt.setRightAlign();\n

or

txt.align = align;\n
  • align :
    • 0 : Left aligned (default)
    • 1 : Middle aligned
    • 2 : Right aligned
"},{"location":"bitmaptext/#set-letter-spacing","title":"Set letter spacing","text":"
txt.setLetterSpacing(spacing);\n

or

txt.letterSpacing = spacing;\n

Can be a positive value to increase the space, or negative to reduce it.

"},{"location":"bitmaptext/#set-line-spacing","title":"Set line spacing","text":"
txt.setLineSpacing(spacing);\n

or

txt.lineSpacing = spacing;\n

Can be a positive value to increase the space, or negative to reduce it.

"},{"location":"bitmaptext/#set-font-size","title":"Set font size","text":"
txt.setFontSize(size);\n

or

txt.fontSize = size;\n
"},{"location":"bitmaptext/#set-font","title":"Set font","text":"
txt.setFont(key);\n// txt.setFont(key, size, align);\n
"},{"location":"bitmaptext/#tint","title":"Tint","text":"

See Tint.

"},{"location":"bitmaptext/#color-of-characters","title":"Color of characters","text":"
  • By character
    txt.setCharacterTint(start, length, tintFill, color);\n// txt.setCharacterTint(start, length, tintFill, topLeft, topRight, bottomLeft, bottomRight);\n
    • start : Index starting character.
      • < 0 : Counts back from the end of the text.
    • length : Number of characters to tint.
      • -1 : All characters from start
    • tintFill :
      • true : Fill-based tint
      • false : Additive tint
    • color, or topLeft, topRight, bottomLeft, bottomRight : Color integer.
  • By word
    txt.setWordTint(word, count, tintFill, color);\n// txt.setWordTint(word, count, tintFill, topLeft, topRight, bottomLeft, bottomRight);\n
    • word : The word to search for.
      • A string
      • An index of the word in the words array.
    • count : Number of matching words to tint.
      • -1 : All matching words
    • tintFill :
      • true : Fill-based tint
      • false : Additive tint
    • color, or topLeft, topRight, bottomLeft, bottomRight : Color integer.
"},{"location":"bitmaptext/#drop-shadow-effect","title":"Drop shadow effect","text":"
txt.setDropShadow(x, y, color, alpha);\n

or

txt.dropShadowX = x;\ntxt.dropShadowY = y;\ntxt.dropShadowColor = color;\ntxt.dropShadowAlpha = alpha;\n
  • x, y : The horizontal/vertical offset of the drop shadow.
  • color : The color of the drop shadow.
  • alpha : The alpha of the drop shadow.

Note

WebGL only

"},{"location":"bitmaptext/#wrap","title":"Wrap","text":"
  • Wrap
    txt.setMaxWidth(width);\n// txt.setMaxWidth(width, wordWrapCharCode);\n
    • width : Line width in pixels.
    • wordWrapCharCode : The character code to check for when word wrapping. Defaults to 32 (the space character)
  • Disable wrapping
    txt.setMaxWidth(0);\n
"},{"location":"bitmaptext/#get-bounds","title":"Get bounds","text":"
var width = txt.width;\nvar height = txt.height;\n

or

var bounds = txt.getTextBounds(round);\n// bounds = {\n//     local: {\n//         x: 0,\n//         y: 0,\n//         width: 0,\n//         height: 0\n//     },\n//     global: {\n//         x: 0,\n//         y: 0,\n//         width: 0,\n//         height: 0\n//     },\n//     lines: {\n//         shortest: 0,\n//         longest: 0,\n//         lengths: null,\n//         height: 0\n//     },\n//     wrappedText: '',\n//     words: [],\n//     characters: [],\n//     scaleX: 0,\n//     scaleY: 0\n// };\n
  • round : Set true to round the results to the nearest integer.
  • local : The BitmapText based on fontSize and 0x0 coords.
  • global : The BitmapText, taking into account scale and world position.
  • lines : The BitmapText line data.
  • wrappedText : Wrapped content joined with '\\n'.
  • characters : Information of each character.
    {\nchar, code, i, idx, x, y, w, h, t, b, r, line\n}\n
    • char : Character (string).
    • code: Character code (number)
    • i : Index of character
    • x , y : World position of this character
    • w, h : Width/height of this character
    • t, b : The top/bottom of the line this character is on.
    • r : The right-most point of this character, including xAdvance.
    • line : The line number the character appears on.
  • words : Information of each word.
    {\nword, i, x, y, w, h, cr\n\n}\n
    • word : Word string.
    • i : Index of start character
    • x, y : World position of start character
    • w , h : Width/height of word
    • cr : Is last word of current line
  • scaleX, scaleY : Scale of width and height.
"},{"location":"bitmaptext/#get-information-of-character","title":"Get information of character","text":"
var data = txt.getCharacterAt(x, y);\n// var data = txt.getCharacterAt(x, y, camera);\n
  • x, y : World position.
  • camera : The Camera which is being tested against.
  • data : Information of character at world position.
    {\nchar, code, i, x, y, w, h, t, b, r, line\n}\n
    • char : Character (string).
    • code: Character code (number)
    • i : Index of character
    • x , y : World position of this character
    • w, h : Width/height of this character
    • t, b : The top/bottom of the line this character is on.
    • r : The right-most point of this character, including xAdvance.
    • line : The line number the character appears on.
"},{"location":"bitmaptext/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"bitmaptext/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"bitmaptext/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"bitmaptext/#appendix","title":"Appendix","text":""},{"location":"bitmaptext/#default-characters-set-of-retro-font","title":"Default characters set of retro font","text":"
  • Phaser.GameObjects.RetroFont.TEXT_SET1 :
    ' !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET2 :
    ' !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET3 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '\n
  • Phaser.GameObjects.RetroFont.TEXT_SET4 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET5 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() \\'!?-*:0123456789'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET6 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.\\' '\n
  • Phaser.GameObjects.RetroFont.TEXT_SET7 :
    'AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-\\'39'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET8 :
    '0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET9 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,\\'\"?!'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET10 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET11 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()\\':;0123456789'\n
"},{"location":"bitmapzone/","title":"Bitmap zone","text":""},{"location":"bitmapzone/#introduction","title":"Introduction","text":"

Particles' emitter zone from canvas bitmap of text/canvas game object.

  • Author: Rex
  • Geometry object
"},{"location":"bitmapzone/#live-demo","title":"Live demo","text":"
  • Particles
"},{"location":"bitmapzone/#usage","title":"Usage","text":"

Sample code

"},{"location":"bitmapzone/#install-plugin","title":"Install plugin","text":""},{"location":"bitmapzone/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbitmapzoneplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbitmapzoneplugin.min.js', true);\n
  • Add bitmap-zone object
    var bitmapZone = scene.plugins.get('rexbitmapzoneplugin').add(gameObject, config);\n
"},{"location":"bitmapzone/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BitmapZonePlugin from 'phaser3-rex-plugins/plugins/bitmapzone-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBitmapZone',\nplugin: BitmapZonePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add bitmap-zone object
    var bitmapZone = scene.plugins.get('rexBitmapZone').add(gameObject, config);\n
"},{"location":"bitmapzone/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import BitmapZone from 'phaser3-rex-plugins/plugins/bitmapzone.js';\n
  • Add bitmap-zone object
    var bitmapZone = new BitmapZone(gameObject, config);\n
"},{"location":"bitmapzone/#create-shape","title":"Create shape","text":"
var bitmapZone = scene.plugins.get('rexBitmapZone').add(gameObject);\n
  • gameObject :
    • Any kind of text object : Text object, bbcode text object, or tag text object.
    • Canvas object
"},{"location":"bitmapzone/#emit-zone","title":"Emit zone","text":"
var particles = scene.add.particles(key,\n[\n// emitter config\n{\n// blendMode:\n// scale:\n// speed:\n// garvityY:\nemitZone: {\ntype: 'random',\nsource: bitmapZone\n}\n}\n]);\n

bitmapZone provides getRandomPoint method.

"},{"location":"bitmapzone/#update-content","title":"Update content","text":"
bitmapZone.setSource(gameObject);\n
"},{"location":"blendmode/","title":"Blend mode","text":""},{"location":"blendmode/#introduction","title":"Introduction","text":"

Constant value of blend modes.

  • Author: Richard Davey
"},{"location":"blendmode/#usage","title":"Usage","text":""},{"location":"blendmode/#webgl-and-canvas","title":"WebGL and Canvas","text":"
  • 'NORMAL', or Phaser.BlendModes.NORMAL, or 0
    • Default setting and draws new shapes on top of the existing canvas content.
  • 'ADD', or Phaser.BlendModes.ADD, or 1
    • Where both shapes overlap the color is determined by adding color values.
  • 'MULTIPLY', or Phaser.BlendModes.MULTIPLY, or 2
    • The pixels are of the top layer are multiplied with the corresponding pixel of the bottom layer. A darker picture is the result.
  • 'SCREEN', or Phaser.BlendModes.SCREEN, or 3
    • The pixels are inverted, multiplied, and inverted again. A lighter picture is the result (opposite of multiply)
  • 'ERASE', or Phaser.BlendModes.ERASE, or 17
    • Alpha erase blend mode. Only works when rendering to a framebuffer, like a Render Texture
"},{"location":"blendmode/#canvas-only","title":"Canvas only","text":"
  • 'OVERLAY', or Phaser.BlendModes.OVERLAY, or 4
    • A combination of multiply and screen. Dark parts on the base layer become darker, and light parts become lighter.
  • 'DARKEN', or Phaser.BlendModes.DARKEN, or 5
    • Retains the darkest pixels of both layers.
  • 'LIGHTEN', or Phaser.BlendModes.LIGHTEN, or 6
    • Retains the lightest pixels of both layers.
  • 'COLOR_DODGE', or Phaser.BlendModes.COLOR_DODGE, or 7
    • Divides the bottom layer by the inverted top layer.
  • 'COLOR_BURN', or Phaser.BlendModes.COLOR_BURN, or 8
    • Divides the inverted bottom layer by the top layer, and then inverts the result.
  • 'HARD_LIGHT', or Phaser.BlendModes.HARD_LIGHT, or 9
    • A combination of multiply and screen like overlay, but with top and bottom layer swapped.
  • 'SOFT_LIGHT', or Phaser.BlendModes.SOFT_LIGHT, or 10
    • A softer version of hard-light. Pure black or white does not result in pure black or white.
  • 'DIFFERENCE', or Phaser.BlendModes.DIFFERENCE, or 11
    • Subtracts the bottom layer from the top layer or the other way round to always get a positive value.
  • 'EXCLUSION', or Phaser.BlendModes.EXCLUSION, or 12
    • Like difference, but with lower contrast.
  • 'HUE', or Phaser.BlendModes.HUE, or 13
    • Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer.
  • 'SATURATION', or Phaser.BlendModes.SATURATION, or 14
    • Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer.
  • 'COLOR', or Phaser.BlendModes.COLOR, or 15
    • Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer.
  • 'LUMINOSITY', or Phaser.BlendModes.LUMINOSITY, or 16
    • Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer.
  • 'SOURCE_IN', or Phaser.BlendModes.SOURCE_IN, or 18
    • The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent.
  • 'SOURCE_OUT', or Phaser.BlendModes.SOURCE_OUT, or 19
    • The new shape is drawn where it doesn't overlap the existing canvas content.
  • 'SOURCE_ATOP', or Phaser.BlendModes.SOURCE_ATOP, or 20
    • The new shape is only drawn where it overlaps the existing canvas content.
  • 'DESTINATION_OVER', or Phaser.BlendModes.DESTINATION_OVER, or 21
    • New shapes are drawn behind the existing canvas content.
  • 'DESTINATION_IN', or Phaser.BlendModes.DESTINATION_IN, or 22
    • The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent.
  • 'DESTINATION_OUT', or Phaser.BlendModes.DESTINATION_OUT, or 23
    • The existing content is kept where it doesn't overlap the new shape.
  • 'DESTINATION_ATOP', or Phaser.BlendModes.DESTINATION_ATOP, or 24
    • The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content.
  • 'LIGHTER', or Phaser.BlendModes.LIGHTER, or 25
    • Where both shapes overlap the color is determined by adding color values.
  • 'COPY', or Phaser.BlendModes.COPY, or 26
    • Only the new shape is shown.
  • 'XOR', or Phaser.BlendModes.XOR, or 27
    • Shapes are made transparent where both overlap and drawn normal everywhere else.

Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these reasons try to be careful about the construction of your Scene and the frequency in which blend modes are used.

"},{"location":"blitter/","title":"Blitter","text":""},{"location":"blitter/#introduction","title":"Introduction","text":"

Display of static images, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"blitter/#usage","title":"Usage","text":""},{"location":"blitter/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"blitter/#add-blitter-container","title":"Add blitter container","text":"

Add blitter container

var blitter = scene.add.blitter(x, y, key);\n

Add blitter container from JSON

var blitter = scene.make.blitter({\nx: 0,\ny: 0,\nkey: '',\n\n// angle: 0,\n// alpha: 1\n// flipX: true,\n// flipY: true,\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
"},{"location":"blitter/#custom-class","title":"Custom class","text":"
  • Define class
    class MyBlitter extends Phaser.GameObjects.Blitter {\nconstructor(scene, x, y, texture, frame) {\nsuper(scene, x, y, texture, frame);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var blitter = new MyBlitter(scene, x, y, key);\n
"},{"location":"blitter/#add-bob-object","title":"Add bob object","text":"
var bob = blitter.create(x, y);\n// var bob = blitter.create(x, y, frame, visible, index);\n
  • frame : The Frame the Bob will use. It must be part of the Texture the parent Blitter object is using.
  • visible : Should the created Bob render or not?
  • index : The position in the Blitters Display List to add the new Bob at. Defaults to the top of the list.
"},{"location":"blitter/#add-mutiple-bob-objects","title":"Add mutiple bob objects","text":"
var bobs = blitter.createMultiple(quantity, frame, visible);\n
  • quantity : The quantity of Bob objects to create.
"},{"location":"blitter/#add-bob-object-from-callback","title":"Add bob object from callback","text":"
var bobs = blitter.createFromCallback(callback, quantity, frame, visible)\n// var callback = function(bob, i){};\n
"},{"location":"blitter/#get-bob-objects","title":"Get bob objects","text":"
var bobs = blitter.children.list;\n
"},{"location":"blitter/#clear-all-bob-objects","title":"Clear all bob objects","text":"
blitter.clear();\n
"},{"location":"blitter/#bob-object","title":"Bob object","text":"

A Bob has a position, alpha value and a frame from a texture that it uses to render with. You can also toggle the flipped and visible state of the Bob.

"},{"location":"blitter/#position","title":"Position","text":"
  • Get
    var x = bob.x;\nvar y = bob.y;\n
  • Set
    bob.setPosition(x, y);\n// bob.x = 0;\n// bob.y = 0;\n
    or
    bob.reset(x, y);\n// bob.reset(x, y, frame);\n
"},{"location":"blitter/#frame","title":"Frame","text":"
  • Get
    var frame = bob.frame;\n
    • frame : Frame object.
  • Set
    bob.setFrame(frame);\n
"},{"location":"blitter/#flip","title":"Flip","text":"
  • Get
    var flipX = bob.flipX;\nvar flipY = bob.flipY;\n
  • Set
    bob.setFlip(boolX, boolY);\n// bob.setFlipX(boolean);\n// bob.setFlipY(boolean);\n// bob.flipX = flipX;\n// bob.flipY = flipY;\n
    or
    bob.resetFlip(); // bob.setFlip(false, false)\n
"},{"location":"blitter/#visible","title":"Visible","text":"
  • Get
    var visible = bob.visible;\n
  • Set
    bob.setVisible(boolean);\n// bob.visible = v;\n
"},{"location":"blitter/#alpha","title":"Alpha","text":"
  • Get
    var alpha = bob.alpha;\n
  • Set
    bob.setAlpha(v);\n// bob.aplha = v;\n
"},{"location":"blitter/#tint","title":"Tint","text":"
  • Get
    var tint = bob.tint;\n
  • Set
    bob.setTint(tint);\n// bob.tint = tint;\n
    • tint : Tint value, between 0 and 0xffffff.
"},{"location":"blitter/#destroy","title":"Destroy","text":"
bob.destroy();\n
"},{"location":"blitter/#data","title":"Data","text":"
var data = bob.data;  // {}\n
"},{"location":"blitter/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"blitter/#create-mask","title":"Create mask","text":"
var mask = bob.createBitmapMask();\n

See mask

"},{"location":"blitter/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"board-bejeweled/","title":"Bejeweled","text":""},{"location":"board-bejeweled/#introduction","title":"Introduction","text":"

Match3-like gameplay template.

  • Author: Rex
  • Template
"},{"location":"board-bejeweled/#live-demos","title":"Live demos","text":"
  • Events
  • Custom input
  • Mask
"},{"location":"board-bejeweled/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-bejeweled/#install-plugin","title":"Install plugin","text":""},{"location":"board-bejeweled/#load-minify-file","title":"Load minify file","text":"
  • Load rexBoard plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\nscene.load.script('rexbejeweled', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbejeweled.min.js');\n
  • Add bejeweled object
    var bejeweled = new rexbejeweled(scene, config);\n
"},{"location":"board-bejeweled/#import-template","title":"Import template","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install rexBoard plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nimport Bejeweled from 'phaser3-rex-plugins/templates/bejeweled/Bejeweled.js';\n\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add bejeweled object
    var bejeweled = new Bejeweled(scene, config);\n
"},{"location":"board-bejeweled/#create-bejeweled-object","title":"Create bejeweled object","text":"
var bejeweled = new Bejeweled(scene, {\n// rexBoard: 'rexBoard',\n\nboard: {\ngrid: {\ngridType: 'quadGrid',\nx: 30,\ny: 30 - 600,\ncellWidth: 60,\ncellHeight: 60,\n},\nwidth: 10,\nheight: 20 // Prepared rows: upper 10 rows\n},\nmatch: {\n// wildcard: undefined\n// dirMask: undefined\n},\nchess: {\n// pick random symbol from array, or a callback to return symbol\nsymbols: [0, 1, 2, 3, 4, 5],\n// symbols: function(board, tileX, tileY, excluded) { return symbol; }\n\n// User-defined chess game object\ncreate: function (board) {\n// Create Game object (Shape, Image, or Sprite)\nvar scene = board.scene;\nvar gameObject = scene.add.sprite(0, 0, textureKey, frame);\n// Initial 'symbol' value\ngameObject.setData('symbol', undefined);\n// Add data changed event of 'symbol` key\ngameObject.data.events.on('changedata_symbol', function (gameObject, value, previousValue) {\n// Change the appearance of game object via new symbol value\ngameObject.setFrame(newFrame);\n});\nreturn gameObject;\n},\n\n// scope for callbacks\nscope: undefined,\n\n// moveTo behavior\nmoveTo: {\nspeed: 400\n},\n// tileZ: 1,\n},\n// mask: false,\n\nselect1Action: undefined,\nselect2Action: undefined,\nswapAction: undefined,\nundoSwapAction: undefined,\neliminatingAction: undefined,\nfallingAction: undefined,\n\n// input: true\n})\n

Configurations

  • rexBoard : Key of 'rexBoard' plugin. Default is 'rexBoard'.
  • Board properties
    • board.width : Board width in tiles.
    • board.height : Board height in tiles.
    • board.grid.x, board.grid.y : World position of tile (0, 0)
    • board.grid.cellWidth, board.grid.cellHeight : The width/height of the cell, in pixels.
  • Chess properties
    • chess.symbols : An array of possible symbols, or a callback to return a symbol. See Generate symbol
    • chess.create, chess.scope : Callback of creating chess object.
    • chess.moveTo.speed : Constant moving speed of chess, in pixel per-second.
  • Custom actions
    • select1Action : Custom select first chess Action
    • select2Action : Custom select second chess Action
    • swapAction : Custon swap action
    • undoSwapAction : Custon undo-swap action
    • eliminatingAction : Custon eliminating action
    • fallingAction : Custon falling action
  • Touch input
    • input : Set true to register default touch input logic.
  • Mask
    • mask :
      • false : No mask. Default behavior.
      • true : Mask invisible upper rows.
        1. Create an internal layer
        2. Mask this internal layer.
"},{"location":"board-bejeweled/#board-height","title":"Board height","text":"

Board is separated into two parts: upper and bottom

  • Bottom : Visible N rows, to swap chess and run matching.
  • Upper : Invisible N rows, chess in these rows will move down, to fill bottom rows.

For example, if amount of visible rows is 10, board.height should set to 20.

"},{"location":"board-bejeweled/#generate-symbol","title":"Generate symbol","text":"

Symbols are declared in property chess.symbols in a symbol array like [0, 1, 2, 3, 4, 5], or a callback to return a symbol. The callback also use chess.scope as the scope.

function(board, tileX, tileY, excluded) {\nreturn symbol\n}\n
  • excluded : undefined or a symbol array. Don't return these symbols.
"},{"location":"board-bejeweled/#create-chess-object","title":"Create chess object","text":"

Return a game object from a callback.

function(board) {\n// Create Game object (Image, Sprite, or Shape)\nvar scene = board.scene;\nvar gameObject = scene.add.sprite(0, 0, textureKey, frame);\n// Initial 'symbol' value\ngameObject.setData('symbol', undefined);\n// Add data changed event of 'symbol` key\ngameObject.data.events.on('changedata_symbol', function (gameObject, value, previousValue) {\n// Change the appearance of game object via new symbol value\ngameObject.setFrame(newFrame);\n});\nreturn gameObject;\n}\n

Each chess has a symbol value stored in 'symbol' key in private data. Add data changed event of 'symbol' key to change the appearance of game object via new symbol value.

"},{"location":"board-bejeweled/#states","title":"States","text":"
graph TD\n\nStart((Start)) --> Select1Start[select1-start]\n\nsubgraph Select 1 states\n  Select1Start --> |Input| Select1[select1]\nend\n\nSelect1 --> select2Start[select2-start]\n\nsubgraph Select 2 states\n  select2Start --> |Input| select2[select2]\nend\n\nselect2Start --> Select1Start\nselect2 --> Swap[swap]\nSwap --> MatchStart[match-start]\n\nsubgraph Match states\n  MatchStart --> Match[match]\n  Match --> Eliminate[eliminate]\n  Match --> MatchEnd[match-end]\n  Eliminate --> Fall[fall]\n  Fall --> Fill[fill]\n  Fill --> Match\nend\n\nMatchEnd --> UndoSwap[undo-swap]\nUndoSwap --> Select1Start\nMatchEnd --> Select1Start
"},{"location":"board-bejeweled/#select-first-chess","title":"Select first chess","text":"

Fire 'select1' event

bejeweled.on('select1', function(board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#custom-select-first-chess-action","title":"Custom Select first chess Action","text":"

Default select action:

function (chess, board, bejeweled) {\n// Do nothing\n}\n
"},{"location":"board-bejeweled/#select-second-chess","title":"Select second chess","text":"

Fire 'select2' event

bejeweled.on('select2', function(board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
    • Selected first chess :
      var chess = bejeweled.getSelectedChess1();\n
"},{"location":"board-bejeweled/#custom-select-second-chess-action","title":"Custom Select second chess Action","text":"

Default select action: The same as Select first chess Action

"},{"location":"board-bejeweled/#swap-selected-chess","title":"Swap selected chess","text":"

Fire 'swap' event

bejeweled.on('swap', function(selectedChess1, selectedChess2, board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#custom-swap-action","title":"Custom Swap Action","text":"

Default swap action:

function (chess1, chess2, board, bejeweled) {\nvar tileXYZ1 = board.chessToTileXYZ(chess1);\nvar tileXYZ2 = board.chessToTileXYZ(chess2);\nvar tileX1 = tileXYZ1.x,\ntileY1 = tileXYZ1.y,\ntileX2 = tileXYZ2.x,\ntileY2 = tileXYZ2.y,\ntileZ = tileXYZ1.z;\n\n// TileZ of chess1 and chess2 are the same, change tileZ of chess2 to a different value\nboard.moveChess(chess2, tileX2, tileY2, `#${tileZ}`, false);\n\n// Move chess1 to tileXYZ2, chess2 to tileXYZ1\nvar moveTo1 = bejeweled.getChessMoveTo(chess1);\nvar moveTo2 = bejeweled.getChessMoveTo(chess2);\nmoveTo1.moveTo(tileX2, tileY2);\nmoveTo2.moveTo(tileX1, tileY1);\n\n// Change tileZ of chess2 back\nboard.moveChess(chess2, tileX1, tileY1, tileZ, false);\n\nif (moveTo1.isRunning) {\nbejeweled.waitEvent(moveTo1, 'complete');\n}\nif (moveTo2.isRunning) {\nbejeweled.waitEvent(moveTo2, 'complete');\n}\n};\n
  • bejeweled.getChessMoveTo(chess) : Get moveTo behavior of a chess.
  • bejeweled.waitEvent(moveTo, 'complete') : Wait 'complete' event of this moveTo behavior.
"},{"location":"board-bejeweled/#match-start","title":"Match start","text":"

Fire 'match-start' event

bejeweled.on('match-start', function(board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#match-lines","title":"Match lines","text":"

Fire 'match' event

bejeweled.on('match', function(lines, board, bejeweled) {\n\n}, scope);\n
  • lines : An array of matched lines, each line is a built-in Set object.
    • Length of each line (lines[i].size) could be 5, 4, or 3.
    • lines[i].entries : An array of chess (Game Object) in a matched line.
    • Get cross chess of two lines via lineA.intersect(lineB).
    • All chess game objects in matched lines will be eliminated in next stage.
      • Add/remove chess game object in a line.
      • Add new line/remove a line in lines array to change the eliminated targets.
  • board : Board object.
    • Get tile position {x,y,z} of a chess game object via
      var tileXYZ = board.chessToTileXYZ(gameObject);\n//var tileXYZ = gameObject.rexChess.tileXYZ;\n
    • Get chess game object of a tile position {x,y,z} via
      var gameObject = board.tileXYZToChess(tileX, tileY, tileZ);\n
    • Get array of neighbor chess of a chess game object via
      var gameObjects = board.getNeighborChess(chess, null);\n
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#eliminating-chess","title":"Eliminating chess","text":"

Fire 'eliminate' event

bejeweled.on('eliminate', function(chessArray, board, bejeweled) {\n\n}, scope);\n
  • chessArray : An array of chess (Game Object) to be eliminated.
  • board : Board object
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#custom-eliminating-action","title":"Custom Eliminating Action","text":"

Default eliminating action:

function (chessArray, board, bejeweled) {\nconst duration = 500; //ms\nfor (var i = 0, cnt = chessArray.length; i < cnt; i++) {\nvar fade = FadeOutDestroy(chessArray[i], duration);\nbejeweled.waitEvent(fade, 'complete');\n}\n}\n
  • bejeweled.waitEvent(fade, 'complete') : Wait 'complete' event of this fade-out-destroy behavior.
"},{"location":"board-bejeweled/#falling-chess","title":"Falling chess","text":"

Fire 'fall' event

bejeweled.on('fall', function(board, bejeweled) {\n\n}, scope);\n
  • board : Board object
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#custom-falling-action","title":"Custom Falling Action","text":"

Default falling action:

function (board, bejeweled) {\nvar tileZ = bejeweled.chessTileZ,\nchess, moveTo;\n\nfor (var tileY = (board.height - 1); tileY >= 0; tileY--) { // bottom to top\nfor (var tileX = 0, cnt = board.width; tileX < cnt; tileX++) { // left to right\nchess = board.tileXYZToChess(tileX, tileY, tileZ);\nif (chess === null) {\ncontinue;\n}\nmoveTo = bejeweled.getChessMoveTo(chess);\ndo {\nmoveTo.moveToward(1);\n} while (moveTo.lastMoveResult)\nif (moveTo.isRunning) {\nbejeweled.waitEvent(moveTo, 'complete');\n}\n}\n}\n}\n
  • bejeweled.getChessMoveTo(chess) : Get moveTo behavior of a chess.
  • bejeweled.waitEvent(moveTo, 'complete') : Wait 'complete' event of this moveTo behavior.
"},{"location":"board-bejeweled/#fill-chess","title":"Fill chess","text":"

Fire 'fill' event

bejeweled.on('fill', function(board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#match-end","title":"Match end","text":"

Fire 'match-end' event

bejeweled.on('match-end', function(board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#undo-swap-selected-chess","title":"Undo-swap selected chess","text":"

Fire 'undo-swap' event

bejeweled.on('undo-swap', function(selectedChess1, selectedChess2, board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#custom-undo-swap-action","title":"Custom Undo-Swap Action","text":"

Default undo-swap action : Equal to Swap action

"},{"location":"board-bejeweled/#start-gameplay","title":"Start gameplay","text":"
bejeweled.start();\n
"},{"location":"board-bejeweled/#input-control","title":"Input control","text":""},{"location":"board-bejeweled/#default-input","title":"Default input","text":"
  1. Enable default input control
    var bejeweled = new Bejeweled(scene, {\n// ...\ninput: true\n});\n
  2. Enable/disable temporarily.
    • Enable
      bejeweled.setInputEnable();\n
    • Disable
      bejeweled.setInputEnable(false);\n
"},{"location":"board-bejeweled/#custom-input","title":"Custom input","text":"
  1. Discard default input control
    var bejeweled = new Bejeweled(scene, {\n// ...\ninput: false\n});\n
  2. Add custom input logic like
    scene.input\n.on('pointerdown', function (pointer) {\nvar chess = bejeweled.worldXYToChess(pointer.worldX, pointer.worldY);\nif (chess) {\nbejeweled.selectChess1(chess);\n}\n}, scene)\n.on('pointermove', function (pointer) {\nif (!pointer.isDown) {\nreturn;\n}\nvar chess = bejeweled.worldXYToChess(pointer.worldX, pointer.worldY);\nif (chess && (chess !== this.bejeweled.getSelectedChess1())) {\nbejeweled.selectChess2(chess);\n}\n}, scene);\n
    • Invoke bejeweled.selectChess1(chess), and bejeweled.selectChess2(chess) under custom logic.

Helper methods

  • Get chess via worldXY position
    var chess = bejeweled.worldXYToChess(worldX, worldY);\n
  • Get chess via tileXY position
    var chess = bejeweled.tileXYToChess(tileX, tileY);\n
  • Get neighbor chess via angle
    var chess2 = bejeweled.getNeighborChessAtAngle(chess1, angle);\n
    • chess1 : Chess object, or tileXY position {x, y}.
    • angle : Angle in radius.
  • Get neighbor chess via direction
    var chess2 = bejeweled.getNeighborChessAtDirection(chess1, direction);\n
    • chess1 : Chess object, or tileXY position {x, y}.
    • direction : Number, or string number.
      • 0 ~ 3 : Quad grid in 4 directions mode.
      • 0 ~ 7 : Quad grid in 8 directions mode.
      • 0 ~ 5 : Hexagon grid.
"},{"location":"board-bejeweled/#data","title":"Data","text":"
  • Get
    var value = bejeweled.getData(key);\nvar values = bejeweled.getData(keys); // keys: an array of keys\nvar value = bejeweled.data.values[key];\n
  • Set
    bejeweled.setData(key, value);\nbejeweled.setData(obj); // obj: {key0:value0, key1:value1, ...}\nbejeweled.data.values[key] = value;\nbejeweled.data.values[key] += inc;\n
  • Enable
    bejeweled.setDataEnabled();\n
  • Events :
    • Set data evant
      bejeweled.on('setdata', function(bejeweled, key, value){ /* ... */ });\n
    • Change data event
      bejeweled.on('changedata', function(bejeweled, key, value, previousValue){ /* ... */ });\n
      bejeweled.on('changedata-' + key, function(bejeweled, value, previousValue){ /* ... */ });\n

See data manager

Note

Ensure data manager is created before binding any data-changed events.

"},{"location":"board-bejeweled/#misc","title":"Misc","text":"
  • Board instance
    var board = bejeweled.getBoard();\n
    • board : Board instance.
  • Match instance
    var match = bejeweled.getMatch();\n
    • match : Match instance.
"},{"location":"board-chessdata/","title":"Chess data","text":""},{"location":"board-chessdata/#introduction","title":"Introduction","text":"

Properties of chess, chess behavior of Board system.

  • Author: Rex
  • Behavior of chess
"},{"location":"board-chessdata/#usage","title":"Usage","text":""},{"location":"board-chessdata/#add-chess-data-object","title":"Add chess data object","text":"

Chess data will be added to game object via gameObject.rexChess once adding this game object to board, or attach any chess behavior.

"},{"location":"board-chessdata/#get-chess-data","title":"Get chess data","text":"
var chessData = gameObject.rexChess;\n
"},{"location":"board-chessdata/#set-tile-z","title":"Set tile Z","text":"
gameObject.rexChess.setTileZ(tileZ);\n

(tileX, tileY) won't be changed.

"},{"location":"board-chessdata/#get-tile-position","title":"Get tile position","text":"
var tileXYZ = gameObject.rexChess.tileXYZ;\n
  • tileXYZ : Tile position {x,y,z}, return null if this chess is not added to any board.
"},{"location":"board-chessdata/#get-board","title":"Get board","text":"
var board = gameObject.rexChess.board;\n
  • board : Board object, or null if this chess is not added to any board.

See also

"},{"location":"board-chessdata/#blocker","title":"Blocker","text":"
  • Set
    gameObject.rexChess.setBlocker();\n
  • Disable
    gameObject.rexChess.setBlocker(false);\n
  • Get
    var blocker = gameObject.rexChess.blocker;\n
"},{"location":"board-fieldofview/","title":"Field of view","text":""},{"location":"board-fieldofview/#introduction","title":"Introduction","text":"

Visible testing, to find field of view, chess behavior of Board system.

  • Author: Rex
  • Behavior of chess
"},{"location":"board-fieldofview/#live-demos","title":"Live demos","text":"
  • Field of view
  • Line of sigh
  • Filter visible chess
  • Pre-test callback
"},{"location":"board-fieldofview/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-fieldofview/#install-plugin","title":"Install plugin","text":""},{"location":"board-fieldofview/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add field-of-view object
    var fieldOfView = scene.rexBoard.add.fieldOfView(chess, config);\n
"},{"location":"board-fieldofview/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add field-of-view object
    var fieldOfView = scene.rexBoard.add.fieldOfView(chess, config);\n
"},{"location":"board-fieldofview/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { FieldOfView } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add field-of-view object
    var fieldOfView = new FieldOfView(chess, config);\n
"},{"location":"board-fieldofview/#create-instance","title":"Create instance","text":"
var fieldOfView = scene.rexBoard.add.fieldOfView(chess, {\n// face: 0,\n// cone: undefined,\n// coneMode: 0,\n// perspective: false,\n\n// ** pre-test **\n// occupiedTest: false,\n// blockerTest: false,\n// preTestCallback: undefined,\n// preTestCallbackScope: undefined,\n\n// ** cost **\n// costCallback: undefined,\n// costCallbackScope: undefined,\n// cost: undefined,   // constant cost\n\n// debug: {\n//     graphics: undefined,\n//     visibleLineColor: 0x00ff00,\n//     invisibleLineColor: 0xff0000,\n//     log: false,\n// }\n})\n
  • face : Face of chess.
    • 0 ~ 3 : Quad grid.
    • 0 ~ 5 : Hexagon grid.
  • cone : View of cone. Tile position or chess which not in view of cone will be invisible.
    • undefined : Ignore this feature
  • coneMode : Unit of cone , in direction or angle.
    • 'direction', or 0 : Cone in directions. For example, visible directions are between (0 - 2/2) to (0 + 2/2) if set
      face : 0,\ncone : 2,\nconeMode: 0\n
    • 'angle', or 1 : Cone in angle. For example, visible angle is between (0 - 120/2) to (0 + 120/2) if set
      face : 0,\ncone : 120,\nconeMode: 1\n
  • perspective :
    • false : Test visible until blocked tiles. Default behavior.
    • true : Test visible until out-of-board. Will test cross any blocked (invisible) tile.
  • Pre-test : Test tiles on visible path.
    • occupiedTest : Set true to test if target tile position is occupied or not.
    • blockerTest : Set true to test blocker property.
    • preTestCallback, preTestCallbackScope : Custom pre-test function, return false to discard cost function.
      function(tileXYArray, visiblePoints, fieldOfView) {\n// return false;\n}\n
      • tileXYArray[0] is current tileXY position of chess.
  • Cost function of each tile on visible path
    • cost : A constant cost for each non-blocked tile
    • costCallback, costCallbackScope : Get cost via callback
      function(curTile, fieldOfView, tileXYArray) {\nreturn cost;\n}\n
      • Cost of blocker : fieldOfView.BLOCKER.
      • curTile : Currest testing tileXY.
      • tileXYArray : A read only tileXY array of sight path.
  • debug :
    • debug.graphics : A graphics object for showing debug messages.
    • debug.visibleLineColor : Color of visible line. Set undefined to not draw any line.
    • debug.invisibleLineColor : Color of invisible line. Set undefined to not draw any line.

Note

Blocker is visible, but tiles behind blocker are invisible.

"},{"location":"board-fieldofview/#set-pre-test-function","title":"Set pre-test function","text":"
fieldOfView.setPreTestFunction(callback, scope);\n
  • callback
    var callback = function(tileXYArray, visiblePoints, fieldOfView) {\nreturn false;\n}\n
    • tileXYArray[0] is current tileXY position of chess.
"},{"location":"board-fieldofview/#set-cost-function","title":"Set cost function","text":"
  • Constant cost for each non-blocked tile
    fieldOfView.setCostFunction(cost);\n
  • Get cost via callback
    fieldOfView.setCostFunction(callback, scope);\n
    • callback
      var callback = function(curTile, fieldOfView, tileXYArray) {\nreturn cost;\n}\n
      • Cost of blocker : fieldOfView.BLOCKER
      • curTile : Currest testing tileXY.
      • tileXYArray : A read only tileXY array of sight path.
"},{"location":"board-fieldofview/#is-tilexychess-visible","title":"Is tileXY/chess visible","text":"
var isVisible = fieldOfView.isInLOS(chess);\n// var isVisible = fieldOfView.isInLOS(chess, visiblePoints);\n// var isVisible = fieldOfView.isInLOS(chess, visiblePoints, originTileXY);\n
  • chess : Chess object or tileXY
  • visiblePoints
    • fieldOfView.INFINITY (undefined) : Infinity visible points. Default value.
  • originTileXY : Put chess at this tileXY position for visible testing temporary.
    • undefined : Use current tileXY position for visible testing.
"},{"location":"board-fieldofview/#get-tilexy-array-in-field-of-view","title":"Get tileXY array in field of view","text":"
var tileXYArray = fieldOfView.findFOV();\n// var tileXYArray = fieldOfView.findFOV(visiblePoints);\n// var tileXYArray = fieldOfView.findFOV(visiblePoints, originTileXY);\n// var out = fieldOfView.findFOV(visiblePoints, out);\n// var out = fieldOfView.findFOV(visiblePoints, originTileXY, out);\n
  • visiblePoints
    • fieldOfView.INFINITY (undefined) : Infinity visible points. Default value.
  • out : Returned tileXY array.
  • originTileXY : Put chess at this tileXY position for visible testing temporary.
    • undefined : Use current tileXY position for visible testing.
"},{"location":"board-fieldofview/#filter-visible-tilexy-array","title":"Filter visible tileXY array","text":"
  • Filter visible tileXY array
    var out = fieldOfView.LOS(chessArray);\n// var out = fieldOfView.LOS(chessArray, originTileXY);\n// var out = fieldOfView.LOS(chessArray, out);\n// var out = fieldOfView.LOS(chessArray, originTileXY, out);\n
    • chessArray : Array of chess object or tileXY
    • out : Array of visible chess object or tileXY
    • originTileXY : Put chess at this tileXY position for visible testing temporary.
      • undefined : Use current tileXY position for visible testing.
  • Filter visible tileXY array with visible points
    var out = fieldOfView.LOS(chessArray, visiblePoints);\n// var out = fieldOfView.LOS(chessArray, visiblePoints, originTileXY);\n// var out = fieldOfView.LOS(chessArray, visiblePoints, out);\n// var out = fieldOfView.LOS(chessArray, visiblePoints, originTileXY, out);\n
    • chessArray : Array of chess object or tileXY
    • out : Array of visible chess object or tileXY
    • originTileXY : Put chess at this tileXY position for visible testing temporary.
      • undefined : Use current tileXY position for visible testing.
"},{"location":"board-fieldofview/#face","title":"Face","text":"

Face direction

  • Get
    var face = fieldOfView.face;\n
  • Set
    fieldOfView.setFace(direction);\n
    or
    fieldOfView.face = direction;\n// fieldOfView.face ++;\n
  • face :
    • 0 ~ 3 : Quad grid.
    • 0 ~ 5 : Hexagon grid.
"},{"location":"board-fieldofview/#debug","title":"Debug","text":"
  • Clear debug graphics
    fieldOfView.clearDebugGraphics();\n
  • Set color of lines
    fieldOfView.setDebugLineColor(visibleLineColor, invisibleLineColor);\n
    • visibleLineColor, invisibleLineColor : Set undefined to not draw any line.
"},{"location":"board-hexagongrid/","title":"Hexagon","text":""},{"location":"board-hexagongrid/#introduction","title":"Introduction","text":"

Hexagon grid object of Board system.

  • Author: Rex
  • Grid object of board
"},{"location":"board-hexagongrid/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-hexagongrid/#create-instance","title":"Create instance","text":"
var grid = scene.rexBoard.add.hexagonGrid({\nx: 0,\ny: 0,\ncellWidth: 0,\ncellHeight: 0,\n// size: undefined,\nstaggeraxis: 1,\nstaggerindex: 1\n});\n

or

// import { HexagonGrid } from 'phaser3-rex-plugins/plugins/board-components.js';\nvar grid = new HexagonGrid(config);\n
  • x, y : World position of origin tile (i.e. tileX = 0, tileY = 0)
  • cellWidth : The width of the cell, in pixels.
  • cellHeight : The height of the cell, in pixels.
  • size : Distance between center to each corner. Get cellWidth and cellHeight from size if this parameter is not undefined.
  • staggeraxis
    • 0, or y
    • 1, or x
  • staggerindex
    • 0, or even
    • 1, or odd
"},{"location":"board-hexagongrid/#world-position-of-tile-0-0","title":"World position of tile (0, 0)","text":"
  • Get
    var worldX = grid.x;\nvar worldY = grid.y;\n
  • Set
    grid.setOriginPosition(worldX, worldY);\n
    or
    grid.x = worldX;\ngrid.y = worldY;\n
"},{"location":"board-hexagongrid/#cell-size","title":"Cell size","text":"
  • Get
    var width = grid.width;\nvar height = grid.height;\n
  • Set
    grid.setCellSize(width, height);\n
    or
    grid.width = width;\ngrid.height = height;\n
    or
    grid.setCellRadius(size);\n
    • size : Distance between center to each corner.
"},{"location":"board-hexagongrid/#grid-type","title":"Grid type","text":"
  • Get
    var staggeraxis = grid.staggeraxis;\nvar staggerindex = grid.staggerindex;\n
  • Set
    grid.setType(staggeraxis, staggerindex);\n
    • staggeraxis
      • 0, or y
      • 1, or x
    • staggerindex
      • 0, or even
      • 1, or odd
"},{"location":"board-hexagongrid/#get-world-position","title":"Get world position","text":"
var worldXY = grid.getWorldXY(tileX, tileY);  // worldXY: {x, y}\n// var out = grid.getWorldXY(tileX, tileY, out);\n
"},{"location":"board-hexagongrid/#get-tile-position","title":"Get tile position","text":"
var tileXY = grid.getTileXY(worldX, worldY);  // tileXY: {x, y}\n// var out = grid.getTileXY(worldX, worldY, out);\n
"},{"location":"board-hexagongrid/#directions","title":"Directions","text":"
  • staggeraxis = 0/y
    • 0 : Down-right
    • 1 : Down
    • 2 : Down-left
    • 3 : Up-left
    • 4 : Up
    • 5 : Up-right
  • staggeraxis = 1/x
    • 0 : Right
    • 1 : Down-right
    • 2 : Down-left
    • 3 : Left
    • 4 : Up-left
    • 5 : Up-right
"},{"location":"board-hexagonmap/","title":"Hexagon map","text":""},{"location":"board-hexagonmap/#introduction","title":"Introduction","text":"

Create tile positions in hexagon/triangle/parallelogram geometry in hexagon grid.

  • Author: Rex
  • Help method of board
"},{"location":"board-hexagonmap/#live-demos","title":"Live demos","text":"
  • Hexagon
"},{"location":"board-hexagonmap/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-hexagonmap/#install-plugin","title":"Install plugin","text":""},{"location":"board-hexagonmap/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Create tile positions
    var tileXYArray = scene.rexBoard.add.hexagonMap.hexagon(board, radius);\nvar tileXYArray = scene.rexBoard.add.hexagonMap.parallelogram(board, type, width, height);\nvar tileXYArray = scene.rexBoard.add.hexagonMap.triangle(board, type, height);\n
"},{"location":"board-hexagonmap/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create tile positions
    var tileXYArray = scene.rexBoard.add.hexagonMap.hexagon(board, radius);\nvar tileXYArray = scene.rexBoard.add.hexagonMap.parallelogram(board, type, width, height);\nvar tileXYArray = scene.rexBoard.add.hexagonMap.triangle(board, type, height);\n
"},{"location":"board-hexagonmap/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { HexagonMap } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Create tile positions
    var tileXYArray = HexagonMap.hexagon(board, radius);\nvar tileXYArray = HexagonMap.parallelogram(board, type, width, height);\nvar tileXYArray = HexagonMap.triangle(board, type, height);\n
"},{"location":"board-hexagonmap/#create-tile-positions","title":"Create tile positions","text":""},{"location":"board-hexagonmap/#hexagon","title":"Hexagon","text":"
var tileXYArray = scene.rexBoard.hexagonMap.hexagon(board, radius);\n// var out = scene.rexBoard.hexagonMap.hexagon(board, radius, out);\n
  • tileXYArray : An array of tile position {x, y}.
  • board : Board object.
  • radius : Radius in tile count.
staggeraxis y x"},{"location":"board-hexagonmap/#parallelogram","title":"Parallelogram","text":"
var tileXYArray = scene.rexBoard.hexagonMap.parallelogram(board, type, width, height);\n// var out = scene.rexBoard.hexagonMap.parallelogram(board, type, width, height, out);\n
  • tileXYArray : An array of tile position {x, y}.
  • board : Board object.
  • width, height : Size of parallelogram
type\\staggeraxis y x 0 1 2"},{"location":"board-hexagonmap/#triangle","title":"Triangle","text":"
var tileXYArray = scene.rexBoard.hexagonMap.triangle(board, type, height);\n// var out = scene.rexBoard.hexagonMap.triangle(board, type, height, out);\n
  • tileXYArray : An array of tile position {x, y}.
  • board : Board object.
  • height : Size of Triangle
type\\staggeraxis y x 0 1"},{"location":"board-hexagonmap/#retrieve-tile-positions","title":"Retrieve tile positions","text":"
  1. Offset all of tile positions to (0, 0), and set board size to fit these tile positions.
    var tileXYArray = board.fit(tileXYArray);\n
  2. Retrieve tile positions
    var tileXY;\nfor(var i = 0, cnt = tileXYArray.length; i < cnt; i++) {\ntileXY = tileXYArray[i];\n// ...\n}\n
"},{"location":"board-image/","title":"Image","text":""},{"location":"board-image/#introduction","title":"Introduction","text":"

Image chess object.

  • Author: Rex
  • Chess Game object of Board system
"},{"location":"board-image/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-image/#install-plugin","title":"Install plugin","text":""},{"location":"board-image/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add chess object
    var chess = scene.rexBoard.add.image(board, tileX, tileY, tileZ, key, frame);\n
"},{"location":"board-image/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add chess object
    var chess = scene.rexBoard.add.image(board, tileX, tileY, tileZ, key, frame);\n
"},{"location":"board-image/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Image } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add chess object
    var chess = new Image(board, tileX, tileY, tileZ, key, frame);\nscene.add.existing(chess);\n
"},{"location":"board-image/#add-chess-object","title":"Add chess object","text":"
  • Create chess object and add to board
    var chess = scene.rexBoard.add.image(board, tileX, tileY, tileZ, key, frame);\n
    • board : Board object
    • tileX, tileY, tileZ : Tile position
    • key, frame : Frame of this image chess object
  • Create chess object but not add to board
    var chess = scene.rexBoard.add.image(board, x, y, undefined, key, frame, false);\n
    • board : Board object
    • x, y : World position
    • key, frame : Frame of this image chess object
"},{"location":"board-image/#other-properties","title":"Other properties","text":"

See Image game object, game object

"},{"location":"board-match/","title":"Match","text":""},{"location":"board-match/#introduction","title":"Introduction","text":"

Get matched chess in lines, or neighbors grouping.

  • Author: Rex
  • Application of Board system
"},{"location":"board-match/#live-demos","title":"Live demos","text":"
  • Match line
  • Match neighbors
"},{"location":"board-match/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-match/#install-plugin","title":"Install plugin","text":""},{"location":"board-match/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add match object
    var match = scene.rexBoard.add.match(config);\n
"},{"location":"board-match/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add match object
    var match = scene.rexBoard.add.match(config);\n
"},{"location":"board-match/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Match } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add match object
    var match = new Match(config);\n
"},{"location":"board-match/#add-match-object","title":"Add match object","text":"
var match = scene.rexBoard.add.match({\nboard: board,\n// wildcard: undefined\n// dirMask: undefined\n});\n
  • board : A board object
  • wildcard : A string or a number
  • dirMask : Enable/Disable matching at directions, all directions are enbale by default.
    • Quad grid, 4 directions
      {\n0: true,  // set false to disable left/right matching\n1: true   // set false to disable up/down matching\n}\n
    • Quad grid, 8 directions
      {\n0: true,  // set false to disable left/right matching\n1: true,  // set false to disable up/down matching\n4: true,  // set false to disable left-down/right-up matching\n5: true   // set false to disable right-down/left-up matching\n}\n
    • Hexagon grid
      {\n0: true,\n1: true,\n3: true\n}\n
"},{"location":"board-match/#custom-class","title":"Custom class","text":"
  • Define class
    class MyMatch extends RexPlugins.Board.Match {\nconstructor(config) {\nsuper(config);\n// ...\n}\n// ...\n}\n
  • Create instance
    var match = new MyMatch(config);\n
"},{"location":"board-match/#set-board","title":"Set board","text":"

Board object could be assigned later.

match.setBoard(board);\n
"},{"location":"board-match/#update-symbols","title":"Update symbols","text":"

Each tile position (tileX, tileY) has a symbol.

"},{"location":"board-match/#update-all-symbols-in-board","title":"Update all symbols in board","text":"
match.refreshSymbols(function(tileXY, board) {\n// var chess = board.tileXYZToChess(tileXY.x, tileXY.y, 0);\n// if (chess == null) { return null; }\nreturn symbol;\n}, scope);\n
  • tileXY : Tile position {x, y}
  • board : Board object
  • symbol : A string or a number
    • null : No symbol
"},{"location":"board-match/#updata-a-symbol","title":"Updata a symbol","text":"
match.setSymbol(tileX, tileY, symbol);\n
"},{"location":"board-match/#get-symbol","title":"Get symbol","text":"
var symbol = match.getSymbol(tileX, tileY);\n
"},{"location":"board-match/#for-each-symbol-cahce","title":"For each symbol cahce","text":"
match.forEach(function(tileXY, symbol, board) {\n// return true; // Break for each loop\n}, scope)\n
  • tileXY : Tile position {x, y}
  • symbol : A string or a number
    • null : No symbol
  • board : Board object
"},{"location":"board-match/#wildcard-symbol","title":"Wildcard symbol","text":"
  • Set
    match.setWildcard(symbol);\n
    or
    match.wildcard = symbol;\n
  • Get
    var wildcard = match.wildcard;\n
"},{"location":"board-match/#directions-mask","title":"Directions mask","text":"

Enable/Disable matching at directions, all directions are enbale by default.

match.setDirMask(dir, value);\n
  • dir :
    • Quad grid, 4 directions : 0, 1
    • Quad grid, 8 directions : 0, 1, 4, 5
    • Hexagon grid : 0, 1, 2
  • value : true or false
"},{"location":"board-match/#line-grouping","title":"Line grouping","text":""},{"location":"board-match/#match-n","title":"Match-N","text":"
match.match(n, function (result, board) {\n// var chess = board.tileXYArrayToChess(result.tileXY, 0);\n// GroupCall(chess, function (chess) { chess.setScale(0.8); });\n\n// return true; // Break for each loop\n}, scope);\n
  • n : A number, to get matched chess with n equal symbols
  • result : A group of chess
    {\ntileXY: [],\ndirection: 0\npattern: symbol\n}\n
    • tileXY : An array of tile positions {x, y}
    • direction : Direction of this chess group
      • 0, 1, for quad grid with 4 directions
      • 0, 1, 4, 5, for quad grid with 8 directions
      • 0, 1, 2, for hexagon grid
    • pattern : Matched symbol
  • board : Board object
"},{"location":"board-match/#any-match-n","title":"Any match-N","text":"
var hasAnyMatchN = match.anyMatch(n);\n
"},{"location":"board-match/#match-pattern","title":"Match pattern","text":"
match.match(pattern, function (result, board) {\n// var chess = board.tileXYArrayToChess(result.tileXY, 0);\n// GroupCall(chess, function (chess) { chess.setScale(0.8); });\n}, scope);\n
  • pattern : A list of symbols
"},{"location":"board-match/#any-match-pattern","title":"Any match pattern","text":"
var hasAnyMatchN = match.anyMatch(pattern);\n
"},{"location":"board-match/#neighbors-grouping","title":"Neighbors grouping","text":"
  • Group by neighbors with the same symbol
    tileXYArray = match.group(startTileX, startTileY);\n// out = match.group(startTileX, startTileY, out);\n
    • startTileX, startTileY : Tile position of grouping, to group neighbors with the same symbol. Can't start from null, undefined or wildcard symbol.
"},{"location":"board-miniboard/","title":"Mini board","text":""},{"location":"board-miniboard/#introduction","title":"Introduction","text":"

Chess Container, to rotate/mirror/drag chess together.

  • Author: Rex
  • Container Game object of chess group
"},{"location":"board-miniboard/#live-demos","title":"Live demos","text":"
  • Group 4
  • Drag & drop, mirror, rotate
"},{"location":"board-miniboard/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-miniboard/#install-plugin","title":"Install plugin","text":""},{"location":"board-miniboard/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add container
    var miniBoard = scene.rexBoard.add.miniBoard(x, y, config);\n
"},{"location":"board-miniboard/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add container
    var miniBoard = scene.rexBoard.add.miniBoard(x, y, config);\n
"},{"location":"board-miniboard/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { MiniBoard } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add match object
    var miniBoard = new MiniBoard(scene, x, y, config);\n
"},{"location":"board-miniboard/#add-container","title":"Add Container","text":"
var miniBoard = scene.rexBoard.add.miniBoard(x, y, {\ngrid: grid,\ndraggable: undefined,\n});\n
  • grid : Create board object first, then get grid object via board.grid.
    • gridType :
      • 'quadGrid' : Quad grid
      • 'hexagonGrid' : hexagon grid
  • draggable : Set true to enable dragging events
"},{"location":"board-miniboard/#add-chess","title":"Add chess","text":"
miniBoard.addChess(gameObject, tileX, tileY, tileZ);\n
  • chess : A game object.
  • tileX , tileY , tileZ : Tile position.
    • tileX , tileY : Number.
    • tileZ : Number or string.

Chess and tile position

  • Any chess has a (tileX, tileY, tileZ) index
  • Any (tileX, tileY, tileZ) index contains only 1 chess.
  • (tileX, tileY) could have more then 1 chess with different tileZ index.
  • tileZ is not equal to depth.

These world properties of chess will be changed with container.

  • Position/Angle/Scale
  • Visible
  • Alpha
  • Scroll factor
  • Mask
"},{"location":"board-miniboard/#remove-chess","title":"Remove chess","text":"
  • Remove chess object from board
    miniBoard.removeChess(chess, null, null, null, destroy);\n
    • chess : A game object
    • destroy : Set true to desrtoy chess object.
  • Remove chess at (tileX, tileY, tileZ) from board
    miniBoard.removeChess(null, tileX, tileY, tileZ, destroy);\n
    • tileX, tileY, tileZ : Tile position
    • destroy : Set true to desrtoy chess object.
  • Remove all chess
    miniBoard.removeAllChess(destroy);\n
    • destroy : Set true to desrtoy chess object.
"},{"location":"board-miniboard/#set-origin","title":"Set origin","text":"
  • Set origin tileXY by offset tileXY of all chess.
    miniBoard.setOrigin(origin);\n// miniBoard.setOrigin(originX, originY);\n
    • originX, originY: 0~1.
      • 0 : Left/top.
      • 0.5 : Center.
      • 1 : Right/bottom.
  • Set origin tileXY to center by offset tileXY of all chess.
    miniBoard.setOrigin();\n// miniBoard.setOrigin('center');\n
  • Set origin tileXY to top-left.
    miniBoard.setOrigin('top-left');\n
"},{"location":"board-miniboard/#main-board","title":"Main board","text":"

Put chess to a main-board (Board object) with the same tile position in mini-board, or pull chess out from main-board.

"},{"location":"board-miniboard/#put-on-main-board","title":"Put on main-board","text":"
miniBoard.putOnMainBoard(mainBoard, tileX, tileY);\n// miniBoard.putOnMainBoard(mainBoard, tileX, tileY, align);\n
  • mainBoard : Board object.
  • tileX, tileY : Tile position to put on.
  • align : Set true to align world position of each chess Game object to grid of main-board. Default is true.

or

miniBoard.putOnMainBoard(mainBoard);\n

To put this mini-board to nearest grid of main-board.

"},{"location":"board-miniboard/#pull-out-from-main-board","title":"Pull out from main-board","text":"
miniBoard.pullOutFromMainBoard();\n

Remove all chess from main-board.

"},{"location":"board-miniboard/#put-back-to-previous-main-board","title":"Put back to previous main-board","text":"
miniBoard.putBack();\n

Previous main-board and tile position will be remembered for putting back.

"},{"location":"board-miniboard/#is-overlapping-to-main-board","title":"Is overlapping to main-board","text":"

Return true if any chess is overlapping to main-board.

miniBoard.isOverlapping(mainBoard);\n

or

miniBoard.isOverlapping(mainBoard, tileZ);\n
"},{"location":"board-miniboard/#align-world-position-to-grid-of-main-board","title":"Align world position to grid of main-board","text":"
miniBoard.alignToMainBoard(mainBoard, tileX, tileY);\n
  • mainBoard : Board object
  • tileX, tileY : Tile position on main-board

or

miniBoard.alignToMainBoard(mainBoard);\n

to align this mini-board to nearest grid of main-board.

"},{"location":"board-miniboard/#get-current-main-board","title":"Get current main-board","text":"
var board = miniBoard.mainBoard;\n
  • board : Board object

Return null if this mini-board is not at any main-board.

"},{"location":"board-miniboard/#rotate","title":"Rotate","text":""},{"location":"board-miniboard/#can-rotate","title":"Can rotate","text":"
miniBoard.canRotate(n);\n
  • n : Rotate to direction current direction + n

or

miniBoard.canRotateTo(direction);\n
  • direction : Rotate to direction
    • 0 ~ 3 : Quad grid.
    • 0 ~ 5 : Hexagon grid.

Always return true if this mini-board is not on a main-board.

"},{"location":"board-miniboard/#rotate_1","title":"Rotate","text":"
miniBoard.rotate(n);\n
  • n : Rotate direction to current direction + n

or

miniBoard.rotateTo(direction);\n
  • direction : Rotate to direction
    • 0 ~ 3 : Quad grid.
    • 0 ~ 5 : Hexagon grid.

Return true if this rotating request is accepted.

var isSuccess = miniBoard.lastTransferResult;\n
"},{"location":"board-miniboard/#mirror","title":"Mirror","text":""},{"location":"board-miniboard/#can-mirror","title":"Can mirror","text":"
miniBoard.canMirror(mode);\n
  • mode :
    • 0, or 'x' : Set tileX to -tileX
    • 1, or 'y' : Set tileY to -tileY
    • 3, or 'x&y' : Set tileX to -tileX, and tileY to -tileY

Always return true if this mini-board is not on a main-board.

"},{"location":"board-miniboard/#mirror_1","title":"Mirror","text":"
miniBoard.mirror(mode);\n
  • mode :
    • 0, or 'x' : Set tileX to -tileX
    • 1, or 'y' : Set tileY to -tileY
    • 3, or 'x&y' : Set tileX to -tileX, and tileY to -tileY

Return true if this mirroring request is accepted.

var isSuccess = miniBoard.lastTransferResult;\n
"},{"location":"board-miniboard/#touch-events","title":"Touch events","text":""},{"location":"board-miniboard/#set-interactive","title":"Set interactive","text":"
  • Enable
    miniBoard.setInteractive();\n
  • Disable
    miniBoard.setInteractive(false);\n
"},{"location":"board-miniboard/#set-drag-able","title":"Set drag-able","text":"
  • Enable
    miniBoard.setDragEnable();\n
  • Disable
    miniBoard.setDragEnable(false);\n
"},{"location":"board-miniboard/#touch-event","title":"Touch event","text":""},{"location":"board-miniboard/#pointer-down","title":"Pointer down","text":"
  • Pointer down at any chess
    miniBoard.on('pointerdown', function(pointer, miniBoard) {\n})\n
  • Pointer down at a chess
    miniBoard.on('gameobjectdown', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('miniboard.pointerdown', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board-miniboard/#pointer-up","title":"Pointer up","text":"
  • Pointer up
    miniBoard.on('pointerup', function(pointer, miniBoard) {\n})\n
  • Pointer up at a chess
    miniBoard.on('gameobjectup', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('miniboard.pointerup', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board-miniboard/#pointer-move","title":"Pointer move","text":"
  • Pointer move
    miniBoard.on('pointermove', function(pointer, miniBoard) {\n})\n
  • Pointer move to another chess
    miniBoard.on('gameobjectmove', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('miniboard.pointermove', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board-miniboard/#drag-events","title":"Drag events","text":"
  • Drag-start
    miniBoard.on('dragstart', function(pointer, dragX, dragY){\n/*\n    miniBoard.pullOutFromMainBoard();\n    */\n}, scope);\n
    Pull out from main-board for dragging.
  • Dragging
    miniBoard.on('drag', function(pointer, dragX, dragY){\n/*\n    miniBoard.setPosition(dragX, dragY);\n    if (miniBoard.isOverlapping(mainBoard)) {\n        miniBoard.alignToMainBoard(mainBoard);\n    }\n    */\n}, scope);\n
    Set world position of mini-board via (dragX, dragY), align to nearest grid of main-board if overlapping with that main-board.
  • Drag-end
    miniBoard.on('dragend', function(pointer, dragX, dragY){\n/*\n    miniBoard.putOnMainBoard(mainBoard);\n    if (miniBoard.mainBoard) {\n    }\n    */\n}, scope);\n
    Put chess on main-board at nearest grid.
"},{"location":"board-monopoly/","title":"Monopoly","text":""},{"location":"board-monopoly/#introduction","title":"Introduction","text":"

Move through path tiles, used in monopoly-like application, chess behavior of Board system.

  • Author: Rex
  • Behavior of chess
"},{"location":"board-monopoly/#live-demos","title":"Live demos","text":"
  • Monopoly
"},{"location":"board-monopoly/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-monopoly/#install-plugin","title":"Install plugin","text":""},{"location":"board-monopoly/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add monopoly behavior
    var monopoly = scene.rexBoard.add.monopoly(chess, config);\n
"},{"location":"board-monopoly/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add monopoly behavior
    var monopoly = scene.rexBoard.add.monopoly(chess, config);\n
"},{"location":"board-monopoly/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Monopoly } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add monopoly behavior
    var board = new Monopoly(chess, config);\n
"},{"location":"board-monopoly/#create-instance","title":"Create instance","text":"
var monopoly = scene.rexBoard.add.monopoly(chess, {\nface: 0,\n\n// ** cost **\n// pathTileZ: 0,\n// cost: 1,   // constant cost\n// costCallback: undefined,\n// costCallbackScope: undefined\n})\n
  • face : Moving direction.
    • 0 ~ 3 : Quad grid in 4 directions mode.
    • 0 ~ 7 : Quad grid in 8 directions mode.
    • 0 ~ 5 : Hexagon grid.
  • Cost function
    • pathTileZ : TileZ of path tiles.
    • cost : A constant cost for each non-blocked tile
    • costCallback, costCallbackScope : Get cost via callback
      function(curTileXY, preTileXY, monopoly) {\nreturn cost;\n}\n
"},{"location":"board-monopoly/#cost-function","title":"Cost function","text":"
var callback = function(curTileXY, preTileXY, monopoly) {\nreturn cost;\n}\n
  • cost : Number cost.
  • curTileXY, preTileXY : TileXY position {x, y}. Cost of moving from preTileXY to curTileXY.
  • monopoly : Path finder object.
    • monopoly.board : Board object
    • monopoly.gameObject : Chess game object.
    • monopoly.STOP, or -1 : Cost of stop. Return this value means chess will stop at curTileXY.
    • monopoly.BLOCKER, or null : Cost of blocker. Return this value means that chess can not move to curTileXY.
"},{"location":"board-monopoly/#set-cost-function","title":"Set cost function","text":"
  • Constant cost for each non-blocked tile
    monopoly.setCostFunction(cost);\n
  • Get cost via callback
    monopoly.setCostFunction(callback, scope);\n
"},{"location":"board-monopoly/#set-face-direction","title":"Set face direction","text":"
monopoly.setFace(direction);\n
  • direction :
    • 0 ~ 3 : Quad grid in 4 directions mode.
    • 0 ~ 7 : Quad grid in 8 directions mode.
    • 0 ~ 5 : Hexagon grid.

Moving direction

Get path toward this face direction.

"},{"location":"board-monopoly/#get-path","title":"Get path","text":"
var tileXYArray = monopoly.getPath(movingPoints);\n// var out = monopoly.getPath(movingPoints, out);\n
  • tileXYArray : Moving path in an array of tile positions {x,y}
    • Uses moveTo behavior to move chess along path.
"},{"location":"board-moveto/","title":"Move to","text":""},{"location":"board-moveto/#introduction","title":"Introduction","text":"

Move chess towards target position with a steady speed, chess behavior of Board system.

  • Author: Rex
  • Behavior of chess
"},{"location":"board-moveto/#live-demos","title":"Live demos","text":"
  • Push
  • Follow chess
"},{"location":"board-moveto/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-moveto/#install-plugin","title":"Install plugin","text":""},{"location":"board-moveto/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add move-to behavior
    var moveTo = scene.rexBoard.add.moveTo(chess, config);\n
"},{"location":"board-moveto/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add move-to behavior
    var moveTo = scene.rexBoard.add.moveTo(chess, config);\n
"},{"location":"board-moveto/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { MoveTo } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add move-to behavior
    var moveTo = new MoveTo(chess, config);\n
"},{"location":"board-moveto/#create-instance","title":"Create instance","text":"
var moveTo = scene.rexBoard.add.moveTo(chess, {\n// speed: 400,\n\n// rotateToTarget: false,\n\n// occupiedTest: false,\n// blockerTest: false,\n// moveableTest: undefined,\n// moveableTestScope: undefined,\n\n// sneak: false,\n})\n
  • speed : moving speed, pixels in second.
  • rotateToTarget : Set true to change angle towards path.
  • occupiedTest : Set true to test if target tile position is occupied or not, in moveable testing.
  • blockerTest : Set true to test blocker property in moveable testing.
  • moveableTest, moveableTestScope : Custom moveable test callback
    function(fromTileXYZ, toTileXYZ, direction, board) {\nreturn true;\n}\n
    • fromTileXYZ, toTileXYZ : Move chess from tileXYZ {x, y, z}, to tileXYZ {x, y, z}
    • direction :
      • 0 ~ 3 : Quad grid in 4 directions mode.
      • 0 ~ 7 : Quad grid in 8 directions mode.
      • 0 ~ 5 : Hexagon grid.
    • board : Board object.
  • sneak : Set true to allow changing tileZ when target tile position is occupied. Changing back when target tile position is not occupied.
    • occupiedTest will be ignored when sneak is true.
"},{"location":"board-moveto/#move-to-destination-tile","title":"Move to destination tile","text":"
moveTo.moveTo(tileX, tileY);\n// moveTo.moveTo(tileXY);\n
  • tileXY : Tile position {x,y}
"},{"location":"board-moveto/#move-to-neighbor-tile","title":"Move to neighbor tile","text":"
moveTo.moveToward(direction);\n
  • direction :
    • 0 ~ 3 : Quad grid in 4 directions mode.
    • 0 ~ 7 : Quad grid in 8 directions mode.
    • 0 ~ 5 : Hexagon grid.
"},{"location":"board-moveto/#move-to-random-neighbor-tile","title":"Move to random neighbor tile","text":"
moveTo.moveToRandomNeighbor();\n
"},{"location":"board-moveto/#move-away-or-move-closer","title":"Move away or move closer","text":"
  • Move away from a tile position
    moveTo.moveAway(tileX, tileY);\n
    or
    moveTo.moveAway(tileXY);\n
    • tileXY : Tile position {x,y}
  • Move closer to a tile position
    moveTo.moveCloser(tileX, tileY);\n
    or
    moveTo.moveCloser(tileXY);\n
    • tileXY : Tile position {x,y}
"},{"location":"board-moveto/#can-move-to-tile","title":"Can move to tile","text":"
var canMoveTo = moveTo.canMoveTo(tileX, tileY);\n

Return true if chess can move to (tileX, tileY)

"},{"location":"board-moveto/#last-move-result","title":"Last move result","text":"
var lastMoveResult = moveTo.lastMoveResult;\n

Return true if chess is moved by moveTo.moveTo(), moveTo.moveToward(), or moveTo.moveToRandomNeighbor()

"},{"location":"board-moveto/#destination","title":"Destination","text":"
var destinationTileX = moveTo.destinationTileX;\nvar destinationTileY = moveTo.destinationTileY;\nvar destinationDirection = moveTo.destinationDirection;\n
"},{"location":"board-moveto/#pause-resume-stop-moving","title":"Pause, Resume, stop moving","text":"
moveTo.pause();\nmoveTo.resume();\nmoveTo.stop();\n
"},{"location":"board-moveto/#enable","title":"Enable","text":"
  • Enable/resume (default)
    moveTo.setEnable();\n
    or
    moveTo.enable = true;\n
  • Disable/pause
    moveTo.setEnable(false);\n
    or
    moveTo.enable = false;\n
"},{"location":"board-moveto/#set-speed","title":"Set speed","text":"
moveTo.setSpeed(speed);\n// moveTo.speed = speed;\n
"},{"location":"board-moveto/#set-rotate-to-target","title":"Set rotate-to-target","text":"
moveTo.setRotateToTarget(rotateToTarget);\n
  • rotateToTarget : Set true to change angle towards target
"},{"location":"board-moveto/#events","title":"Events","text":"
  • Try to move on an occupied tile position
    moveTo.on('occupy', function(occupiedChess, gameObject, moveTo){\n// Move away occupiedChess\n});\n
  • On reached target
    moveTo.on('complete', function(gameObject, moveTo){});\n// moveTo.once('complete', function(gameObject, moveTo){});\n
"},{"location":"board-moveto/#status","title":"Status","text":"
  • Is moving
    var isRunning = moveTo.isRunning;\n
"},{"location":"board-overview/","title":"Overview","text":""},{"location":"board-overview/#install-plugin","title":"Install plugin","text":""},{"location":"board-overview/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add board object
    var board = scene.rexBoard.add.board(config);\n
"},{"location":"board-overview/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add board object
    var board = scene.rexBoard.add.board(config);\n
"},{"location":"board-overview/#using-typescript-declaration-file","title":"Using typescript declaration file","text":"
import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\n\nclass Game extends Phaser.Scene {\nrexBoard: BoardPlugin;  // Declare scene property 'rexBoard' as BoardPlugin type\n\ncreate() {\nvar board = this.rexBoard.add.board({\n// ...\n})\n}\n}\n\nvar game = new Phaser.Game({\nscene: Game,\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n});\n
  • 'phaser3-rex-plugins/plugins/board-plugin' : Factories of board components.
  • 'phaser3-rex-plugins/plugins/board-components' : Class of board components.
    import { Board } from 'phaser3-rex-plugins/plugins/board-components';\n

See this example

"},{"location":"board-overview/#list-of-board-plugins","title":"List of board plugins","text":""},{"location":"board-overview/#board","title":"Board","text":"
  • Board
  • Grids
    • Quad grid
    • Hexagon grid
  • Chess
"},{"location":"board-overview/#chess-game-object","title":"Chess game object","text":"
  • Shape game object
  • Image game object
  • Sprite game object
  • Tile texture
"},{"location":"board-overview/#behaviors","title":"Behaviors","text":"
  • Move to
"},{"location":"board-overview/#applications","title":"Applications","text":"
  • Path finder
  • Monopoly
  • Field of view
  • Match
  • Hexagon map
"},{"location":"board-overview/#mini-board","title":"Mini-board","text":"
  • Mini-board
"},{"location":"board-overview/#templates","title":"Templates","text":"
  • Bejeweled
"},{"location":"board-pathfinder/","title":"Path finder","text":""},{"location":"board-pathfinder/#introduction","title":"Introduction","text":"

Find moveable area or moving path, chess behavior of Board system.

  • Author: Rex
  • Application of Board system, or behavior of chess
"},{"location":"board-pathfinder/#live-demos","title":"Live demos","text":"
  • Find area, get path
  • Draw path
  • Energy drain
  • Turning cost
  • Move from high to low
  • Chinese checkers
"},{"location":"board-pathfinder/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-pathfinder/#install-plugin","title":"Install plugin","text":""},{"location":"board-pathfinder/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add path-finder
    var pathFinder = scene.rexBoard.add.pathFinder(config);\n
"},{"location":"board-pathfinder/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add path-finder
    var pathFinder = scene.rexBoard.add.pathFinder(config);\n
"},{"location":"board-pathfinder/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PathFinder } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add path-finder
    var pathFinder = new PathFinder(config);\n
"},{"location":"board-pathfinder/#create-instance","title":"Create instance","text":"
var pathFinder = scene.rexBoard.add.pathFinder({\n// occupiedTest: false,\n// blockerTest: false,\n\n// ** cost **\n// cost: 1,   // constant cost\n// costCallback: undefined,\n// costCallbackScope: undefined,\n// cacheCost: true,\n\n// pathMode: 10,  // A*\n// weight: 10,   // weight for A* searching mode\n// shuffleNeighbors: false,\n})\n
  • occupiedTest : Set true to test if target tile position is occupied or not, in cost function.
  • blockerTest : Set true to test blocker property in cost function.
  • Cost function
    • cost : A constant cost for each non-blocked tile
    • costCallback, costCallbackScope : Get cost via callback
      function(curTile, preTile, pathFinder) {\nreturn cost;\n}\n
      • Board : pathFinder.board
      • Chess game object : pathFinder.gameObject
      • Cost of blocker : pathFinder.BLOCKER
  • pathMode
    • Shortest path
      • 'random', or 0
      • 'diagonal', or 1
      • 'straight', or 2
      • 'line', or 3
    • A* path
      • 'A*', or 10
      • 'A*-random', or 11
      • 'A*-line', or 12
  • weight : Weight parameter for A* searching mode.
  • cacheCost : Set false to get cost every time. It is useful when cost is a function of (current tile, previous tile).
  • shuffleNeighbors : Shuffle neighbors.
"},{"location":"board-pathfinder/#create-behavior","title":"Create behavior","text":"
var pathFinder = scene.rexBoard.add.pathFinder(chess, config);\n
"},{"location":"board-pathfinder/#set-chess","title":"Set chess","text":"
pathFinder.setChess(chess);\n

Note

Don't use this method if pathFinder is a behavior of Chess

"},{"location":"board-pathfinder/#cost-function","title":"Cost function","text":"
var callback = function(curTileXY, preTileXY, pathFinder) {\nreturn cost;\n}\n
  • cost : Number cost.
  • curTileXY, preTileXY : TileXY position {x, y}. Cost of moving from preTileXY to curTileXY.
    • preTileXY.pathCost : Path cost of preTilexY.
    • preTileXY.preNodes : Previous tiles of preTileXY.
  • pathFinder : Path finder object.
    • pathFinder.board : Board object
    • pathFinder.gameObject : Chess game object.
    • pathFinder.BLOCKER : Cost of blocker. Return this value means that chess can not move to curTileXY.
"},{"location":"board-pathfinder/#set-cost-function","title":"Set cost function","text":"
  • Constant cost for each non-blocked tile
    pathFinder.setCostFunction(cost);\n
  • Get cost via callback
    pathFinder.setCostFunction(callback, scope);\n
"},{"location":"board-pathfinder/#set-path-mode","title":"Set path mode","text":"
pathFinder.setPathMode(pathMode)\n
  • pathMode
    • Shortest path
      • 'random', or 0
      • 'diagonal', or 1
      • 'straight', or 2
      • 'line', or 3
    • A* path
      • 'A*', or 10
      • 'A*-random', or 11
      • 'A*-line', or 12
"},{"location":"board-pathfinder/#find-moveable-area","title":"Find moveable area","text":"
var tileXYArray = pathFinder.findArea(movingPoints);\n// var out = pathFinder.findArea(movingPoints, out);\n
  • movingPoints
    • pathFinder.INFINITY (undefined) : Infinity moving points. Default value.
  • tileXYArray : An array of moveable tile positions {x,y,pathCost}
"},{"location":"board-pathfinder/#get-shortest-path-to-a-moveable-tile","title":"Get shortest path to a moveable tile","text":"
var tileXYArray = pathFinder.getPath(endTileXY);\n
  • endTileXY : Tile position of moveable area in last result of pathFinder.findArea()
  • tileXYArray : Moving path in an array of tile positions {x,y,pathCost}
    • Uses moveTo behavior to move chess along path.

Path mode

  • Path info of each tile is calculated during pathFinder.findArea()
"},{"location":"board-pathfinder/#find-moving-path","title":"Find moving path","text":"
var tileXYArray = pathFinder.findPath(endTileXY);\n// var tileXYArray = pathFinder.findPath(endTileXY, movingPoints, isClosest, out);\n
  • endTileXY : Tile position
  • tileXYArray : Moving path in an array of tile positions {x,y,pathCost}
    • Uses moveTo behavior to move chess along path.
  • movingPoints
    • pathFinder.INFINITY (undefined) : Infinity moving points. Default value.
  • isClosest : Set true to get closest path.

Path mode

  • Set pathMode to A* ('A*', 'A*-random', or 'A*-line') to speed up calculating.
"},{"location":"board-pathfinder/#cost-of-tile","title":"Cost of tile","text":"

During or after finding moveable area...

  • Get cost of path from chess to tile
    var pathCost = pathFinder.tileXYToCost(tileX, tileY, true);\n
  • Get cost of tile
    var tileCost = pathFinder.tileXYToCost(tileX, tileY, false);\n
"},{"location":"board-quadgrid/","title":"Quad","text":""},{"location":"board-quadgrid/#introduction","title":"Introduction","text":"

Quad grid object of Board system.

  • Author: Rex
  • Grid object of board
"},{"location":"board-quadgrid/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-quadgrid/#create-instance","title":"Create instance","text":"
var grid = scene.rexBoard.add.quadGrid({\nx: 0,\ny: 0,\ncellWidth: 0,\ncellHeight: 0,\ntype: 0,\n// dir: 4\n});\n

or

// import { QuadGrid } from 'phaser3-rex-plugins/plugins/board-components.js';\nvar grid = new QuadGrid(config);\n
  • x, y : World position of tile (0, 0)
  • cellWidth : The width of the cell, in pixels.
  • cellHeight : The height of the cell, in pixels.
  • type
    • 0, or orthogonal
    • 1, or isometric
  • dir :
    • 4 or '4dir' : Left/Down/Right/Up
    • 8 or '8dir' : Left/Down/Right/Up/Left-down/Down-right/Right-up/Up-left
"},{"location":"board-quadgrid/#world-position-of-tile-0-0","title":"World position of tile (0, 0)","text":"
  • Get
    var worldX = grid.x;\nvar worldY = grid.y;\n
  • Set
    grid.setOriginPosition(worldX, worldY);\n
    or
    grid.x = worldX;\ngrid.y = worldY;\n
"},{"location":"board-quadgrid/#cell-size","title":"Cell size","text":"
  • Get
    var width = grid.width;\nvar height = grid.height;\n
  • Set
    grid.setCellSize(width, height);\n
    or
    grid.width = width;\ngrid.height = height;\n
"},{"location":"board-quadgrid/#grid-type","title":"Grid type","text":"
  • Get
    var mode = grid.mode;\n
  • Set
    grid.setType(mode);\n
    • mode
      • 0, or orthogonal
      • 1, or isometric
"},{"location":"board-quadgrid/#get-world-position","title":"Get world position","text":"
var worldXY = grid.getWorldXY(tileX, tileY);  // worldXY: {x, y}\n// var out = grid.getWorldXY(tileX, tileY, out);\n
"},{"location":"board-quadgrid/#get-tile-position","title":"Get tile position","text":"
var tileXY = grid.getTileXY(worldX, worldY);  // tileXY: {x, y}\n// var out = grid.getTileXY(worldX, worldY, out);\n
"},{"location":"board-quadgrid/#directions","title":"Directions","text":"
  • 0 : Right
  • 1 : Down
  • 2 : Left
  • 3 : Up
  • 4 : Right-down
  • 5 : Left-down
  • 6 : Left-up
  • 7 : Right-up
6|3|7\n-+-+-\n2|A|0\n-+-+-\n5|1|4\n
"},{"location":"board-shape/","title":"Shape","text":""},{"location":"board-shape/#introduction","title":"Introduction","text":"

Grid (polygon) shape chess object.

  • Author: Rex
  • Chess Game object of Board system
"},{"location":"board-shape/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-shape/#install-plugin","title":"Install plugin","text":""},{"location":"board-shape/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add chess object
    var chess = scene.rexBoard.add.shape(board, tileX, tileY, tileZ, fillColor);\n
"},{"location":"board-shape/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add chess object
    var chess = scene.rexBoard.add.shape(board, tileX, tileY, tileZ, fillColor);\n
"},{"location":"board-shape/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Shape } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add chess object
    var chess = new Shape(board, tileX, tileY, tileZ, fillColor);\nscene.add.existing(chess);\n
"},{"location":"board-shape/#add-chess-object","title":"Add chess object","text":"
  • Create chess object and add to board
    var chess = scene.rexBoard.add.shape(board, tileX, tileY, tileZ, fillColor, fillAlpha);\n
    • board : Board object
    • tileX, tileY, tileZ : Tile position
    • fillColor, fillAlpha : Color of this shape chess object
  • Create chess object but not add to board
    var chess = scene.rexBoard.add.shape(board, x, y, undefined, fillColor, fillAlpha, false);\n
    • board : Board object
    • x, y : World position
    • fillColor, fillAlpha : Color of this shape chess object
"},{"location":"board-shape/#set-color","title":"Set color","text":"
  • Fill color
    chess.setFillStyle(color, alpha)\n
  • Stroke color
    chess.setStrokeStyle(lineWidth, color, alpha)\n

No tint methods

Uses shape.setFillStyle(color, alpha) to change color.

"},{"location":"board-shape/#other-properties","title":"Other properties","text":"

See polygon shape game object, game object

"},{"location":"board-sprite/","title":"Sprite","text":""},{"location":"board-sprite/#introduction","title":"Introduction","text":"

Sprite chess object.

  • Author: Rex
  • Chess Game object of Board system
"},{"location":"board-sprite/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-sprite/#install-plugin","title":"Install plugin","text":""},{"location":"board-sprite/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add chess object
    var chess = scene.rexBoard.add.sprite(board, tileX, tileY, tileZ, key, frame);\n
"},{"location":"board-sprite/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add chess object
    var chess = scene.rexBoard.add.sprite(board, tileX, tileY, tileZ, key, frame);\n
"},{"location":"board-sprite/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Sprite } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add chess object
    var chess = new Sprite(board, tileX, tileY, tileZ, key, frame);\nscene.add.existing(chess);\n
"},{"location":"board-sprite/#add-chess-object","title":"Add chess object","text":"
  • Create chess object and add to board
    var chess = scene.rexBoard.add.sprite(board, tileX, tileY, tileZ, key, frame);\n
    • board : Board object
    • tileX, tileY, tileZ : Tile position
    • key, frame : Frame of this sprite chess object
  • Create chess object but not add to board
    var chess = scene.rexBoard.add.sprite(board, x, y, undefined, key, frame, false);\n
    • board : Board object
    • x, y : World position
    • key, frame : Frame of this sprite chess object
"},{"location":"board-sprite/#other-properties","title":"Other properties","text":"

See Sprite game object, game object

"},{"location":"board-texture/","title":"Tile texture","text":""},{"location":"board-texture/#introduction","title":"Introduction","text":"

Create canvas-texture of tile.

  • Author: Rex
  • Help method of board
"},{"location":"board-texture/#live-demos","title":"Live demos","text":"
  • Tile texture
"},{"location":"board-texture/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-texture/#install-plugin","title":"Install plugin","text":""},{"location":"board-texture/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Create tile texture
    scene.rexBoard.createTileTexture(board, key, fillStyle, strokeStyle, lineWidth);\n
"},{"location":"board-texture/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create tile texture
    scene.rexBoard.createTileTexture(board, key, fillStyle, strokeStyle, lineWidth);\n
"},{"location":"board-texture/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { CreateTileTexture } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Create tile texture
    CreateTileTexture(board, key, fillStyle, strokeStyle, lineWidth);\n
"},{"location":"board-texture/#create-tile-texture","title":"Create tile texture","text":""},{"location":"board-texture/#hexagon","title":"Hexagon","text":"
CreateTileTexture(board, key, fillStyle, strokeStyle, lineWidth);\n// CreateTileTexture(board, key, fillStyle, strokeStyle, lineWidth, overlapGrid, lineJoin);\n
  • board : Board object.
  • fillStyle : Fill color of tile texture.
    • undefined : Don't fill tile texture.
  • strokeStyle, lineWidth : Stroke color, stroke line width of tile texture.
    • undefined : Don't stroke tile texture.
  • overlapGrid :
    • true : Overlap grid. i.e. Grid width = lineWidth. Default behavior.
    • false : Don't overlap grid. i.e. Grid width = 2 * lineWidth.
  • lineJoin : Join style of stroke lines. 'round', 'bevel' and 'miter'. Default is 'miter'.
"},{"location":"board-tilemap/","title":"Tilemap","text":""},{"location":"board-tilemap/#introduction","title":"Introduction","text":"

Create board from tilemap

  • Author: Rex
  • Help method of board
"},{"location":"board-tilemap/#live-demos","title":"Live demos","text":"
  • Create board from tilemap
"},{"location":"board-tilemap/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-tilemap/#install-plugin","title":"Install plugin","text":""},{"location":"board-tilemap/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Create board from tilemap
    var board = scene.rexBoard.createBoardFromTilemap(tilemap, layers);\n
"},{"location":"board-tilemap/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create board from tilemap
    var board = scene.rexBoard.createBoardFromTilemap(tilemap, layers);\n
"},{"location":"board-tilemap/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { CreateBoardFromTilemap } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Create board from tilemap
    var board = CreateBoardFromTilemap(tilemap, layers);\n
"},{"location":"board-tilemap/#create-board-from-tilemap","title":"Create board from tilemap","text":"
var board = CreateBoardFromTilemap(tilemap, layers);\n
  • tilemap : Tilemap object
  • layers : Add tiles of layers into board, tileZ will be name of layer (layer.name)
    • undefined : Add tiles of all layers.
    • Array of TilemapLayer game object, or a TilemapLayer game object
    • Array of layers' name, or a name of layer.
  • board : Board object.
"},{"location":"board/","title":"Board","text":""},{"location":"board/#introduction","title":"Introduction","text":"

Core object of Board system.

  • Author: Rex
  • Member of scene
"},{"location":"board/#live-demos","title":"Live demos","text":"
  • Touch events
  • Get tileXY at direction
  • Line to tileXY array
  • Triangle to tileXY array
  • Ellipse to tileXY array
  • Bounds
"},{"location":"board/#usage","title":"Usage","text":"

Sample code

"},{"location":"board/#install-plugin","title":"Install plugin","text":""},{"location":"board/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add board object
    var board = scene.rexBoard.add.board(config);\n
"},{"location":"board/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add board object
    var board = scene.rexBoard.add.board(config);\n
"},{"location":"board/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Board, HexagonGrid, QuadGrid } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add board object
    var board = new Board(scene, {\ngrid: QuadGrid(gridConfig),  // or HexagonGrid(gridConfig)\n// ...\n});\n
"},{"location":"board/#add-board-object","title":"Add board object","text":"
  • Quad board
    var board = scene.rexBoard.add.board({\ngrid: {\ngridType: 'quadGrid',\nx: 0,\ny: 0,\ncellWidth: 0,\ncellHeight: 0,\ntype: 'orthogonal'  // 'orthogonal'|'isometric'\n},\n// width: 0,\n// height: 0,\n// wrap: false,\n// infinity: false,\n});\n
  • Hexagon board
    var board = scene.rexBoard.add.board({\ngrid: {\ngridType: 'hexagonGrid',\nx: 0,\ny: 0,\ncellWidth: 0,\ncellHeight: 0,\nstaggeraxis: 'x',   // 'x'|'y'\nstaggerindex: 'odd' // 'odd'|'even'\n},\n// width: 0,\n// height: 0,\n// wrap: false,\n// infinity: false,\n});\n

Configuration

  • grid :
    • gridType :
      • 'quadGrid' : Quad grid
      • 'hexagonGrid' : hexagon grid
  • width : Board width in tiles
  • height : Board height in tiles
  • wrap : Set true to wrap board bounds. Default value is false.
  • infinity : Infinity board size if set to true. Default value is false.
"},{"location":"board/#custom-class","title":"Custom class","text":"
  • Define class
    class MyBoard extends RexPlugins.Board.Board {\nconstructor(scene) {\nsuper(scene, {\ngrid: {\ngridType: 'quadGrid',\nx: 0,\ny: 0,\ncellWidth: 0,\ncellHeight: 0,\ntype: 'orthogonal'  // 'orthogonal'|'isometric'\n},\nwidth: 0,\nheight: 0\n});\n// ...\n}\n// ...\n}\n
  • Create instance
    var board = new MyBoard(scene);\n
"},{"location":"board/#board-size","title":"Board size","text":"
  • Width : Board width in tiles
    • Get
      var width = board.width;\n
    • Set
      board.setBoardWidth(width);\n
  • Height : Board height in tiles
    • Get
      var height = board.height;\n
    • Set
      board.setBoardHeight(height);\n
"},{"location":"board/#add-chess","title":"Add chess","text":"
board.addChess(chess, tileX, tileY, tileZ, align);\n
  • chess : A game object.
  • tileX , tileY , tileZ : Tile position.
    • tileX , tileY : Number.
    • tileZ : Number or string.
  • align : Set true to align (i.e. set position) chess to grid (tileX, tileY). Default is true.

Chess and tile position

  • Any chess has a (tileX, tileY, tileZ) index
  • Any (tileX, tileY, tileZ) index contains only 1 chess.
  • (tileX, tileY) could have more then 1 chess with different tileZ index.
  • tileZ is not equal to depth.
"},{"location":"board/#kick-out-event","title":"Kick-out event","text":"

Board will fire kickout event when adding chess to an occupied grid.

board.on('kickout', function(chessToAdd, occupiedChess, tileXYZ){\n})\n

chessToAdd kicks out occupiedChess at tile position tileXYZ({x,y,z}).

"},{"location":"board/#remove-chess","title":"Remove chess","text":"
  • Remove chess object from board
    board.removeChess(chess, null, null, null, destroy);\n
    • chess : A game object
    • destroy : Set true to desrtoy chess object.
  • Remove chess at (tileX, tileY, tileZ) from board
    board.removeChess(null, tileX, tileY, tileZ, destroy);\n
    • tileX, tileY, tileZ : Tile position
    • destroy : Set true to desrtoy chess object.
  • Remove all chess
    board.removeAllChess(destroy);\n
    • destroy : Set true to desrtoy chess object.
"},{"location":"board/#move-chess","title":"Move chess","text":"
board.moveChess(chess, toTileX, toTileY, toTileZ, align);\n
  • chess : A game object
  • toTileX, toTileY, toTileZ : Target tile position
  • align : Set true to align (i.e. set position) chess to grid (tileX, tileY). Default is true.

Do nothing if chess is not at this board.

"},{"location":"board/#set-tilez-of-chess","title":"Set tileZ of chess","text":"
board.setChessTileZ(chess, toTileZ, align);\n
  • chess : A game object
  • toTileZ : Target tileZ
  • align : Set true to align (i.e. set position) chess to grid (tileX, tileY). Default is false.
"},{"location":"board/#swap-chess","title":"Swap chess","text":"
board.swapChess(chessA, chessB, align);\n
  • chessA, chessB : Game objects
  • align : Set true to align (i.e. set position) chess to grid (tileX, tileY).
"},{"location":"board/#chess-tile-position","title":"Chess -> tile position","text":"
var tileXYZ = board.chessToTileXYZ(chess);\n
  • chess : A game object
  • tileXYZ : {x,y,z} or null if chess is not added to board.
"},{"location":"board/#tile-position-chess","title":"Tile position -> chess","text":"
  • Get chess at (tileX, tileY, tileZ)
    var chess = board.tileXYZToChess(tileX, tileY, tileZ);\n
    • chess : A game object
  • Get chess at (tileX, tileY)
    var out = board.tileXYToChessArray(tileX, tileY);\n// var out = board.tileXYToChessArray(tileX, tileY, out);\n
    • out : An array of chess
  • Get chess at tileZ
    var out = board.tileZToChessArray(tileZ);\n// var out = board.tileZToChessArray(tileZ, out);\n
    • out : An array of chess
  • Get chess from array of (tileX, tileY)
    var out = board.tileXYArrayToChessArray(tileXYArray);\n// var out = board.tileXYArrayToChessArray(tileXYArray, out);\n
    or
    var out = board.tileXYArrayToChessArray(tileXYArray, tileZ);\n// var out = board.tileXYArrayToChessArray(tileXYArray, tileZ, out);\n
    • tileXYArray : An array of tileXY {x, y}
    • out : An array of chess
"},{"location":"board/#world-position-chess","title":"World position -> chess","text":"
  • Get chess at (worldX, worldY)
    var out = board.worldXYToChessArray(worldX, worldY);\n// var out = board.worldXYToChessArray(worldX, worldY, out);\n
    • out : An array of chess
  • Get chess at (worldX, worldY), tileZ
    var chess = board.worldXYToChess(worldX, worldY, tileZ);\n
    • chess : A game object
  • Get chess at (worldX, worldY)
    var chess = board.worldXYToChess(worldX, worldY);\n
    • chess : A game object at a tileZ.
"},{"location":"board/#contains","title":"Contains","text":"
  • Is (tileX, tileY) inside board?
    var isTileInBoard = board.contains(tileX, tileY);\n
  • Does (tileX, tileY, tileZ) have chess?
    var isTileInBoard = board.contains(tileX, tileY, tileZ);\n
  • Is chess inside board?
    var isChessInBoard = board.exists(chess);\n
    • chess : A game object
"},{"location":"board/#for-each-tile","title":"For each tile","text":"
board.forEachTileXY(function(tileXY, board) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n}, scope);\n

Iteration order :

board.forEachTileXY(function(tileXY, board) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n\n// return isBreak;\n}, scope, order);\n
  • order :
    • 0, or 'x+' : Increasing x, increasing y.
    • 1, or 'x-' : Decreasing x, increasing y.
    • 2, or 'y+' : Increasing y, increasing x.
    • 3, or 'y-' : Decreasing y, increasing x.

Or using for-loop

for (var tileY = 0; tileY < board.height; tileY++) {\nfor (var tileX = 0; tileX < board.width; tileX++) {\n// ...\n}\n}\n
  • board.width , board.height : Board width/height in tiles.
"},{"location":"board/#for-each-tile-in-viewport-of-a-camera","title":"For each tile in viewport of a camera","text":"
board.forEachCullTileXY(function(tileXY, board) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n}, scope);\n
board.forEachCullTileXY(function(tileXY, board) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n}, scope, {\ncamera: board.scene.cameras.main,\npaddingX: 1,\npaddingY: 1,\norder: 0,\n});\n
  • camera : Camera of scene. Default value is the main camera.
  • paddingX , paddingY : Padding space of camera's viewport
  • order :
    • 0, or 'x+' : Increasing x, increasing y.
    • 1, or 'x-' : Decreasing x, increasing y.
    • 2, or 'y+' : Increasing y, increasing x.
    • 3, or 'y-' : Decreasing y, increasing x.
"},{"location":"board/#tile-position-world-position","title":"Tile position -> world position","text":"
var worldXY = board.tileXYToWorldXY(tileX, tileY);  // worldXY: {x, y}\n// var out = board.tileXYToWorldXY(tileX, tileY, out);\n
"},{"location":"board/#world-position-tile-position","title":"World position -> tile position","text":"
var tileXY = board.worldXYToTileXY(worldX, worldY);  // tileXY: {x, y}\n// var out = board.worldXYToTileXY(worldX, worldY, out);\n
"},{"location":"board/#world-position-grid-world-position","title":"World position -> Grid world position","text":"
var gridWorldXY = board.worldXYSnapToGrid(worldX, worldY);\n// var out = board.worldXYSnapToGrid(worldX, worldY, out);\n
"},{"location":"board/#grid-distance","title":"Grid distance","text":"
var distance = board.getDistance(tileA, tileB);\n
  • tileA, tileB : Chess object, or tileXY {x, y}.
"},{"location":"board/#ring-tile-position","title":"Ring -> tile position","text":"
  • Get array of tile position around a ring.
    var out = board.ringToTileXYArray(centerTileXY, radius);\n// var out = board.ringToTileXYArray(centerTileXY, radius, out);\n
    • centerTileXY : Chess object, or tileXY {x, y} of ring center.
    • radius : Radius of the ring.
  • Get array of tile position within a filled ring. centerTileXY will be included.
    var out = board.filledRingToTileXYArray(centerTileXY, radius);\nvar out = board.filledRingToTileXYArray(centerTileXY, radius, nearToFar);\n// var out = board.filledRingToTileXYArray(centerTileXY, radius, out);\n// var out = board.filledRingToTileXYArray(centerTileXY, radius, nearToFar, out);\n
    • centerTileXY : Chess object, or tileXY {x, y} of ring center.
    • radius : Radius of the ring.
    • nearToFar : From near ring to far ring. Default value is true.
"},{"location":"board/#ring-chess","title":"Ring -> chess","text":"
  • Get array of chess around a ring.
    var out = board.ringToChessArray(centerTileXY, radius, tileZ);\n// var out = board.ringToChessArray(centerTileXY, radius, tileZ, out);\n
    • centerTileXY : Chess object, or tileXY {x, y} of ring center.
  • Get array of chess within a filled ring. Chess at centerTileXY will be included.
    var out = board.filledRingToTileXYArray(centerTileXY, radius, tileZ);\nvar out = board.filledRingToTileXYArray(centerTileXY, radius, tileZ, nearToFar);\n// var out = board.filledRingToTileXYArray(centerTileXY, radius, tileZ, out);\n// var out = board.filledRingToTileXYArray(centerTileXY, radius, tileZ, nearToFar, out);\n
    • centerTileXY : Chess object, or tileXY {x, y} of ring center.
"},{"location":"board/#shape-tile-position","title":"Shape -> tile position","text":""},{"location":"board/#line-tile-position","title":"Line -> tile position","text":"

Get array of tile position along a line defined via (startWorldX, startWorldY) to (endWorldX, endWorldY)

var out = board.lineToTileXYArray(startWorldX, startWorldY, endWorldX, endWorldY);\n// var out = board.lineToTileXYArray(startWorldX, startWorldY, endWorldX, endWorldY, out);\n
  • startWorldX, startWorldY, endWorldX, endWorldY : Start and end pointer of a line
  • out : An array of tile position

or

var out = board.lineToTileXYArray(line);\n// var out = board.lineToTileXYArray(line, out);\n
  • line : Line object
"},{"location":"board/#circle-tile-position","title":"Circle -> tile position","text":"

Get array of tile position inside a circle shape

var out = board.circleToTileXYArray(circle);\n// var out = board.circleToTileXYArray(circle, out);\n// var out = board.circleToTileXYArray(circle, testMode, out);\n
  • circle : Circle shape
  • testMode :
    • 0 : Test if shape is overlapping center position of a grid. Default behavior.
    • 1 : Test if shape is overlapping grid bounds of a grid.
    • 2 : Test if shape is overlapping grid points of a grid.
  • out : An array of tile position.
"},{"location":"board/#rectangle-tile-position","title":"Rectangle -> tile position","text":"

Get array of tile position inside a rectangle shape

var out = board.rectangleToTileXYArray(rectangle);\n// var out = board.rectangleToTileXYArray(rectangle, out);\n// var out = board.rectangleToTileXYArray(rectangle, testMode, out);\n
  • rectangle : Rectangle shape
  • testMode :
    • 0 : Test if shape is overlapping center position of a grid. Default behavior.
    • 1 : Test if shape is overlapping grid bounds of a grid.
    • 2 : Test if shape is overlapping grid points of a grid.
  • out : An array of tile position.
"},{"location":"board/#ellipse-tile-position","title":"Ellipse -> tile position","text":"

Get array of tile position inside a ellipse shape

var out = board.ellipseToTileXYArray(ellipse);\n// var out = board.ellipseToTileXYArray(ellipse, out);\n// var out = board.ellipseToTileXYArray(ellipse, testMode, out);\n
  • ellipse : Ellipse shape
  • testMode :
    • 0 : Test if shape is overlapping center position of a grid. Default behavior.
    • 1 : Test if shape is overlapping grid bounds of a grid.
    • 2 : Test if shape is overlapping grid points of a grid.
  • out : An array of tile position.
"},{"location":"board/#triangle-tile-position","title":"Triangle -> tile position","text":"

Get array of tile position inside a triangle shape

var out = board.triangleToTileXYArray(triangle);\n// var out = board.triangleToTileXYArray(triangle, out);\n// var out = board.triangleToTileXYArray(triangle, testMode, out);\n
  • triangle : Triangle shape
  • testMode :
    • 0 : Test if shape is overlapping center position of a grid. Default behavior.
    • 1 : Test if shape is overlapping grid bounds of a grid.
    • 2 : Test if shape is overlapping grid points of a grid.
  • out : An array of tile position.
"},{"location":"board/#polygon-tile-position","title":"Polygon -> tile position","text":"

Get array of tile position inside a polygon shape

var out = board.polygonToTileXYArray(polygon);\n// var out = board.polygonToTileXYArray(polygon, out);\n// var out = board.polygonToTileXYArray(polygon, testMode, out);\n
  • polygon : Polygon shape
  • testMode :
    • 0 : Test if shape is overlapping center position of a grid. Default behavior.
    • 1 : Test if shape is overlapping grid bounds of a grid.
    • 2 : Test if shape is overlapping grid points of a grid.
  • out : An array of tile position.
"},{"location":"board/#angle-between-world-position-of-2-tiles","title":"Angle between world position of 2 tiles","text":"
var radian = board.angleBetween(tileA, tileB);\n
  • tileA, tileB : Chess object, or tileXY {x, y} of ring center.
  • radian : Angle between world position of 2 tiles, in radian.
"},{"location":"board/#is-angle-in-cone","title":"Is angle in cone","text":"
var isInCone = board.isAngleInCone(chessA, chessB, face, cone);\n
  • chessA, chessB : Chess object, or tileXY {x, y}.
  • face, cone : Range of compared angle is between face - (cone/2) to face + (cone/2). Angle in radian.
"},{"location":"board/#direction-between-2-tiles","title":"Direction between 2 tiles","text":"
var direction = board.directionBetween(chessA, chessB);\n
  • chessA, chessB : A chess object, or tile position {x,y}.
  • direction : Integer number.
    • Quad grid : 0, 1, 2, 3, 4, 5, 6, 7.
    • Hexagon grid : 0, 1, 2, 3, 4, 5.
var direction = board.directionBetween(chessA, chessB, false);\n
  • direction : Integer number, or float number.
    • Quad grid : 0, 1, 2, 3, 4, 5, 6, 7, or float number between 0~1, 1~2, 2~3, 3~4, 4~5, 5~6, 6~7.
    • Hexagon grid : 0, 1, 2, 3, 4, 5, or float number between 0~1, 1~2, 2~3, 3~4, 4~5, 5~6.
"},{"location":"board/#is-direction-in-cone","title":"Is direction in cone","text":"
var isInCone = board.isDirectionInCone(chessA, chessB, face, cone);\n
  • chessA, chessB : Chess object, or tileXY {x, y}.
  • face, cone : Range of compared direction is between face - (cone/2) to face + (cone/2). Integer number, or float number.
    • Quad grid : 0, 1, 2, 3, or float number between 0~1, 1~2, 2~3, 3~4.
    • Hexagon grid : 0, 1, 2, 3, 4, 5, or float number between 0~1, 1~2, 2~3, 3~4, 4~5, 5~6.
"},{"location":"board/#opposite-direction","title":"Opposite direction","text":"
var direction = board.getOppositeDirection(tileX, tileY, direction);\n

or

var direction = board.getOppositeDirection(tileXY, direction);\n
  • tileXY : Chess object, or tileXY {x, y}.
"},{"location":"board/#angle-snap-to-direction","title":"Angle snap to direction","text":"
var direction = board.angleSnapToDirection(tileXY, angle);\n
  • tileXY : Chess object, or tileXY {x, y}, or undefined.
  • angle : Angle in radius.
  • direction : Integer number.
    • Quad grid : 0, 1, 2, 3, 4, 5, 6, 7.
    • Hexagon grid : 0, 1, 2, 3, 4, 5.
"},{"location":"board/#align-world-position-to-grid","title":"Align world position to grid","text":"
  • Align one chess object
    board.gridAlign(chess);\n
  • Align all chess
    board.gridAlign();\n
"},{"location":"board/#is-overlapping-with-world-position","title":"Is overlapping with world position","text":"
var isOverlapping = board.isOverlappingPoint(worldX, worldY);\n

or

var isOverlapping = board.isOverlappingPoint(worldX, worldY, tileZ);\n
"},{"location":"board/#neighbors","title":"Neighbors","text":""},{"location":"board/#neighbor-tile-position","title":"Neighbor tile position","text":"
  • Get neighbor tile position at 1 direction
    var neighborTileXY = board.getNeighborTileXY(srcTileXY, direction);\n// var out = board.getNeighborTileXY(srcTileXY, direction, out);\n
    • srcTileXY : Chess object, or tileXY {x, y} of source.
    • direction : Number, or string number.
      • 0 ~ 3 : Quad grid in 4 directions mode.
      • 0 ~ 7 : Quad grid in 8 directions mode.
      • 0 ~ 5 : Hexagon grid.
    • neighborTileXY : Tile position {x, y} of neighbor. Retrun null if no neighbor there (i.e. source chess is at the edge of board.)
  • Get neighbor tile position at directions
    var neighborTileXY = board.getNeighborTileXY(srcTileXY, directions);\n// var out = board.getNeighborTileXY(srcTileXY, directions, out);\n
    • directions
      • Array of numbers, [0, 2, 4].
      • String number concatenated via ,, '0,2,4'.
    • out : Tile position array of all neighbors
  • Get neighbor tile position at all directions
    var out = board.getNeighborTileXY(srcTileXY, null);\n// var out = board.getNeighborTileXY(srcTileXY, null, out);\n
    • out : Tile position array of all neighbors
  • Get direction between 2 tile positions
    var direction = board.getNeighborTileDirection(srcTile, neighborTileXY);\n
    • srcTile, neighborTileXY : Chess object, or tileXY {x, y}.
    • direction : Retu1rn null if these 2 tile positions are not neighbors.
  • Get neighbor tile position at angle
    var neighborTileXY = board.getNeighborTileXYAtAngle(srcTileXY, angle);\n// var out = board.getNeighborTileXYAtAngle(srcTileXY, angle, out);\n
    • srcTileXY : Tile position {x, y} of source.
    • angle : Angle in radius.
    • neighborTileXY : Tile position {x, y} of neighbor. Retrun null if no neighbor there (i.e. source chess is at the edge of board.)
"},{"location":"board/#neighbor-chess","title":"Neighbor chess","text":"
  • Get neighbor chess at 1 direction
    var neighborChess = board.getNeighborChess(chess, direction); // neighborTileZ = tileZ of chess\n// var neighborChess = board.getNeighborChess(chess, direction, neighborTileZ);\n
    • chess : A chess object, or tile position {x, y, z}.
    • direction : Number, or string number.
      • 0 ~ 3 : Quad grid in 4 directions mode.
      • 0 ~ 7 : Quad grid in 8 directions mode.
      • 0 ~ 5 : Hexagon grid.
    • neighborChess : A chess object.
  • Get neighbor chess at directions
    var out = board.getNeighborChess(chess, directions); // neighborTileZ = tileZ of chess\n// var out = board.getNeighborChess(chess, directions, neighborTileZ);\n
    • chess : A chess object, or tile position {x,y,z}.
    • directions
      • Array of numbers, [0, 2, 4].
      • String number concatenated via ,, '0,2,4'.
    • out : Chess array of neighbors.
  • Get neighbor chess at all directions
    var out = board.getNeighborChess(chess, null); // neighborTileZ = tileZ of chess\n// var out = board.getNeighborChess(chess, null, neighborTileZ);\n
    • chess : A chess object, or tile position {x, y, z}.
    • out : Chess array of all neighbors.
  • Get direction between 2 chess
    var direction = board.getNeighborChessDirection(chess, neighborChess);\n
    • direction : Return null if these 2 chess are not neighbors.
  • Are 2 chess neighbors?
    var areNeighbor = board.areNeighbors(tileA, tileB);\n
  • tileA, tileB : A chess object, or tile position {x, y}.
  • areNeighbor : Return true if chessA and chessB are neighbors.
"},{"location":"board/#map-neighbor-tile-position","title":"Map neighbor tile position","text":"
var newArray = board.mapNeighbors(chess, function(neighborTileXY, index, neighborTileXYArray){\nreturn {};\n}, scope);\n

or

var newArray = board.mapNeighbors(chess, distance, function(neighborTileXY, index, neighborTileXYArray){\nreturn {};\n}, scope);\n
  • chess : A chess object, or tile position {x,y,z}.
  • neighborTileXY : Neighbor tile position {x,y,direction}
"},{"location":"board/#tile-at-direction","title":"Tile at direction","text":"
  • Get tile position at 1 direction
    var out = board.getTileXYAtDirection(srcTileXY, direction, distance);\n// var out = board.getTileXYAtDirection(srcTileXY, direction, distance, out);\n
    • srcTileXY : A chess object, or tile position {x, y} of source.
    • direction : Number, or string number.
      • 0 ~ 3 : Quad grid in 4 directions mode.
      • 0 ~ 7 : Quad grid in 8 directions mode.
      • 0 ~ 5 : Hexagon grid.
    • distance : A JSON, number, or number array.
      • JSON : Range of distances. {end: 3} is equal to [1,2,3].
        {\nstart: 1,\nend: 1,\nstep: 1\n}\n
        • start : Start distance. Default value is 1.
        • end : End distance. Default value is 1.
        • step : Step. Default value is 1.
      • Number, 3.
      • Array of numbers, [2, 3, 5] : Array of distances.
    • out :
      • A single tile position, if distance is a number.
      • Tile position {x, y} array, if distance is a JSON or a number array.
  • Get tile positions at directions
    var neighborTileXY = board.getTileXYAtDirection(srcTileXY, directions, distance);\n// var out = board.getTileXYAtDirection(srcTileXY, directions, distance, out);\n
    • directions
      • Array of numbers, [0, 2, 4].
      • String number concatenated via ,, '0,2,4'.
    • out : Tile position {x, y} array.
  • Get tile positions at all directions
    var out = board.getTileXYAtDirection(srcTileXY, null, distance);\n// var out = board.getTileXYAtDirection(srcTileXY, null, distance, out);\n
    • out : Tile position {x, y} array.
"},{"location":"board/#empty-tile-position","title":"Empty tile position","text":"
  • Is tile empty? (TileXY is inside board, and TileXYZ has no chess)
    var isEmpty = board.isEmptyTileXYZ(tileX, tileY, tileZ);\n
  • Get a random tile position which does not have any chess
    var tileXY = board.getRandomEmptyTileXY(tileZ);\n// var out = board.getRandomEmptyTileXY(tileZ, out);\n
    • tileXY : Tile position {x, y},
      • null : All positions are occupied.
  • Get an array of tile position which does not have any chess
    var tileXYArray = board.getEmptyTileXYArray(tileZ);\n// var out = board.getEmptyTileXYArray(tileZ, out);\n
    • tileXYArray : An array of tile position
  • Get a random tile position of neighbor which does not have any chess
    var tileXY = board.getRandomEmptyTileXYInRange(centerTileXY, radius, tileZ);\n// var out = board.getRandomEmptyTileXYInRange(centerTileXY, radius, tileZ, out);\n
    • centerTileXY : Chess object, or tileXY {x, y} of ring center.
    • radius : Radius of the ring.
    • tileXY : Tile position {x, y},
      • null : All positions are occupied.
  • Get an array of tile position of neighbors which does not have any chess
    var tileXYArray = board.getEmptyTileXYArrayInRange(centerTileXY, radius, tileZ);\n// var out = board.getEmptyTileXYArrayInRange(centerTileXY, radius, tileZ, out);\n
    • centerTileXY : Chess object, or tileXY {x, y} of ring center.
    • radius : Radius of the ring.
    • tileXYArray : An array of tile position
"},{"location":"board/#get-all-chess","title":"Get all chess","text":"
var chessArray = board.getAllChess();\n
"},{"location":"board/#fit","title":"Fit","text":"
var out = board.fit(tileXYArray);\n
  • tileXYArray : An array of tile position {x,y}.

Offset all of tile positions to (0, 0), and set board size to fit these tile positions.

"},{"location":"board/#blocker","title":"Blocker","text":"
  • Set blocker property : See chess data
  • Has blocker at tile position (tileX, tileY, tileZ)
    var hasBlocker = board.hasBlocker(tileX, tileY, tileZ);\n// var hasBlocker = board.hasBlocker(chess);  // chess or tileXYZ\n
  • Any chess at (tileX, tileY) has blocker property
    var hasBlocker = board.hasBlocker(tileX, tileY);\n// var hasBlocker = board.hasBlocker(chess);  // chess or tileXY\n
"},{"location":"board/#touch-events","title":"Touch events","text":""},{"location":"board/#set-interactive","title":"Set interactive","text":"
  • Enable
    board.setInteractive();\n// board.setInteractive({ useTouchZone: false });\n
    • useTouchZone :
      • true : Detect touch input by input event of a full-screen zone game object. Default behavior.
      • false : Detect touch input by input event of scene.
  • Disable
    board.setInteractive(false);\n
"},{"location":"board/#touch-zone","title":"Touch Zone","text":"
  • Get
    var touchZone = board.getTouchZone();\n// var touchZone = board.touchZone;\n
    • Return null if useTouchZone is false.
  • Set depth
    touchZone.setDepth(depth);\n
    or
    scene.children.bringToTop(touchZone);\nscene.children.sendToBack(touchZone);\nscene.children.moveUp(touchZone);\nscene.children.moveDown(touchZone);\nscene.children.moveUp(touchZone);\nscene.children.moveTo(touchZone, index);\nscene.children.moveAbove(touchZone, child); // Move touchZone above child\nscene.children.moveBelow(touchZone, child); // Move touchZone below child\nscene.children.swap(touchZone, child);\n
"},{"location":"board/#pointer-down","title":"Pointer down","text":"
  • Pointer down at any tile
    board.on('tiledown', function(pointer, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • pointer : Touch pointer
    • tileXY : {x, y}
  • Pointer down at chess
    board.on('gameobjectdown', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('board.pointerdown', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#pointer-up","title":"Pointer up","text":"
  • Pointer up at any tile
    board.on('tileup', function(pointer, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • tileXY : {x, y}
  • Pointer up at chess
    board.on('gameobjectup', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('board.pointerup', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#pointer-move","title":"Pointer move","text":"
  • Pointer move to another tile
    board.on('tilemove', function(pointer, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • tileXY : {x, y}
    • Only triggered when tileXY is changed.
  • Pointer move to another chess
    board.on('gameobjectmove', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('board.pointermove', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#pointer-over","title":"Pointer over","text":"
  • Pointer over to another tile
    board.on('tileover', function(pointer, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • tileXY : {x, y}
    • Only triggered when tileXY is changed.
  • Pointer over to another chess
    board.on('gameobjectover', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('board.pointerover', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#pointer-out","title":"Pointer out","text":"
  • Pointer out tile
    board.on('tileout', function(pointer, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • tileXY : {x, y}
    • Only triggered when tileXY is changed.
  • Pointer out chess
    board.on('gameobjectout', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('board.pointerout', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at pointer-out (tileX, tileY)
"},{"location":"board/#tap","title":"Tap","text":"
  • Tap at any tile
    board.on('tiletap', function(tap, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n// var tapsCount = tap.tapsCount;\n});\n
    • tap : Tap behavior.
      • tap.tapsCount : Taps count.
    • tileXY : {x, y}
  • N-taps at any tile
    board.on('tile' + tapsCount + 'tap' , function(tap, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • 'tile' + tapsCount + 'tap' : 'tile1tap', 'tile2tap', 'tile3tap', etc ...
    • tap : Tap behavior.
    • tileXY : {x, y}
  • Tap at chess
    board.on('gameobjecttap', function(tap, gameObject) {\n// var tapsCount = tap.tapsCount;\n})\n
    or
    gameObject.on('board.tap', function(tap) {\n// var tapsCount = tap.tapsCount;\n})\n
    • tap : Tap behavior.
      • tap.tapsCount : Taps count.
    • gameObject : Game object at touched (tileX, tileY)
  • N-taps at chess
    board.on('gameobject' + tapsCount + 'tap' , function(tap, gameObject) {\n})\n
    or
    gameObject.on('board.' + tapsCount + 'tap', function(tap) {\n})\n
    • 'gameobject' + tapsCount + 'tap' : 'gameobject1tap', 'gameobject2tap', 'gameobject3tap', etc ...
    • 'board.' + tapsCount + 'tap' : 'board.1tap', 'board.2tap', 'board.3tap', etc ...
    • tap : Tap behavior.
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#press","title":"Press","text":"
  • Press-start at any tile
    board.on('tilepressstart', function(press, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • press : Press behavior.
    • tileXY : {x, y}
  • Press-end at any tile
    board.on('tilepressend', function(press, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • press : Press behavior.
    • tileXY : {x, y}
  • Press-star at chess
    board.on('gameobjectpressstart', function(press, gameObject) {\n})\n
    or
    gameObject.on('board.pressstart', function(press) {\n})\n
    • press : Press behavior.
    • gameObject : Game object at touched (tileX, tileY)
  • Press-end at chess
    board.on('gameobjectpressend', function(press, gameObject) {\n})\n
    or
    gameObject.on('board.pressend', function(press) {\n})\n
    • press : Press behavior.
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#swipe","title":"Swipe","text":"
  • Swipe at any tile
    board.on('tileswipe', function(swipe, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n// var direction = swipe.direction;\n});\n
    • swipe : Swipe behavior.
      • swipe.direction : Integer number.
        • Quad grid : 0, 1, 2, 3, 4, 5, 6, 7.
        • Hexagon grid : 0, 1, 2, 3, 4, 5.
    • tileXY : {x, y}
  • Swipe at chess
    board.on('gameobjectswipe', function(swipe, gameObject) {\n// var direction = swipe.direction;\n})\n
    or
    gameObject.on('board.swipe', function(swipe) {\n// var direction = swipe.direction;\n})\n
    • swipe : Swipe behavior.
      • swipe.direction : Integer number.
        • Quad grid : 0, 1, 2, 3, 4, 5, 6, 7.
        • Hexagon grid : 0, 1, 2, 3, 4, 5.
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#grid-points","title":"Grid points","text":"
  • Get an array of grid points at tile position (tileX, tileY).
    var points = board.getGridPoints(tileX, tileY);\n// var out = board.getGridPoints(tileX, tileY, out);\n// var points = board.getGridPoints(chess, out);  // chess or tileXY\n
    • points :\u3000Array of world position {x, y}.
  • Draw grid polygon on graphics object
    graphics.strokePoints(points, true);\n
"},{"location":"board/#bounds","title":"Bounds","text":""},{"location":"board/#board-bounds","title":"Board bounds","text":"
  • Get a rectangle of all tiles
    var rectangle = board.getBoardBounds();\n// var out = board.getGridBounds(out);\n
    • rectangle : Rectangle object.
  • Draw rectangle on graphics object
    graphics.strokeRectShape(rectangle);\n
"},{"location":"board/#grid-bounds","title":"Grid bounds","text":"
  • Get a rectangle of a tile
    var rectangle = board.getGridBounds(tileX, tileY);\n// var out = board.getGridBounds(tileX, tileY, out);\n// var rectangle = board.getGridBounds(chess, out);  // chess or tileXY\n
    • rectangle : Rectangle object.
  • Draw rectangle on graphics object
    graphics.strokeRectShape(rectangle);\n
"},{"location":"board/#get-board","title":"Get Board","text":"
  • Static method

    var board = Board.GetBoard(chess);\n

    • GetBoard is a static method of Board class.
  • Member method

    var board = board.chessToBoard(chess);\n

  • Board property
    • Chess
      var board = chess.rexChess.board;\n
    • Miniboard
      var board = miniboard.mainBoard;\n
"},{"location":"board/#other-properties","title":"Other properties","text":"
  • Scene
    var scene = board.scene;\n
  • Grid object
    • Get
      var grid = board.grid;\n
      • grid : Quad grid, or hexagon grid.
    • Set
      board.setGrid(grid);\n
      • grid : Quad grid, or hexagon grid.
"},{"location":"bounds/","title":"Bounds","text":""},{"location":"bounds/#introduction","title":"Introduction","text":"

Clamp or wrap position of game object inside target bounds.

  • Author: Rex
  • Behavior of game object
"},{"location":"bounds/#live-demos","title":"Live demos","text":"
  • Drag inside bounds
  • Target bounds
  • Wrap bounds
"},{"location":"bounds/#usage","title":"Usage","text":"

Sample code

"},{"location":"bounds/#install-plugin","title":"Install plugin","text":""},{"location":"bounds/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexboundsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboundsplugin.min.js', true);\n
  • Add bounds behavior
    var bounds = scene.plugins.get('rexboundsplugin').add(gameObject, config);\n
"},{"location":"bounds/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoundsPlugin from 'phaser3-rex-plugins/plugins/bounds-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBounds',\nplugin: BoundsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add bounds behavior
    var bounds = scene.plugins.get('rexBounds').add(gameObject, config);\n
"},{"location":"bounds/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Bounds from 'phaser3-rex-plugins/plugins/bounds.js';\n
  • Add bounds behavior
    var bounds = new Bounds(gameObject, config);\n
"},{"location":"bounds/#create-instance","title":"Create instance","text":"
var bounds = scene.plugins.get('rexBounds').add(gameObject, {\n// target: undefined,\n// bounds: undefined,\n// enable: true,\n\n// boundsHitMode: 'clamp',  // 'clamp', or 'wrap'\n// boundsHitMode: {\n//     left: 'clamp',\n//     right: 'clamp',\n//     top: 'clamp',\n//     bottom: 'clamp' \n// },\n\n// alignMode: 0\n});\n
  • target :
    • A game object : Update target bounds from this game object in each tick.
    • undefined, null, or false : Set target bounds in bounds parameter. Default behavior.
  • bounds : Target bounds used when target is not a game object.
    • A rectangle object
    • An object :
      {\nwidth: 0, height: 0,\nx: 0, y: 0,\ncenterX: 0, centerY: 0,            }\n
      • width, height : Size of target bounds.
      • x, y, or centerX, centerY : Position of target bounds.
  • enable :
    • true : Clamp or wrap game object's position when game object overlap left/right/top/bottom bounds.
    • false : Don't clamp or wrap game object's position at any bound
    • An objecct : Set true to clamp or wrap game object's position at a bound
      {\nleft: true,\nright: true,\ntop: true,\nbottom: true\n}\n
  • boundsHitMode : Position mode when game object overlap bounds
    • 0, or 'clamp' : Clamp game object's position when game object overlap left/right/top/bottom bounds.
    • 1, or 'wrap' : Wrap game object's position when game object overlap left/right/top/bottom bounds.
    • An objecct : Set 0/'clamp', or 1/'wrap' to clamp or wrap game object's position at a bound
      {\nleft: 0,   // 0,'clamp',1,'wrap'\nright: 0,  // 0,'clamp',1,'wrap'\ntop: 0,    // 0,'clamp',1,'wrap'\nbottom: 0  // 0,'clamp',1,'wrap'\n}\n
  • alignMode :
    • 0, or 'bounds' : Align bounds of game object to target bound. Default behavior if boundsHitMode are all set to clamp mode.
    • 1, or 'origin' : Set position of game object to target bound. Default behavior if boundsHitMode has wrap mode.
"},{"location":"bounds/#target-game-object","title":"Target game object","text":"
  • Set
    bounds.setBoundsTarget(gameObject);\n// bounds.boundsTarget = gameObject;\n
  • Clear
    bounds.setBoundsTarget();\n// bounds.boundsTarget = undefined;\n
  • Get
    var gameObject = bounds.boundsTarget;\n
"},{"location":"bounds/#target-bounds","title":"Target bounds","text":"
  • Set
    bounds.setBounds(bounds);\n
    • bounds : Target bounds used when target is not a game object.
      • A rectangle
      • An object :
        {\nwidth: 0, height: 0,\nx: 0, y: 0,\ncenterX: 0, centerY: 0,            }\n
        • width, height : Size of target bounds.
        • x, y, or centerX, centerY : Position of target bounds.
  • Get
    var rect = bounds.bounds;\n
    • rect : A rectangle object
"},{"location":"bounds/#enable","title":"Enable","text":"
  • Set
    • Enable all bounds
      bounds.setEnable();\n//  bounds.setEnable(true);\n
    • Disable all bounds
      bounds.setEnable(false);\n
    • Enable bounds via object
      bounds.setEnable({\nleft: true,\nright: true,\ntop: true,\nbottom: true\n});\n
  • Get
    var enable = bounds.enable;\n
    • true : Has any enabled bounds
    • false : All bounds are disabled.
  • Get enabled of a bound
    var enableLeftBound = bounds.boundsEnable.left;\nvar enableRightBound = bounds.boundsEnable.right;\nvar enableTopBound = bounds.boundsEnable.top;\nvar enableBottomBound = bounds.boundsEnable.bottom;\n
"},{"location":"bounds/#bound-hit-mode","title":"Bound hit mode","text":"
  • Set
    bounds.setBoundsHitMode(mode);\n
    • 0, or 'clamp' : Clamp game object's position when game object overlap left/right/top/bottom bounds.
    • 1, or 'wrap' : Wrap game object's position when game object overlap left/right/top/bottom bounds.
    • An objecct : Set 0/'clamp', or 1/'wrap' to clamp or wrap game object's position at a bound
      {\nleft: 0,   // 0,'clamp',1,'wrap'\nright: 0,  // 0,'clamp',1,'wrap'\ntop: 0,    // 0,'clamp',1,'wrap'\nbottom: 0  // 0,'clamp',1,'wrap'\n}\n
  • Get
    var leftBoundHitMode = bounds.boundsHitMode.left;\nvar rightBoundHitMode = bounds.boundsHitMode.right;\nvar topBoundHitMode = bounds.boundsHitMode.top;\nvar bottomBoundHitMode = bounds.boundsHitMode.bottom;\n
"},{"location":"bounds/#align-mond","title":"Align mond","text":"
  • Set
    bounds.setAlignMode(mode);\n
    • 0, or 'bounds' : Align bounds of game object to target bound.
    • 1, or 'origin' : Set position of game object to target bound.
  • Get
    var alignMode = bounds.alignMode;\n
    • 0 : Align bounds of game object to target bound.
    • 1 : Set position of game object to target bound.
"},{"location":"bounds/#hit-result","title":"Hit result","text":"
  • Game object is hitting any bound
    var isHitAny = bounds.isHitAny;\n
  • Game object is hitting a bound
    var isHitLeft = this.isHitLeft;\nvar isHitRight = this.isHitRight;\nvar isHitTop = this.isHitTop;\nvar isHitBottom = this.isHitBottom;\n
"},{"location":"bounds/#event","title":"Event","text":"
  • On hit any bound
    bounds.on('hitany', function(gameObject, bounds) {\n\n})\n
  • On hit left bound
    bounds.on('hitleft', function(gameObject, bounds) {\n\n})\n
  • On hit right bound
    bounds.on('hitright', function(gameObject, bounds) {\n\n})\n
  • On hit top bound
    bounds.on('hittop', function(gameObject, bounds) {\n\n})\n
  • On hit bottom bound
    bounds.on('hitbottom', function(gameObject, bounds) {\n\n})\n
"},{"location":"bracketparser/","title":"Bracket parser","text":""},{"location":"bracketparser/#introduction","title":"Introduction","text":"

A lite-weight delimiter parser.

  • Author: Rex
  • Object
"},{"location":"bracketparser/#live-demoes","title":"Live demoes","text":"
  • Basic
  • Markup text
"},{"location":"bracketparser/#usage","title":"Usage","text":"

Sample code

"},{"location":"bracketparser/#install-plugin","title":"Install plugin","text":""},{"location":"bracketparser/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbracketparserplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbracketparserplugin.min.js', true);\n
  • Add parser object
    var parser = scene.plugins.get('rexbracketparserplugin').add(config);\n
"},{"location":"bracketparser/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BracketParserPlugin from 'phaser3-rex-plugins/plugins/bracketparser-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBracketParser',\nplugin: BracketParserPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add parser object
    var parser = scene.plugins.get('rexBracketParser').add(config);\n
"},{"location":"bracketparser/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import BracketParser from 'phaser3-rex-plugins/plugins/bracketparser.js';\n
  • Add parser object
    var parser = new BracketParser(config);\n
"},{"location":"bracketparser/#create-instance","title":"Create instance","text":"
var parser = scene.plugins.get('rexBracketParser').add({\n// delimiters: '<>', // or ['<', '>']\n// valueConvert: true,\n// translateTagNameCallback: undefined,\n});\n
  • delimiters: String of left-delimiter and right-delimiter.
    • A single string with 2 characters. Default value is '<>'.
    • A array with 2 strings
  • valueConvert : A callback to convert values.
    • true : Use defaule value converter. Values will be converted to number (include hex number string like '0xFF'), boolean, null, or string.
    • false, or null : Bypass string value.
    • Function object:
      function(s) {\nreturn s;\n}\n
  • translateTagNameCallback : Callback to translate tag-name
    • undefined : Use original tag-name. Default behavior.
    • A function, return new tag name.
      function(tagName) {\nreturn newTagName;\n}\n
"},{"location":"bracketparser/#tag-and-content","title":"Tag and content","text":"

Assume that left-delimiter and right-delimiter is '<>'

  • Start-tag : '<TAG>'
    • Start-tag with a single value : '<TAG=value>'
      • value : If valueConvert is true,
        • Number
        • Boolean
        • null
        • String
    • Start-tag with array values, separated via ',' : '<TAG=value0,value1,value2>'
  • End-tag : '<\\TAG>'
  • Content : Any string outside of tag-start, or tag-end.
"},{"location":"bracketparser/#start-parsing","title":"Start parsing","text":"
parser.start(text);\n

These events will be emitted under this method.

"},{"location":"bracketparser/#pause","title":"Pause","text":"
  • Pause
    parser.pause();\n
  • Pause until event
    parser.pauseUntilEvent(eventEmitter, eventName);\n
    • Will invoke
      eventEmitter.once(eventName, function() {\nparser.next();\n})\n

Invoke this method during tag-start,tag-end, or content events to suspend parsing.

"},{"location":"bracketparser/#resume","title":"Resume","text":"
parser.next();\n
"},{"location":"bracketparser/#skip-any-tag-startany-tag-end-event","title":"Skip any-tag-start/any-tag-end event","text":"
parser.skipEvent();\n

When getting a tag-start, or a tag-end event, parser will emitts

  • Start-tag : '+TAG', then '+'
  • End-tag : '-TAG', then '-'

Invoke this medthod under '+TAG', or '-TAG' event to skip '+', or '-' event.

"},{"location":"bracketparser/#status","title":"Status","text":"
  • Is parsing
    var isRunning = parser.isRunning;\n
    • true : Has remainder characters
    • false : After parsing last character
  • Is paused
    var isPaused = parser.isPaused;\n
"},{"location":"bracketparser/#events","title":"Events","text":""},{"location":"bracketparser/#tagscontent","title":"Tags/Content","text":"
  • Get a specific tag-start
    • Start-tag with a single value : '<TAG=value>'
      parser.on('+' + TagName, function(value){ /* ... */ });\n
    • Start-tag with array values, separated via ',' : '<TAG=value0,value1,value2>'
      parser.on('+' + TagName, function(value0, value1, value2){ /* ... */ });\n
  • Get any-tag-start
    • Start-tag with a single value : '<TAG=value>'
      parser.on('+', function(tagName, value){ /* ... */ });\n
    • Start-tag with array values, separated via ',' : '<TAG=value0,value1,value2>'
      parser.on('+', function(tagName, value0, value1, value2){ /* ... */ });\n
  • Get a specific tag-end
    parser.on('-' + TagName, function(){ /* ... */ });\n
  • Get a content
    parser.on('content', function(content){ /* ... */ });\n
    • Previous tag-start : parser.lastTagStart
  • Get any-tag-end
    parser.on('-', function(tagName){ /* ... */ });\n
    • Previous tag-start : parser.lastTagStart
    • Previous Content : parser.lastContent
"},{"location":"bracketparser/#control-flow","title":"Control flow","text":"
  • Parsing start
    parser.on('start', function(){ /* ... */ });\n
  • Parsing end
    parser.on('complete', function(){ /* ... */ });\n
  • On pause
    parser.on('pause', function(){ /* ... */ });\n
  • On resume
    parser.on('resume', function(){ /* ... */ });\n
"},{"location":"bracketparser2/","title":"Bracket parser 2","text":""},{"location":"bracketparser2/#introduction","title":"Introduction","text":"

A lite-weight delimiter parser.

  • Author: Rex
  • Object
"},{"location":"bracketparser2/#live-demoes","title":"Live demoes","text":"
  • Basic
"},{"location":"bracketparser2/#usage","title":"Usage","text":"

Sample code

"},{"location":"bracketparser2/#install-plugin","title":"Install plugin","text":""},{"location":"bracketparser2/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbracketparser2plugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbracketparser2plugin.min.js', true);\n
  • Add parser object
    var parser = scene.plugins.get('rexbracketparser2plugin').add(config);\n
"},{"location":"bracketparser2/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BracketParserPlugin from 'phaser3-rex-plugins/plugins/bracketparser2-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBracketParser',\nplugin: BracketParserPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add parser object
    var parser = scene.plugins.get('rexBracketParser').add(config);\n
"},{"location":"bracketparser2/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import BracketParser from 'phaser3-rex-plugins/plugins/bracketparser2.js';\n
  • Add parser object
    var parser = new BracketParser(config);\n
"},{"location":"bracketparser2/#create-instance","title":"Create instance","text":"
var parser = scene.plugins.get('rexBracketParser').add({\n// delimiters: '<>', // or ['<', '>']\n// valueConvert: true,\n// translateTagNameCallback: undefined,\n});\n
  • delimiters: String of left-delimiter and right-delimiter.
    • A single string with 2 characters. Default value is '<>'.
    • A array with 2 strings
  • valueConvert : A callback to convert values.
    • true : Use defaule value converter. Values will be converted to number (include hex number string like '0xFF'), boolean, null, or string.
    • false, or null : Bypass string value.
    • Function object:
      function(s) {\nreturn s;\n}\n
  • translateTagNameCallback : Callback to translate tag-name
    • undefined : Use original tag-name. Default behavior.
    • A function, return new tag name.
      function(tagName) {\nreturn newTagName;\n}\n
"},{"location":"bracketparser2/#tag-and-content","title":"Tag and content","text":"

Assume that left-delimiter and right-delimiter is '<>'

  • Start-tag : <TAG>
  • Start-tag with payload :
    <TAG param0=value0 param1=value1>\n
    or
    <\n    TAG\n    param0=value0 \n    param1=value1\n>\n
    • payload will be {param0:value0, param1:value1}
    • value : If valueConvert is true,
      • String with '...', or \"...\"
      • JSON array with [...]
      • JSON object with {...}
      • Number
      • Boolean
      • null
      • String
  • End-tag : <\\TAG>
  • End-tag with payload
    <\\TAG param0=value0 param1=value1>\n
    or
    <\n    \\TAG\n    param0=value0 \n    param1=value1\n>\n
    • payload will be {param0:value0, param1:value1}
    • value : If valueConvert is true,
      • String with '...', or \"...\"
      • JSON array with [...]
      • JSON object with {...}
      • Number
      • Boolean
      • null
      • String
  • Content : Any string outside of tag-start, or tag-end.
"},{"location":"bracketparser2/#start-parsing","title":"Start parsing","text":"
parser.start(text);\n

These events will be emitted under this method.

"},{"location":"bracketparser2/#pause","title":"Pause","text":"
  • Pause
    parser.pause();\n
  • Pause until event
    parser.pauseUntilEvent(eventEmitter, eventName);\n
    • Will invoke
      eventEmitter.once(eventName, function() {\nparser.next();\n})\n

Invoke this method during tag-start,tag-end, or content events to suspend parsing.

"},{"location":"bracketparser2/#resume","title":"Resume","text":"
parser.next();\n
"},{"location":"bracketparser2/#skip-any-tag-startany-tag-end-event","title":"Skip any-tag-start/any-tag-end event","text":"
parser.skipEvent();\n

When getting a tag-start, or a tag-end event, parser will emitts

  • Start-tag : '+TAG', then '+'
  • End-tag : '-TAG', then '-'

Invoke this medthod under '+TAG', or '-TAG' event to skip '+', or '-' event.

"},{"location":"bracketparser2/#status","title":"Status","text":"
  • Is parsing
    var isRunning = parser.isRunning;\n
    • true : Has remainder characters
    • false : After parsing last character
  • Is paused
    var isPaused = parser.isPaused;\n
"},{"location":"bracketparser2/#events","title":"Events","text":""},{"location":"bracketparser2/#tagscontent","title":"Tags/Content","text":"
  • Get a specific tag-start
    • Start-tag with payload : '<TAG param0=value0 param1=value1>'
      parser.on('+' + TagName, function(payload){ /* ... */ });\n
      • payload : {param0:value0, param1:value1, ...}
  • Get any-tag-start
    • Start-tag with payload : '<TAG param0=value0 param1=value1>'
      parser.on('+', function(tagName, payload){ /* ... */ });\n
      • payload : {param0:value0, param1:value1, ...}
  • Get a specific tag-end
    • End-tag with payload : '<\\TAG param0=value0 param1=value1>'
      parser.on('-' + TagName, function(payload){ /* ... */ });\n
      • payload : {param0:value0, param1:value1, ...}
  • Get a content
    parser.on('content', function(content){ /* ... */ });\n
    • Previous tag-start : parser.lastTagStart
      {\nname: '',\npayload: {}\n}\n
  • Get any-tag-end
    • End-tag with payload : '<TAG param0=value0 param1=value1>'
      parser.on('-', function(tagName, payload){ /* ... */ });\n
      • payload : {param0:value0, param1:value1, ...}
    • Previous tag-start : parser.lastTagStart
      {\nname: '',\npayload: {}\n}\n
    • Previous Content : parser.lastContent
"},{"location":"bracketparser2/#control-flow","title":"Control flow","text":"
  • Parsing start
    parser.on('start', function(){ /* ... */ });\n
  • Parsing end
    parser.on('complete', function(){ /* ... */ });\n
  • On pause
    parser.on('pause', function(){ /* ... */ });\n
  • On resume
    parser.on('resume', function(){ /* ... */ });\n
"},{"location":"bracketparser2/#compare-with-bracket-parser","title":"Compare with bracket-parser","text":"

Tag format in

  • bracket-parser:
    <TAG=value0,value1>\n
    • Carried parameters is an array, more compactly.
  • bracket-parser2:
    <TAG param0=value0 param1=value1>\n
    or
    <\n  TAG \n    param0=value0 \n    param1=value1\n>\n
    • Carried parameters is a dictionary, more clearly.
"},{"location":"buffdata/","title":"Buff data","text":""},{"location":"buffdata/#introduction","title":"Introduction","text":"

Data manager with buffs, extends from built-in data manager.

  • Author: Rex
  • Member of scene
"},{"location":"buffdata/#usage","title":"Usage","text":"

Sample code

"},{"location":"buffdata/#install-plugin","title":"Install plugin","text":""},{"location":"buffdata/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbuffdataplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbuffdataplugin.min.js', true);\n
  • Add buff data manager object
    var data = scene.plugins.get('rexbuffdataplugin').add(parent);\n
"},{"location":"buffdata/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BuffDataPlugin from 'phaser3-rex-plugins/plugins/buffdata-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBuffData',\nplugin: BuffDataPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add buff data manager object
    var data = scene.plugins.get('rexBuffData').add(parent);\n
"},{"location":"buffdata/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import BuffData from 'phaser3-rex-plugins/plugins/buffdata.js';\n
  • Add buff data manager object
    var data = new BuffData(parent);\n
"},{"location":"buffdata/#create-instance","title":"Create instance","text":"
var data = scene.plugins.get('rexBuffData').add(parent);\n// var data = scene.plugins.get('rexBuffData').add(parent, eventEmitter);\n
  • data : Buff data manager
  • parent : The object (a scene, or a game object) that this DataManager belongs to.
  • eventEmitter : The DataManager's event emitter.
"},{"location":"buffdata/#extend-existing-data-manager","title":"Extend existing data manager","text":"
var data = scene.plugins.get('rexBuffData').extend(data);\n
  • data : Existing data manager
"},{"location":"buffdata/#buff","title":"Buff","text":"

A value is composed of baseValue, and some buffs, clamped by min, max values.

  • Base value

    • Set
      data.setBaseValue(key, value);\n
    • Remove
      data.removeBaseValue(key);\n
    • Get
      var baseValue = data.getBaseValue(key);\n
  • Buffs, each value can have many buffs, or no buff.

    • Add/set a buff
      data.setBuff(key, buffKey, value);\n
      • value :
        • A number
        • A string for percentage like '10%', which means that (baseValue * percentage)
    • Remove a buff of a key
      data.removeBuff(key, buffKey);\n
    • Remove all buffs of a key
      data.removeBuff(key);\n
    • Get a buff value
      var buffValue = data.getBuffValue(key, buffKey);\n
  • Min, max bounds, optional.
    • Set
      data.setMin(key, min);\n
      data.setMax(key, max);\n
      data.setBounds(key, min, max);\n
      • min, max : Clamp buffed result value between min and max value. Set undefined to ignore it.
    • Get
      var min = data.getMinBound(key);\nvar max = data.getMaxBound(key);\n
  • Buffed result
    • Get
      var result = data.get(key);\n
    • Events
"},{"location":"buildarcadeobject/","title":"Build arcade object","text":""},{"location":"buildarcadeobject/#introduction","title":"Introduction","text":"

Create arcade body, and inject arcade object methods.

  • Author: Rex
  • Arcade behavior of game object
"},{"location":"buildarcadeobject/#usage","title":"Usage","text":"

Sample code

"},{"location":"buildarcadeobject/#install-plugin","title":"Install plugin","text":""},{"location":"buildarcadeobject/#load-minify-file","title":"Load minify file","text":"
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbuildarcadeobjectplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbuildarcadeobjectplugin.min.js', true);\n
  • Inject arcade object methods
    var gameObject = scene.plugins.get('rexbuildarcadeobjectplugin').build(gameObject);\n
"},{"location":"buildarcadeobject/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine and install plugin in configuration of game
    import BuildArcadeObjectPlugin from 'phaser3-rex-plugins/plugins/buildarcadeobject-plugin.js';\nvar config = {\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBuildArcadeObject',\nplugin: BuildArcadeObjectPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Inject arcade object methods
    var gameObject = scene.plugins.get('rexBuildArcadeObject').build(gameObject);\n
"},{"location":"buildarcadeobject/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Import class
    import BuildArcadeObject from 'phaser3-rex-plugins/plugins/buildarcadeobject.js';\n
  • Inject arcade object methods
    var gameObject = BuildArcadeObject(gameObject);\n
"},{"location":"buildarcadeobject/#inject-arcade-object-methods","title":"Inject arcade object methods","text":"
  • Inject arcade method to game object
    scene.plugins.get('rexBuildArcadeObject').injectMethods(gameObject);\n// scene.physics.add.existing(gameObject);        // Dynamic arcade body\n// scene.physics.add.existing(gameObject, true);  // Static arcade body\n
  • Inject arcade method to game object class
    scene.plugins.get('rexBuildArcadeObject').injectMethods(GameObjectClass.prototype);\n
  • Inject arcade method to root of all game object class
    scene.plugins.get('rexBuildArcadeObject').injectMethodsToRootClass();\n
  • Create dynamic arcade body
    var gameObject = scene.plugins.get('rexBuildArcadeObject').build(gameObject);\n// var gameObjects = scene.plugins.get('rexBuildArcadeObject').build(gameObjects);\n
  • Create static arcade body
    var gameObject = scene.plugins.get('rexBuildArcadeObject').build(gameObject, true);\n// var gameObjects = scene.plugins.get('rexBuildArcadeObject').build(gameObjects, true);\n
"},{"location":"bullet/","title":"Bullet","text":""},{"location":"bullet/#introduction","title":"Introduction","text":"

Move game object toward current angle of game object, with a constant speed.

  • Author: Rex
  • Arcade behavior of game object
"},{"location":"bullet/#usage","title":"Usage","text":"

Sample code

"},{"location":"bullet/#install-plugin","title":"Install plugin","text":""},{"location":"bullet/#load-minify-file","title":"Load minify file","text":"
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbulletplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbulletplugin.min.js', true);\n
  • Add bullet behavior
    var bullet = scene.plugins.get('rexbulletplugin').add(gameObject, config);\n
"},{"location":"bullet/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine and install plugin in configuration of game
    import BulletPlugin from 'phaser3-rex-plugins/plugins/bullet-plugin.js';\nvar config = {\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBullet',\nplugin: BulletPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add bullet behavior
    var bullet = scene.plugins.get('rexBullet').add(gameObject, config);\n
"},{"location":"bullet/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Import class
    import Bullet from 'phaser3-rex-plugins/plugins/bullet.js';\n
  • Add bullet behavior
    var bullet = new Bullet(gameObject, config);\n
"},{"location":"bullet/#create-instance","title":"Create instance","text":"
var bullet = scene.plugins.get('rexBullet').add(gameObject, {\nspeed: 200,\n// wrap: false,\n// padding: 0,\n// enable: true,\n\n// angle: undefined,\n// rotation: undefined\n});\n
  • speed : moving speed, pixels in second.
  • Wrap
    • wrap : Set true to enable wrap mode. Default value is false.
    • padding
  • enable : set false to disable moving.
  • angle, rotation :
    • undefined : Use angle of game object as angle of bullet. Default value.
    • A number : Angle of bullet, in degrees or radians.
"},{"location":"bullet/#speed","title":"Speed","text":"
  • Set
    bullet.setSpeed(speed);\n// bullet.speed = speed;\n
  • Get
    var speed = bullet.speed;\n
"},{"location":"bullet/#set-wrap-mode","title":"Set wrap mode","text":"
bullet.setWrapMode(wrap, padding);\n
  • wrap : Set true to enable wrap mode.
"},{"location":"bullet/#angle","title":"Angle","text":"
  • Set angle
    bullet.setAngle(degrees);\n// bullet.angle = degrees;\n
    or
    bullet.setRotation(radians);\n// bullet.rotation  = radians;\n
  • Use angle of game object
    bullet.setAngle();\n// bullet.setRotation();\n
"},{"location":"button/","title":"Click/Button","text":""},{"location":"button/#introduction","title":"Introduction","text":"

Fires 'click' event when touch releasd after pressed.

  • Author: Rex
  • Behavior of game object
"},{"location":"button/#usage","title":"Usage","text":"

Sample code

"},{"location":"button/#install-plugin","title":"Install plugin","text":""},{"location":"button/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbuttonplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbuttonplugin.min.js', true);\n
  • Add button behavior
    var button = scene.plugins.get('rexbuttonplugin').add(gameObject, config);\n
"},{"location":"button/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ButtonPlugin from 'phaser3-rex-plugins/plugins/button-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexButton',\nplugin: ButtonPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add button behavior
    var button = scene.plugins.get('rexButtonn').add(gameObject, config);\n
"},{"location":"button/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Button from 'phaser3-rex-plugins/plugins/button.js';\n
  • Add button behavior
    var button = new Button(gameObject, config);\n
"},{"location":"button/#create-instance","title":"Create instance","text":"
var button = scene.plugins.get('rexButton').add(gameObject, {\n// enable: true,\n// mode: 1,              // 0|'press'|1|'release'\n// clickInterval: 100    // ms\n// threshold: undefined\n});\n
  • enable : Clickable.
  • mode :
    • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
    • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
  • clickInterval : Interval between 2 'click' events, in ms.
  • threshold : Cancel clicking detecting when dragging distance is larger then this threshold.
    • undefined : Ignore this feature. Default behavior.
"},{"location":"button/#events","title":"Events","text":"
  • Click
    button.on('click', function (button, gameObject, pointer, event) {\n// ...\n}, scope);\n
    • Cancel remaining touched events : event.stopPropagation()
  • Enable
    button.on('enable', function (button, gameObject) {\n// ...\n}, scope);\n
  • Disable
    button.on('disable', function (button, gameObject) {\n// ...\n}, scope);\n
  • Pointer over
    button.on('over', function (button, gameObject, pointer, event) {\n// ...\n}, scope);\n
  • Pointer out
    button.on('out', function (button, gameObject, pointer, event) {\n// ...\n}, scope);\n
  • Pointer down
    button.on('down', function (button, gameObject, pointer, event) {\n// ...\n}, scope);\n
  • Pointer up
    button.on('up', function (button, gameObject, pointer, event) {\n// ...\n}, scope);\n
"},{"location":"button/#enable","title":"Enable","text":"
  • Get
    var enabled = button.enable;  // enabled: true, or false\n
  • Set
    button.setEnable(enabled);  // enabled: true, or false\n// button.enable = enabled;\n
  • Toggle
    button.toggleEnable();\n
"},{"location":"button/#set-mode","title":"Set mode","text":"
button.setMode(mode);\n
  • mode :
    • 'press', or 0 : Fire 'click' event when touch pressed.
    • 'release', or 1 : Fire 'click' event when touch released after pressed.
"},{"location":"button/#set-click-interval","title":"Set click interval","text":"
button.setClickInterval(interval);  // interval in ms\n
"},{"location":"button/#set-dragging-threshold","title":"Set dragging threshold","text":"
button.setDragThreshold(distance);  // distance in pixels\n
"},{"location":"camera-controller/","title":"Controller","text":""},{"location":"camera-controller/#introduction","title":"Introduction","text":"

Scroll/zoom camera.

  • Author: Richard Davey
"},{"location":"camera-controller/#usage","title":"Usage","text":""},{"location":"camera-controller/#setup","title":"Setup","text":"
  1. Create controllor
    // var cursors = scene.input.keyboard.createCursorKeys();\nvar controls = new Phaser.Cameras.Controls.SmoothedKeyControl({\ncamera: camera,\n\nleft: cursors.left,    // { isDown, isUp }\nright: cursors.right,  // { isDown, isUp }\nup: cursors.up,        // { isDown, isUp }\ndown: cursors.down,    // { isDown, isUp }\nzoomIn: null,          // { isDown, isUp }\nzoomOut: null,         // { isDown, isUp }\n\nzoomSpeed: 0.01,\nminZoom: 0.001,\nmaxZoom: 1000,\n\nacceleration: null,\n// acceleration: {\n//    x: 0,\n//    y: 0\n// }\n\ndrag: null,\n// drag: {\n//    x: 0,\n//    y: 0\n// }\n\nmaxSpeed: null\n// maxSpeed: {\n//    x: 0,\n//    y: 0\n// }\n});\n
    or
    var controls = new Phaser.Cameras.Controls.FixedKeyControl(config);\n
  2. Update
    scene.update = function (time, delta) {\ncontrols.update(delta);\n}\n
"},{"location":"camera-controller/#other-methods","title":"Other methods","text":"
  • Start
    controls.start();\n
  • Stop
    controls.stop();\n
  • Set camera
    controls.setCamera(camera);\n
"},{"location":"camera-effects/","title":"Effects","text":""},{"location":"camera-effects/#introduction","title":"Introduction","text":"

Effects of camera.

  • Author: Richard Davey
"},{"location":"camera-effects/#usage","title":"Usage","text":""},{"location":"camera-effects/#fade","title":"Fade","text":"
  • Fades the Camera in, from the given color over the duration specified.
    camera.fadeIn(duration);   // duration in ms\n// camera.fadeIn(duration, red, green, blue, callback, context);\n// red/green/blue: the value to fade the red/green/blue channel from. A value between 0 and 255.\n
    • callback , context : It will be invoked every frame for the duration of the effect.
      function(camera, progress) {}\n
  • Fades the Camera out, to the given color over the duration specified.
    camera.fadeOut(duration);   // duration in ms\n// camera.fadeOut(duration, red, green, blue, callback, context);\n
    • callback , context : It will be invoked every frame for the duration of the effect.
      function(camera, progress) {}\n
  • Fades the Camera, from the given color to transparent over the duration specified.
    camera.fadeFrom(duration);   // duration in ms\n// camera.fadeFrom(duration, red, green, blue, force, callback, context);\n
    • force : Force the effect to start immediately, even if already running.
    • callback , context : It will be invoked every frame for the duration of the effect.
      function(camera, progress) {}\n
  • Fades the Camera, from transparent to the given color over the duration specified.
    camera.fade(duration);   // duration in ms\n// camera.fade(duration, red, green, blue, force, callback, context);\n
    • force : Force the effect to start immediately, even if already running.
    • callback , context : It will be invoked every frame for the duration of the effect.
      function(camera, progress) {}\n
"},{"location":"camera-effects/#events","title":"Events","text":"
camera.on('camerafadeincomplete', camera, fade);\n
camera.on('camerafadeoutcomplete', camera, fade);\n
"},{"location":"camera-effects/#flash","title":"Flash","text":"
camera.flash(duration);   // duration in ms\n// camera.flash(duration, red, green, blue, force, callback, context);\n
  • callback , context : It will be invoked every frame for the duration of the effect.
    function(camera, progress) {}\n
"},{"location":"camera-effects/#events_1","title":"Events","text":"
camera.on('cameraflashstart', camera, flash, duration, red, green, blue);\n
camera.on('cameraflashcomplete', camera, flash);\n
"},{"location":"camera-effects/#shake","title":"Shake","text":"
camera.shake(duration);   // duration in ms\n// camera.shake(duration, intensity, force, callback, context);  // callback: invoked when completed\n
  • callback , context : It will be invoked every frame for the duration of the effect.
    function(camera, progress) {}\n
"},{"location":"camera-effects/#events_2","title":"Events","text":"
camera.on('camerashakestart', camera, shake, duration, intensity);\n
camera.on('camerashakecomplete', camera, shake);\n
"},{"location":"camera-effects/#pan","title":"Pan","text":"
camera.pan(x, y, duration);   // duration in ms\n// camera.pan(x, y, duration, ease, force, callback, context);\n
  • x, y : The destination x/y coordinate to scroll the center of the Camera viewport to.
  • callback , context : It will be invoked every frame for the duration of the effect.
    function(camera, progress, x, y) {}\n
"},{"location":"camera-effects/#events_3","title":"Events","text":"
camera.on('camerapanstart', camera, pan, duration, x, y);\n
camera.on('camerapancomplete', camera, pan);\n
"},{"location":"camera-effects/#zoom","title":"Zoom","text":"
camera.zoomTo(zoomValue, duration);   // duration in ms\n// camera.zoomTo(zoomValue, duration, ease, force, callback, context);\n
  • callback , context : It will be invoked every frame for the duration of the effect.
    function(camera, progress, zoomValue) {}\n
"},{"location":"camera-effects/#events_4","title":"Events","text":"
camera.on('camerazoomstart', camera, zoom, duration, zoomValue);\n
camera.on('camerazoomcomplete', camera, zoom);\n
"},{"location":"camera-effects/#rotate-to","title":"Rotate to","text":"
camera.rotateTo(radians, shortestPath, duration);   // duration in ms\n// camera.rotateTo(radians, shortestPath, duration, ease, force, callback, context);\n
  • callback , context : It will be invoked every frame for the duration of the effect.
    function(camera, progress, angle) {}\n
"},{"location":"camera-effects/#events_5","title":"Events","text":"
camera.on('camerarotatestart', camera, rotateTo, duration, angle);\n
camera.on('camerarotatecomplete', camera, rorotateTotate);\n
"},{"location":"camera-effects/#mask","title":"Mask","text":"
  • Add mask
    camera.setMask(mask);\n
  • Clear mask
    camera.clearMask();\n

More detail about mask

"},{"location":"camera-shader-effect/","title":"Shader effect","text":""},{"location":"camera-shader-effect/#introduction","title":"Introduction","text":"

Shader effect of camera.

  • Author: Richard Davey
"},{"location":"camera-shader-effect/#usage","title":"Usage","text":""},{"location":"camera-shader-effect/#register-post-fx-pipeline","title":"Register post-fx pipeline","text":"
  • Register post-fx pipeline in game config
    import PostFxClass from 'path';\nvar config = {\n// ...\npipeline: [PostFxClass]\n// ...\n};\nvar game = new Phaser.Game(config);\n

Some post-fx pipelines:

  • Barrel: Barrel post processing filter.
  • Color replace: Replace color post processing filter.
  • Cross-stitching: Cross-stitching post processing filter.
  • CRT: CRT post processing filter.
  • Dissolve: Dissolve transition post processing filter.
  • Fish eye: Fish-eye post processing filter.
  • Glow-filter: Glow post processing filter.
  • Glow-filter: Glow post processing filter, ported from pixi.
  • Gray-scale: Gray scale post processing filter.
  • Hsl-adjust: Adjust color in HSL domain, post processing filter.
  • Horri-fi: 6-in-1 post processing filter.
  • Inverse: Inverse color post processing filter.
  • Kawase-blur: Kawase-blur post processing filter.
  • Pixelation: Pixelation post processing filter.
  • Toonify: Draw outlines and quantize color in HSV domain, post processing filter.
  • Shockwave: Shockwave post processing filter.
  • Split: Split image into 4 parts.
  • Swirl: Swirl post processing filter.
  • Warp: Warp post processing filter.
"},{"location":"camera-shader-effect/#add-post-fx-pipeline","title":"Add post-fx pipeline","text":"
camera.setPostPipeline(PostFxClass);\n
  • PostFxClass : Class of post-fx pipeline.
"},{"location":"camera-shader-effect/#remove-post-fx-pipeline","title":"Remove post-fx pipeline","text":"
  • Remove a kind of post-fx pipeline
    camera.removePostPipeline(PostFxClass);\n
  • Remove all post-fx pipelines
    camera.resetPipeline(true);\n
    or
    camera.postPipelines = [];\ncamera.hasPostPipeline = false;\n
"},{"location":"camera-shader-effect/#get-post-fx-pipeline","title":"Get post-fx pipeline","text":"
var pipelineInstance = camera.getPostPipeline(PostFxClass);\n
  • pipelineInstance :
    • A pipeline instance
    • An array of pipeline instances
"},{"location":"camera-shader-effect/#add-effect-properties","title":"Add effect properties","text":"

See Add effect properties behavior

"},{"location":"camera/","title":"Camera","text":""},{"location":"camera/#introduction","title":"Introduction","text":"

Camera to display game objects, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"camera/#usage","title":"Usage","text":""},{"location":"camera/#get-camera","title":"Get camera","text":"

Each scene has one or more cameras.

  • Main camera
    var camera = scene.cameras.main;\n
  • Get camera by name
    var camera = scene.cameras.getCamera(name);\n
  • Add new camera
    var camera = scene.cameras.add();\n// var camera = scene.cameras.add(x, y, width, height);\n
  • Add new camera with name
    var camera = scene.cameras.add(undefined, undefined, undefined, undefined, false, name);\n// var camera = scene.cameras.add(x, y, width, height, makeMain, name);\n
  • Add existed camera
    scene.cameras.addExisting(camera);\n
"},{"location":"camera/#create-cameras-from-json","title":"Create cameras from JSON","text":"
scene.cameras.fromJSON(config);\n// scene.cameras.fromJSON(configArray);\n
  • config :
    {\nname: '',\nx: 0,\ny: 0,\nwidth: scene.sys.scale.width,\nheight: scene.sys.scale.height,\nzoom: 1,\nrotation: 0,\nscrollX: 0,\nscrollY: 0,\nroundPixels: false,\nvisible: true,\nbackgroundColor: false,\nbounds: null, // {x, y, width, height}\n}\n
"},{"location":"camera/#remove-camera","title":"Remove camera","text":"
scene.cameras.remove(camera);\n
"},{"location":"camera/#destroy-camera","title":"Destroy camera","text":"
camera.destroy();\n
"},{"location":"camera/#view-port","title":"View port","text":"
  • Set
    camera.setViewport(top, left, width, height);\n
    or
    camera.setPosition(top, left);\n// camera.x = top;\n// camera.y = left;\n
    camera.setSize(width, height);\n// camera.width = width;\n// camera.height = height;\n
  • Get
    • Position
      • Top-left
        var top = camera.x;\nvar left = camera.y;\n
      • Center, relative to the top-left of the game canvas.
        var x = camera.centerX;\nvar y = camera.centerY;\n
    • Width & height
      var width = camera.width;\nvar height = camera.height;\n
      var displayWidth = camera.displayWidth;\nvar displayHeight = camera.displayHeight;\n
"},{"location":"camera/#zoom","title":"Zoom","text":"
  • Set
    camera.setZoom(zoomValue);  // The minimum it can be is 0.001.\ncamera.zoom = zoomValue;\n
  • Get
    var zoomValue = camera.zoom;\n
"},{"location":"camera/#rotation","title":"Rotation","text":"
  • Set
    camera.setAngle(angle);  // angle in degree\ncamera.setRotation(angle);  // angle in radians\ncamera.rotation = angle; // angle in radians\n
  • Get
    var angle = camera.rotation;  // angle in radians\n
"},{"location":"camera/#origin","title":"Origin","text":"
  • Set
    camera.setOrigin(x, y);\n// camera.originX = 0.5;\n// camera.originY = 0.5;\n
  • Get
    var originX = camera.originX\nvar originY = camera.originY\n
"},{"location":"camera/#visible","title":"Visible","text":"

A visible camera will render and perform input tests. An invisible camera will not render anything and will skip input tests.

camera.setVisible(value);\n// camera.visible = value\n
var visible = camera.visible;\n
"},{"location":"camera/#alpha","title":"Alpha","text":"
camera.setAlpha(value);\n// camera.alpha = value;\n
var alpha = camera.alpha;\n
"},{"location":"camera/#scroll","title":"Scroll","text":"
camera.setScroll(x, y)\n
camera.scrollX = scrollX;\ncamera.scrollY = scrollY;\n
camera.centerToBounds();\n
camera.centerOn(x, y);  // centered on the given coordinates\n
camera.centerOnX(x);\ncamera.centerOnY(y);\n
camera.centerToSize();\n
"},{"location":"camera/#follow-game-object","title":"Follow game object","text":"
  • Start following
    camera.startFollow(gameObject);\n// camera.startFollow(gameObject, roundPx, lerpX, lerpY, offsetX, offsetY);  // \n
    • roundPx : set true to round the camera position to integers
    • lerpX, lerpY : A value between 0 and 1.
      • 1 : Camera will instantly snap to the target coordinates.
      • 0.1 : Camera will more slowly track the target, giving a smooth transition.
    • offsetX, offsetY : The horizontal/vertical offset from the camera follow target.x position.
  • Stop following
    camera.stopFollow();\n
  • Set follow offset
    camera.setFollowOffset(x, y);\n
  • Set lerp
    camera.setLerp(x, y);\n
    • 1 : Camera will instantly snap to the target coordinates.
    • 0.1 : Camera will more slowly track the target, giving a smooth transition.
  • Deadzone
    camera.setDeadzone(width, height);\n
    If the target moves outside of this area, the camera will begin scrolling in order to follow it.
    • Boundaries
      var left = camera.deadzone.left;\nvar right = camera.deadzone.right;\nvar top = camera.deadzone.top;\nvar bootom = camera.deadzone.bottom;\n
    • Clear deadzone
      camera.setDeadzone();\n
"},{"location":"camera/#events","title":"Events","text":"
  • Follower Update
    camera.on('followupdate', function(camera, gameObject){ })\n
"},{"location":"camera/#scroll-factor","title":"Scroll factor","text":"

See Scroll factor in game object.

"},{"location":"camera/#bounds","title":"Bounds","text":"
  • Set
    camera.setBounds(x, y, width, height)\n
  • Get
    var bounds = camera.getBounds();  // bounds: a rectangle object\n// var out = camera.getBounds(out);\n
"},{"location":"camera/#world-coordinates","title":"World coordinates","text":"
  • World view, a rectangle object
    var worldView = camera.worldView;\nvar x = worldView.x;\nvar y = worldView.y;\nvar width = worldView.width;  // displayWidth\nvar height = worldView.height; // displayHeight\nvar left = worldView.left;  // x\nvar right = worldView.right;  // x + width\nvar top = worldView.top;  // y\nvar bottom = worldView.bottom;  // y + height\nvar centerX = worldView.centerX;\nvar centerY = worldView.centerY;\nvar isInside = worldView.contains(x, y);\nvar randPoint = worldView.getRandomPoint(point); // point: {x, y}\n
  • Middle point
    var x = camera.midPoint.x;\nvar y = camera.midPoint.y;\n
  • Get world position
    var out = camera.getWorldPoint(x, y);\n// var out = camera.getWorldPoint(x, y, out);\n
    • x , y : Position of camera.
    • out : World position {x, y}
"},{"location":"camera/#set-background-color","title":"Set background color","text":"
camera.setBackgroundColor(color);\n
"},{"location":"camera/#ignore-game-object","title":"Ignore game object","text":"

Ignored game objects won't show at that camera.

camera.ignore(gameObject);\n
  • gameObject :
    • A game object
    • An array of game objects
    • A group
"},{"location":"camera/#get-cameras-below-pointer","title":"Get cameras below pointer","text":"
var cameras = scene.cameras.getCamerasBelowPointer(pointer);\n
  • cameras : An array of cameras.
  • pointer : {x, y}
"},{"location":"camera/#pause-resume","title":"Pause, resume","text":"
  • Pause
    camera.renderToTexture = false; // Pause\n
  • Resume
    camera.renderToTexture = true; // Resume\n
"},{"location":"camera/#clear","title":"Clear","text":"
camera.clearRenderToTexture();\n
"},{"location":"camera/#children","title":"Children","text":""},{"location":"camera/#visible-children","title":"Visible children","text":"
  • Filter visible children
    var visible = scene.cameras.getVisibleChildren(children, camera);\n
  • Get all visible children
    var visible = scene.cameras.getVisibleChildren(scene.sys.displayList.list, camera);\n

See also: gameObject.willRender(camera)

"},{"location":"camera/#render-children","title":"Render children","text":"
var children = camera.renderList;\n

Read only.

"},{"location":"canvas-circularprogress/","title":"Circular progres","text":""},{"location":"canvas-circularprogress/#introduction","title":"Introduction","text":"

Circular progress bar on canvas.

  • Author: Rex
  • Game object
"},{"location":"canvas-circularprogress/#live-demos","title":"Live demos","text":"
  • Circular-progress
"},{"location":"canvas-circularprogress/#usage","title":"Usage","text":"

Sample code

"},{"location":"canvas-circularprogress/#install-plugin","title":"Install plugin","text":""},{"location":"canvas-circularprogress/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcircularprogresscanvasplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcircularprogresscanvasplugin.min.js', true);\n
  • Add circular-progress object
    var circularProgress = scene.add.rexCircularProgressCanvas(x, y, radius, color, value, config);\n
"},{"location":"canvas-circularprogress/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CircularProgressCanvasPlugin from 'phaser3-rex-plugins/plugins/circularprogresscanvas-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCircularProgressCanvasPlugin',\nplugin: CircularProgressCanvasPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add circular-progress object
    var circularProgress = scene.add.rexCircularProgressCanvas(x, y, radius, color, value, config);\n
"},{"location":"canvas-circularprogress/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CircularProgressCanvas from 'phaser3-rex-plugins/plugins/circularprogresscanvas.js';\n
  • Add circular-progress object
    var circularProgress = new CircularProgressCanvas(scene, x, y, radius, color, value, config);\nscene.add.existing(image);\n
"},{"location":"canvas-circularprogress/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCircularProgressCanvasPlugin',\nplugin: CircularProgressCanvasPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"canvas-circularprogress/#create-instance","title":"Create instance","text":"
var circularProgress = scene.add.rexCircularProgressCanvas(x, y, radius, barColor, value, {\nbarColor2: undefined,\ntrackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nendAngle: Phaser.Math.DegToRad(270+360),\nanticlockwise: false,\n\ntextColor: undefined,\ntextStrokeColor: undefined,\ntextStrokeThickness: undefined,\n// textFont: ,\ntextSize: '16px',\ntextFamily: 'Courier',\ntextStyle: '',\ntextFormatCallback: undefined,\ntextFormatCallbackScope: undefined,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},\n});\n

or

var circularProgress = scene.add.rexCircularProgressCanvas({\nx: 0,\ny: 0,\nradius: 1,\n\nbarColor: undefined,\nbarColor2: undefined,\ntrackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nendAngle: Phaser.Math.DegToRad(270+360),\nanticlockwise: false,\n\ntextColor: undefined,\ntextStrokeColor: undefined,\ntextStrokeThickness: undefined,\n// textFont: ,\ntextSize: '16px',\ntextFamily: 'Courier',\ntextStyle: '',\ntextFormatCallback: undefined,\ntextFormatCallbackScope: undefined,\n\nvalue: 0,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},\n});\n
  • x, y : Position of this object.
  • radius : Radius of this circle. Size will be (radius*2, radius*2).
  • barColor, barColor2 : Fill color of circular bar, in number or css string value. Assign gradient start color by barColor2.
  • trackColor : Color of circular track, in number or css string value.
  • centerColor : Color of center circle, in number or css string value.
  • thickness : 0 ~ 1, thickness of circular bar. Default value is 0.2 (0.2*radius)
  • startAngle : Start angle of circular bar, in radians. Default value is 270 degrees.
  • endAngle : End angle of circular bar, in radians. Default value is 270+360 degrees.
  • anticlockwise : Set true to put anticlockwise circular bar. Default value is false.
  • textColor : Color of display text. Default is undefined.
  • textStrokeColor, textStrokeThickness : Stroke color, stroke line width of display text. Default is undefined.
  • textSize, textFamily, textStyle : Size, family, style of display text.
  • textFormatCallback, textFormatCallbackScope : Formating callback of display text. ex:
    function(value) {\nreturn Math.floor(value * 100).toString();\n}\n
    Default value is undefined.
  • value : 0 ~ 1, progress value. Default is 0.
  • easeValue : Parameters of easing value.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • valuechangeCallback : callback function when value changed.
    function(newValue, oldValue, circularProgress) {\n}\n

Add circular-progress from JSON

var circularProgress = scene.make.rexCircularProgressCanvas({\nx: 0,\ny: 0,\nradius: 1,\n\nbarColor: undefined,\nbarColor2: undefined,\ntrackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nendAngle: Phaser.Math.DegToRad(270+360),\nanticlockwise: false,\n\ntextColor: undefined,\ntextStrokeColor: undefined,\ntextStrokeThickness: undefined,\ntextSize: '16px',\ntextFamily: 'Courier',\ntextStyle: '',\ntextFormatCallback: undefined,\ntextFormatCallbackScope: undefined,\n\nvalue: 0,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},\n\nadd: true\n});\n
"},{"location":"canvas-circularprogress/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCircularProgressCanvas extends CircularProgressCanvas {\nconstructor(scene, x, y, radius, barColor, value, config) {\nsuper(scene, x, y, radius, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var circularProgress = new MyCircularProgressCanvas(scene, x, y, radius, color, value, config);\n
"},{"location":"canvas-circularprogress/#progress-value","title":"Progress value","text":"
  • Get value
    var value = circularProgress.getValue(min, max); // value : min ~ max\n
    or
    var value = circularProgress.getValue(); // value: 0 ~ 1\n
    or
    var value = circularProgress.value; // value: 0 ~ 1\n
  • Set value
    circularProgress.setValue(value, min, max); // value: min ~ max\n
    or
    circularProgress.setValue(value); // value: 0 ~ 1\n
    or
    circularProgress.value = value; // value: 0 ~ 1\n
  • Increase value
    circularProgress.addValue(inc, min, max); // inc: min ~ max\n
    or
    circularProgress.addValue(inc); // inc: 0 ~ 1\n
    or
    circularProgress.value += inc; // inc: 0 ~ 1\n
"},{"location":"canvas-circularprogress/#ease-progress-value","title":"Ease progress value","text":"
  • Ease value to
    circularProgress.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    circularProgress.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    circularProgress.stopEaseValue();\n
  • Set ease duration
    circularProgress.setEaseValueDuration(duration);\n
  • Set ease function
    circularProgress.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"canvas-circularprogress/#radius","title":"Radius","text":"
  • Get
    var radius = circularProgress.radius;\n
  • Set
    circularProgress.setRadius(radius);\n// circularProgress.radius = radius;\n
    • Also resize this game object to (radius*2, radius*2)
"},{"location":"canvas-circularprogress/#circular-track","title":"Circular track","text":"
  • Color
    • Get
      var trackColor = circularProgress.trackColor;\n
    • Set
      circularProgress.setTrackColor(trackColor);\n// circularProgress.trackColor = trackColor;\n
  • Thickness : radius*thickness
    circularProgress.setThickness(thickness);\n
    • thickness : 0~1.
"},{"location":"canvas-circularprogress/#circular-bar","title":"Circular bar","text":"
  • Color
    • Get
      var barColor = circularProgress.barColor;\n
    • Set
      circularProgress.setBarColor(color);\n// circularProgress.barColor = color;\n
  • Color2
    • Get
      var barColor2 = circularProgress.barColor2;\n
    • Set
      circularProgress.setBarColor2(color);\n// circularProgress.barColor2 = color;\n
  • Thickness : radius*thickness
    circularProgress.setThickness(thickness);\n
    • thickness : 0~1.
  • Start angle
    • Get
      var startAngle = circularProgress.startAngle;\n
    • Set
      circularProgress.setStartAngle(startAngle);\ncircularProgress.startAngle = startAngle;\n
      • startAngle : Start angle of circular bar, in radians.
  • End angle
    • Get
      var endAngle = circularProgress.endAngle;\n
    • Set
      circularProgress.setEndAngle(endAngle);\ncircularProgress.endAngle = endAngle;\n
      • endAngle : End angle of circular bar, in radians.
  • Anticlockwise
    • Get
      var anticlockwise = circularProgress.anticlockwise;\n
    • Set
      circularProgress.setAnticlockwise(anticlockwise);\n// circularProgress.anticlockwise = anticlockwise;\n
"},{"location":"canvas-circularprogress/#center-circle","title":"Center circle","text":"
  • Color
    • Get
      var centerColor = circularProgress.centerColor;\n
    • Set
      circularProgress.setCenterColor(centerColor);\n// circularProgress.centerColor = centerColor;\n
"},{"location":"canvas-circularprogress/#display-text","title":"Display text","text":"
  • Fill color
    circularProgress.setTextColor(color);\n
  • Stroke color
    circularProgress.setTextStrokeColor(color, thickness);\n
  • Font
    circularProgress.setTextFont(fontSize, fontFamily, fontStyle);\n
  • Format callback
    circularProgress.setTextFormatCallback(callback, scope);\n
    • callback :
      function(value) {\nreturn Math.floor(value * 100).toString(); }\n
"},{"location":"canvas-circularprogress/#events","title":"Events","text":"
  • On value changed
    circularProgress.on('valuechange', function(newValue, oldValue, circularProgress){\n//\n}, scope);\n
"},{"location":"canvas-circularprogress/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"canvas-circularprogress/#create-mask","title":"Create mask","text":"
var mask = circularProgress.createBitmapMask();\n

See mask

"},{"location":"canvas-circularprogress/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"canvas-circularprogress/#compare-with-circular-progress-shape","title":"Compare with Circular-progress shape","text":"
  • Circular-progress canvas creates a canvas then draw on that canvas, circular progress shape draw on GRAPHICS pipeline like Shape or Graphics game object.
  • Circular-progress canvas can draw text directly, circular progress shape can't draw any text.
"},{"location":"canvas-data/","title":"Canvas image data","text":""},{"location":"canvas-data/#introduction","title":"Introduction","text":"

Get image data from texture, or text object.

  • Author: Rex
  • Method only
"},{"location":"canvas-data/#live-demos","title":"Live demos","text":"
  • Text to bit-map
  • Texture to color-map
"},{"location":"canvas-data/#usage","title":"Usage","text":"

Sample code

"},{"location":"canvas-data/#install-plugin","title":"Install plugin","text":""},{"location":"canvas-data/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcanvasdataplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcanvasdataplugin.min.js', true);\n
  • Add canvas-data object
    var canvasData = scene.plugins.get('rexcanvasdataplugin').canvasObjectToBitmap(gameObject);\nvar canvasData = scene.plugins.get('rexcanvasdataplugin').textureTColorMap(textureKey, frameName);\n
"},{"location":"canvas-data/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CanvasDataPlugin from 'phaser3-rex-plugins/plugins/canvasdata-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCanvasData',\nplugin: CanvasDataPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add canvas-data object
    var canvasData = scene.plugins.get('rexCanvasData').canvasObjectToBitmap(gameObject);\nvar canvasData = scene.plugins.get('rexCanvasData').textureTColorMap(textureKey, frameName);\n
"},{"location":"canvas-data/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CanvasData from 'phaser3-rex-plugins/plugins/canvasdata.js';\n
  • Add canvas-data object
    var canvasdata = CanvasData.canvasObjectToBitmap(gameObject);\nvar canvasdata = CanvasData.textureTColorMap(textureKey, frameName);\n
"},{"location":"canvas-data/#textcanvas-object-bitmap","title":"Text/canvas object -> Bitmap","text":"
var canvasData = scene.plugins.get('rexCanvasData').canvasObjectToBitmap(gameObject);\n// var out = scene.plugins.get('rexCanvasData').canvasObjectToBitmap(gameObject, out);\n
  • gameObject :
    • Any kind of text object : Text object, bbcode text object, or tag text object.
    • Canvas object
  • For each pixel data
    canvasData.forEach(function(value, x, y, canvasData){\n\n}, scope);\n
    • value : true, or false
"},{"location":"canvas-data/#texture-color-map","title":"Texture -> Color map","text":"
  • Texture -> Color map
    var canvasData = scene.plugins.get('rexCanvasData').textureTColorMap(textureKey, frameName);\n// var out = scene.plugins.get('rexCanvasData').canvasObjectToBitmap(textureKey, frameName, out);\n
  • Texture of game object -> Color map
    var canvasData = scene.plugins.get('rexCanvasData').textureTColorMap(gameObject);\n// var out = scene.plugins.get('rexCanvasData').canvasObjectToBitmap(gameObject, out);\n
  • For each pixel data
    canvasData.forEach(function(value, x, y, canvasData){\n\n}, scope);\n
    • value : Color32 integer = color integer + (alpha << 24)
      • Get color integer (0 ~ 0xffffff)
        var color = value & 0xffffff;\n
        or
        var color = canvasData.color32ToColorInt(value);\n
      • Get alpha (0 ~ 0xff)
        var alpha = value >>> 24;\n
        var alpha = canvasData.color32ToAlpha(value);\n
"},{"location":"canvas-data/#canvas-data","title":"Canvas data","text":""},{"location":"canvas-data/#for-each-pixel","title":"For each pixel","text":"
  • For each pixel data
    canvasData.forEach(callback, scope);\n
    • callback : Callback for each pixel
      function(value, x, y, canvasData) {\n\n}\n
  • For each non zero pixel data
    canvasData.forEachNonZero(callback, scope);\n
"},{"location":"canvas-data/#get-pixel-data","title":"Get pixel data","text":"
var data = canvasData.get(x, y);\n
  • data :
    • true, or false in result of canvasObjectToBitmap method
    • Color32 in result of textureTColorMap method
"},{"location":"canvas-data/#size","title":"Size","text":"
var width = canvasData.width;\nvar height = canvasData.height;\n
"},{"location":"canvas-lineprogress/","title":"Line progres","text":""},{"location":"canvas-lineprogress/#introduction","title":"Introduction","text":"

Horizontal line progress bar filled with gradient color on canvas.

  • Author: Rex
  • Game object
"},{"location":"canvas-lineprogress/#live-demos","title":"Live demos","text":"
  • Line-progress
"},{"location":"canvas-lineprogress/#usage","title":"Usage","text":"

Sample code

"},{"location":"canvas-lineprogress/#install-plugin","title":"Install plugin","text":""},{"location":"canvas-lineprogress/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlineprogresscanvasplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlineprogresscanvasplugin.min.js', true);\n
  • Add line-progress object
    var lineProgress = scene.add.rexLineProgressCanvas(x, y, width, height, barColor, value, config);\n
"},{"location":"canvas-lineprogress/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LineProgressCanvasPlugin from 'phaser3-rex-plugins/plugins/lineprogresscanvas-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLineProgressCanvasPlugin',\nplugin: LineProgressCanvasPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add line-progress object
    var lineProgress = scene.add.rexLineProgressCanvas(x, y, width, height, barColor, value, config);\n
"},{"location":"canvas-lineprogress/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LineProgressCanvas from 'phaser3-rex-plugins/plugins/lineprogresscanvas.js';\n
  • Add line-progress object
    var lineProgress = new LineProgressCanvas(scene, x, y, width, height, barColor, value, config);\nscene.add.existing(image);\n
"},{"location":"canvas-lineprogress/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLineProgressCanvasPlugin',\nplugin: LineProgressCanvasPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"canvas-lineprogress/#create-instance","title":"Create instance","text":"
var lineProgress = scene.add.rexLineProgressCanvas(x, y, width, height, barColor, value, {    barColor2: undefined,\nisHorizontalGradient: true,\ntrackColor: undefined,\ntrackStrokeColor: undefined,\ntrackStrokeThickness: 2,\n\nskewX:0,\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, lineProgress) {\n},\n});\n

or

var lineProgress = scene.add.rexLineProgressCanvas({\nx: 0,\ny: 0,\nwidth: 2,\nheight: 2,\n\nbarColor: undefined,\nbarColor2: undefined,\nisHorizontalGradient: true,\ntrackColor: undefined,\ntrackStrokeColor: undefined,\ntrackStrokeThickness: 2,\n\nskewX:0,\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvalue: 0,\nvaluechangeCallback: function(newValue, oldValue, lineProgress) {\n},\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • barColor, barColor2, isHorizontalGradient : Fill color of line bar, in number or css string value. Assign gradient start color by barColor2.
  • trackColor : Fill color of line track, in number or css string value.
  • trackStrokeColor : Stroke color of track, in number or css string value.
  • trackStrokeThickness : Stroke line width of track.
  • skewX : Horizontal skew of track and bar.
  • rtl :
    • false : Bar starts from left side. Default behavior.
    • true : Bar starts from right side.
  • value : 0 ~ 1, progress value. Default is 0.
  • easeValue : Parameters of easing value.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • valuechangeCallback : callback function when value changed.
    function(newValue, oldValue, lineProgress) {\n}\n

Add line-progress from JSON

var lineProgress = scene.make.rexLineProgressCanvas({\nx: 0,\ny: 0,\nwidth: 2,\nheight: 2,\n\nbarColor: undefined,\nbarColor2: undefined,\nisHorizontalGradient: true,\ntrackColor: undefined,\ntrackStrokeColor: undefined,\ntrackStrokeThickness: 2,\n\nskewX:0,\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvalue: 0,\nvaluechangeCallback: function(newValue, oldValue, lineProgress) {\n},\n\nadd: true\n});\n
"},{"location":"canvas-lineprogress/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLineProgressCanvas extends LineProgressCanvas {\nconstructor(scene, x, y, width, height, barColor, value, config) {\nsuper(scene, x, y, width, height, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var lineProgress = new MyLineProgressCanvas(scene, x, y, width, height, barColor, value, config);\n
"},{"location":"canvas-lineprogress/#progress-value","title":"Progress value","text":"
  • Get value
    var value = lineProgress.getValue(min, max); // value : min ~ max\n
    or
    var value = lineProgress.getValue(); // value: 0 ~ 1\n
    or
    var value = lineProgress.value; // value: 0 ~ 1\n
  • Set value
    lineProgress.setValue(value, min, max); // value: min ~ max\n
    or
    lineProgress.setValue(value); // value: 0 ~ 1\n
    or
    lineProgress.value = value; // value: 0 ~ 1\n
  • Increase value
    lineProgress.addValue(inc, min, max); // inc: min ~ max\n
    or
    lineProgress.addValue(inc); // inc: 0 ~ 1\n
    or
    lineProgress.value += inc; // inc: 0 ~ 1\n
"},{"location":"canvas-lineprogress/#ease-progress-value","title":"Ease progress value","text":"
  • Ease value to
    lineProgress.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    lineProgress.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    lineProgress.stopEaseValue();\n
  • Set ease duration
    lineProgress.setEaseValueDuration(duration);\n
  • Set ease function
    lineProgress.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"canvas-lineprogress/#line-track","title":"Line track","text":"
  • Color
    • Get
      var trackColor = lineProgress.trackColor;\n
    • Set
      lineProgress.setTrackColor(trackColor);\n// lineProgress.trackColor = trackColor;\n
  • Stroke
    • Get
      var trackStrokeColor = lineProgress.trackStrokeColor;\nvar trackStrokeThickness = lineProgress.trackStrokeThickness;\n
    • Set
      lineProgress.setTrackColor(color);\nlineProgress.setTrackStroke(lineWidth, color);\n
"},{"location":"canvas-lineprogress/#line-bar","title":"Line bar","text":"
  • Color
    • Get
      var barColor = lineProgress.barColor;\nvar barColor2 = lineProgress.barColor2;\n
    • Set
      lineProgress.setBarColor(barColor, barColor2);\n// lineProgress.barColor = barColor;\n// lineProgress.barColor2 = barColor2;\n
"},{"location":"canvas-lineprogress/#horizontal-skew","title":"Horizontal skew","text":"
  • Get
    var skewX = lineProgress.skewX;\n
  • Set
    lineProgress.setSkewX(skewX);\n// lineProgress.skewX = skewX;\n
"},{"location":"canvas-lineprogress/#right-to-left","title":"Right-to-left","text":"
  • Get
    var rtl = lineProgress.rtl;\n
  • Set
    lineProgress.setRTL(rtl);\n// lineProgress.rtl = rtl;\n
"},{"location":"canvas-lineprogress/#events","title":"Events","text":"
  • On value changed
    lineProgress.on('valuechange', function(newValue, oldValue, lineProgress){\n//\n}, scope);\n
"},{"location":"canvas-lineprogress/#alpha","title":"Alpha","text":"
  • Get
    var alpha = lineProgress.alpha;\n
  • Set
    lineProgress.setAlpha(alpha);\n// lineProgress.alpha = alpha;\n
"},{"location":"canvas-lineprogress/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"canvas-lineprogress/#create-mask","title":"Create mask","text":"
var mask = lineProgress.createBitmapMask();\n

See mask

"},{"location":"canvas-lineprogress/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"canvas-lineprogress/#compare-with-line-progress-shape","title":"Compare with Line-progress shape","text":"
  • Line-progress canvas creates a canvas then draw on that canvas, line progress shape draw on GRAPHICS pipeline like Shape or Graphics game object.
  • Line-progress canvas can fill gradient color, line progress shape only can fill 1 color.
"},{"location":"canvas-roundrectangle/","title":"Round rectangle","text":""},{"location":"canvas-roundrectangle/#introduction","title":"Introduction","text":"

Round rectangle on canvas.

  • Author: Rex
  • Game object
"},{"location":"canvas-roundrectangle/#live-demos","title":"Live demos","text":"
  • Round rectangle
"},{"location":"canvas-roundrectangle/#usage","title":"Usage","text":"

Sample code

"},{"location":"canvas-roundrectangle/#install-plugin","title":"Install plugin","text":""},{"location":"canvas-roundrectangle/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexroundrectanglecanvasplugin', 'https://raw.githubusercontent.com/rexrainbow/    phaser3-rex-notes/master/dist/rexroundrectanglecanvasplugin.min.js', true);\n
  • Add shape object
    var rect = scene.add.rexRoundRectangleCanvas(x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
"},{"location":"canvas-roundrectangle/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RoundRectanglePlugin from 'phaser3-rex-plugins/plugins/roundrectanglecanvas-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRoundRectangleCanvasPlugin',\nplugin: RoundRectangleCanvasPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add shape object
    var rect = scene.add.rexRoundRectangleCanvas(x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
"},{"location":"canvas-roundrectangle/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RoundRectangleCanvas from 'phaser3-rex-plugins/plugins/roundrectanglecanvas.js';\n
  • Add shape object
    var rect = new RoundRectangleCanvas(scene, x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\nscene.add.existing(rect);\n
"},{"location":"canvas-roundrectangle/#create-shape-object","title":"Create shape object","text":"
var rect = scene.add.rexRoundRectangleCanvas(x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
  • width, height : Size of rectangle.
    • undefined : Set ot undefined to draw a circle.
  • radius : Radius of four corners.
    • 0, or undefined : Disable round corner.
    • Number: 4 corners with the same radius.
    • JSON
      • 4 corners with the same radius X/Y
        {\nx: radiusX,\ny: radiusY\n}\n
      • Eeach radius of corner
        {\ntl: radius,\ntr: radius,\nbl: radius,\nbr: radius\n}\n
        or
        {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n}\n
      • Radius and iteration
        {\nradius: radius,\niteration: 0\n}\n
        or
        {\nradius: {x: radiusX, y: radiusY},\niteration: 0\n}\n
        or
        {\nradius: {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n},\niteration: 0\n}\n
        • radius :
          • 0 : No round corner
          • > 0 : Convex round corner
          • < 0 : Concave round corner
        • iteration : Number of interpolation points in each round corner. Default value is 4.
          • 0 : Draw a straight line instead of arc.
  • fillStyle : Fill color in number or css string value, or a callback
    • Number, or css string value : Color value
    • Callback :
      function(canvas, context) {\n// Radial gradient\nvar grd = context.createRadialGradient(x0, y0, r0, x1, y1, r1);\ngrd.addColorStop(0, color0);\ngrd.addColorStop(1, color1);\nreturn grd;\n}\n
  • strokeStyle : Stroke color in number or css string value.
  • lineWidth : Stroke line width.
  • fillColor2 : Gradient color in number or css string value.
  • isHorizontalGradient :
    • true : Horizontal gradient.
    • false : Vertical gradient.

Note

If radius >= 0, draw convex corner, else draw concave corner

"},{"location":"canvas-roundrectangle/#deform","title":"Deform","text":"
  • Rectangle, set radius of 4 corners to 0.
    var rect = scene.add.rexRoundRectangleCanvas(x, y, width, height, 0, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
  • Circle, set width and height to 2*radius.
    var rect = scene.add.rexRoundRectangleCanvas(x, y, (2*radius), (2*radius), radius, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
  • Ellipse, set width and height to 2*radiusX, 2*radiusY.
    var rect = scene.add.rexRoundRectangleCanvas(x, y, (2*radiusX), (2*radiusX), {x: radiusX, y: radiusY}, fillColor, fillAlpha);\n
  • Rhombus, set width and height to 2*radius, and assign iteration to 0
    var rect = scene.add.rexRoundRectangleCanvas(x, y, (2*radius), (2*radius), {\nradius: radius,\niteration: 0\n}, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
  • Octagon, assign iteration to 0
    var rect = scene.add.rexRoundRectangleCanvas(x, y, width, height, {\nradius: radius,\niteration: 0\n}, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
"},{"location":"canvas-roundrectangle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyRoundRectangleCanvas extends RexPlugins.GameObjects.RoundRectangleCanvas {\nconstructor(scene, x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient) {\nsuper(scene, x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var rect = new MyRoundRectangleCanvas(scene, x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
"},{"location":"canvas-roundrectangle/#color","title":"Color","text":"
  • Fill color
    • Get
      var fillStyle = rect.fillStyle;\nvar fillColor2 = rect.fillColor2;\nvar isHorizontalGradient = rect.isHorizontalGradient;\n
    • Set
      rect.setFillStyle(fillStyle);\n// rect.setFillStyle(fillStyle, fillColor2, isHorizontalGradient);\n
      • fillStyle : Fill color in number or css string value, or a callback
        • Number, or css string value : Color value
        • Callback :
          function(canvas, context) {\n// Radial gradient\nvar grd = context.createRadialGradient(x0, y0, r0, x1, y1, r1);\ngrd.addColorStop(0, color0);\ngrd.addColorStop(1, color1);\nreturn grd;\n}\n
    • Clear
      rect.setFillStyle();\n
  • Stroke color
    • Get
      var strokeStyle = rect.strokeStyle;\nvar lineWidth = rect.lineWidth;\n
    • Set
      rect.setStrokeStyle(strokeStyle, lineWidth);\n
    • Clear
      rect.setStrokeStyle();\n
"},{"location":"canvas-roundrectangle/#size","title":"Size","text":"
  • Get
    var width = rect.width;\nvar height = rect.height;\n
  • Set
    rect.setSize(width, height);\n
    or
    rect.width = width;\nrect.height = height;\n
"},{"location":"canvas-roundrectangle/#radius","title":"Radius","text":"
  • Set
    rect.setRadius(value);\n
    or
    rect.radius = radius;\n
    • radius :
      • Number : 4 corners with the same radius.
        • 0 : No round corner
        • > 0 : Convex round corner
        • < 0 : Concave round corner
      • JSON
        • 4 corners with the same radius X/Y
          {\nx: radiusX,\ny: radiusY\n}\n
        • Eeach radius of corner
          {\ntl: radius,\ntr: radius,\nbl: radius,\nbr: radius\n}\n
          or
          {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n}\n
"},{"location":"canvas-roundrectangle/#iteration","title":"Iteration","text":"
  • Get
    var iteration = rect.iteration;\n
  • Set
    rect.setIteration(value);\n
    or
    rect.iteration = value;\n

Number of interpolation points in each round corner. Default value is 4.

  • 0 : Draw a straight line instead of arc.
"},{"location":"canvas-roundrectangle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"canvas-roundrectangle/#create-mask","title":"Create mask","text":"
var mask = rect.createBitmapMask();\n

See mask

"},{"location":"canvas-roundrectangle/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"canvas-roundrectangle/#compare-with-shape-roundrectangle","title":"Compare with Shape-Roundrectangle","text":"
  • Gradient
    • Canvas-RoundRectangle can fill with gradient color.
    • Shape-Roundrectangle can't fill gradient color.
  • Drawing method
    • Canvas-RoundRectangle draw shape on canvas, then map this canvas to frame buffer.
    • Shape-Roundrectangle draw shape on frame buffer directly without drawing to canvas first.
"},{"location":"canvas-texture/","title":"Canvas texture","text":""},{"location":"canvas-texture/#introduction","title":"Introduction","text":"

Canvas Canvas Texture stored in texture cache, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"canvas-texture/#usage","title":"Usage","text":""},{"location":"canvas-texture/#create-canvas-texture","title":"Create canvas texture","text":"
var texture = scene.textures.createCanvas(key, width, height);\n
"},{"location":"canvas-texture/#get-canvas-element","title":"Get canvas element","text":"
var canvas = texture.getCanvas();\nvar context = texture.getContext();\n

Canvas api

"},{"location":"canvas-texture/#draw-frame","title":"Draw frame","text":"
texture.drawFrame(key, frame, x, y);\n// texture.drawFrame(key, frame, x, y, update);\n
  • update : Update the internal ImageData buffer and arrays. Default value is true.
"},{"location":"canvas-texture/#draw-image","title":"Draw image","text":"
texture.draw(x, y, source);\n// texture.draw(x, y, source, update);\n
  • source : The HTML Image element, or HTML Canvas element to draw to this canvas.
  • update : Update the internal ImageData buffer and arrays. Default value is true.
"},{"location":"canvas-texture/#clear","title":"Clear","text":"
texture.clear();\n
texture.clear(x, y, width, height);\n// // texture.clear(x, y, width, height, update);\n
  • update : Update the internal ImageData buffer and arrays. Default value is true.
"},{"location":"canvas-texture/#refresh-texture","title":"Refresh texture","text":"
texture.refresh();\n
"},{"location":"canvas-texture/#color","title":"Color","text":"
  • Set
    texture.setPixel(x, y, red, green, blue);\n// texture.setPixel(x, y, red, green, blue, alpha);\n
  • Get
    var color = texture.getPixel(x, y);\n// var color = texture.getPixel(x, y, color);\n
    var colors = texture.getPixels(x, y, width, height);\n
    • colors : [{x, y, color, alpha}, ...]
"},{"location":"canvas-texture/#image-data","title":"Image data","text":"
  • Set
    texture.putData(imageData, x, y);\n
  • Get
    var imageData = texture.getData(x, y, width, height);\n
"},{"location":"canvas-texture/#add-frame","title":"Add frame","text":"
texture.add(name, sourceIndex, x, y, width, height);\n
  • name : The name of this Frame. The name is unique within the Texture.
  • sourceIndex : The index of the TextureSource that this Frame is a part of.
  • x : The x coordinate of the top-left of this Frame.
  • y : The y coordinate of the top-left of this Frame.
  • width : The width of this Frame.
  • height : The height of this Frame.
"},{"location":"canvas/","title":"Canvas","text":""},{"location":"canvas/#introduction","title":"Introduction","text":"

Drawing on canvas.

  • Author: Rex
  • Game object
"},{"location":"canvas/#live-demos","title":"Live demos","text":"
  • Kaleidoscope
  • chartjs
  • Resolution
"},{"location":"canvas/#usage","title":"Usage","text":"

Sample code

"},{"location":"canvas/#install-plugin","title":"Install plugin","text":""},{"location":"canvas/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcanvasplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcanvasplugin.min.js', true);\n
  • Add canvas object
    var canvas = scene.add.rexCanvas(x, y, width, height);\n
"},{"location":"canvas/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CanvasPlugin from 'phaser3-rex-plugins/plugins/canvas-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCanvasPlugin',\nplugin: CanvasPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add canvas object
    var canvas = scene.add.rexCanvas(x, y, width, height);\n
"},{"location":"canvas/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Canvas from 'phaser3-rex-plugins/plugins/canvas.js';\n
  • Add canvas object
    var canvas = new Canvas(scene, x, y, width, height);\nscene.add.existing(canvas);\n
"},{"location":"canvas/#create-instance","title":"Create instance","text":"
var canvas = scene.add.rexCanvas(x, y, width, height);\n// var canvas = scene.add.rexCanvas(x, y, width, height, resolution);\n

Add canvas from JSON

var canvas = scene.make.rexCanvas({\nx: 0,\ny: 0,\nwidth: 256,\nheight: 256,\n// resolution: 1,\n\n// origin: {x: 0.5, y: 0.5},\n// fill: null,\n\nadd: true\n});\n
  • resolution : The resolution the content is rendered to its internal canvas at. Default value is 1.
"},{"location":"canvas/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCanvas extends Canvas {\nconstructor(scene, x, y, width, height, resolution) {\nsuper(scene, x, y, width, height, resolution);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var canvas = new MyCanvas(scene, x, y, width, height, resolution);\n
"},{"location":"canvas/#clear-or-fill-canvas","title":"Clear or fill canvas","text":"
  • Clear
    canvas.clear();\n
  • Fill color
    canvas.fill(color);\n
"},{"location":"canvas/#update-canvas","title":"Update canvas","text":"
  1. Get canvas elemet
    var canvasElem = canvas.getCanvas();\nvar context = canvas.getContext();\n
    or
    var canvaesElem = canvas.canvas;\nvar context = canvas.context;\n
  2. Draw on context
"},{"location":"canvas/#update-display-texture","title":"Update display texture","text":"
  • Update texture when rendering
    canvas.needRedraw();\n
    or
    canvas.dirty = true;\n
  • Update texture now
    canvas.updateTexture();\n
    or update canvas and texture
    canvas.updateTexture(function(canvasElem, context) { });\n// canvas.updateTexture(callback, scope);\n
"},{"location":"canvas/#load-or-save-texture","title":"Load or save texture","text":"
  • Save canvas to texuture
    canvas.generateTexture(key);\n// canvas.generateTexture(key, x, y, width, height);\n
  • Copy canvas from texture
    canvas.loadTexture(key, frame);\n
"},{"location":"canvas/#paste-frame","title":"Paste frame","text":"
canvas.drawFrame(key, frame);\n// canvas.drawFrame(key, frame, dx, dy, dWidth, dHeight);\n// canvas.drawFrame(key, frame, dx, dy, dWidth, dHeight, sxOffset, syOffset, sWidth, sHeight);\n
  • dx, dy : Top-left position in this canvas. Default value is 0, 0.
  • dWidth, dHeight : The size to draw the image in this canvas. Default value is origin size of frame.
  • sxOffset, syOffset : Offset position of source frame. Default value is 0, 0
  • sWidth, sHeight : The size of the sub-rectangle of the source frame to draw into this canvas. Default value is origin size of frame.
"},{"location":"canvas/#data-url","title":"Data URL","text":"
  • Load image from URL
    canvas.loadFromURL(url);\n// canvas.loadFromURL(url, callback);\n
    or
    canvas.loadFromURLPromise(url)\n.then(function() {\n\n})\n
    • url : Image url/uri(base64 string)
    • callback : Load complete callback.
  • Get data URL of image
    var dataURL = canvas.getDataURL();\n// var dataURL = canvas.getDataURL(type, encoderOptions);\n
    • dataURL : A base64 string.
    • type : A DOMString indicating the image format. The default format type is image/png.
    • encoderOptions : A Number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp.
"},{"location":"canvas/#file","title":"File","text":"
  • Load image from File object
    canvas.loadFromFile(file);\n// canvas.loadFromFile(file, callback);\n
    or
    canvas.loadFromFilePromise(file)\n.then(function() {\n\n})\n
    • file : File object
    • callback : Load complete callback.
"},{"location":"canvas/#pixel-color","title":"Pixel color","text":"
  • Get color
    var color = canvas.getPixel(x, y);\n
    • color : Color object
      • color.red, color.green, color.blue, color.alpha
  • Set color
    canvas.setPixel(x, y, r, g, b);\n// canvas.setPixel(x, y, r, g, b, a);\n
    or
    canvas.setPixel(x, y, color);\n
    • r, g, b, a : Integer number between 0 ~ 255.
    • color : Color object
"},{"location":"canvas/#size","title":"Size","text":"
canvas.setCanvasSize(width, height);\n

or

canvas.setSize(width, height);\n

or

canvas.resize(width, height);\n
"},{"location":"canvas/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"canvas/#create-mask","title":"Create mask","text":"
var mask = canvas.createBitmapMask();\n

See mask

"},{"location":"canvas/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"canvas/#compare-with-graphics-object","title":"Compare with Graphics object","text":"
  • Drawing method
    • This canvas object draws stuff on canvas in WEBGL or CANVAS render mode.
    • Graphics object draws stuff on webgl render pipeline in WEBGL render mode.
  • Size
    • This canvas object has size (width, height) and origin.
    • Graphics object does not have size and origin.
"},{"location":"canvasinput/","title":"Canvas input","text":""},{"location":"canvasinput/#introduction","title":"Introduction","text":"

An invisible Input DOM element to receive character input and display on DynamicText.

Inspirited from CanvasInput.

  • Author: Rex
  • Game object
"},{"location":"canvasinput/#live-demos","title":"Live demos","text":"
  • Simple
  • Text input
  • Number input
  • With rexui-Label
  • Text area
"},{"location":"canvasinput/#usage","title":"Usage","text":"

Sample code

"},{"location":"canvasinput/#install-plugin","title":"Install plugin","text":""},{"location":"canvasinput/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcanvasinputplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcanvasinputplugin.min.js', true);\n
  • Add canvas-input object
    var txt = scene.add.rexCanvasInput(x, y, width, height, config);\n
"},{"location":"canvasinput/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CanvasInputPlugin from 'phaser3-rex-plugins/plugins/canvasinput-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCanvasInputPlugin',\nplugin: CanvasInputPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add canvas-input object
    var txt = scene.add.rexCanvasInput(x, y, width, height, config);\n
"},{"location":"canvasinput/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CanvasInput from 'phaser3-rex-plugins/plugins/canvasinput.js';\n
  • Add canvas-input object
    var txt = new CanvasInput(textGameObject, x, y, width, height, config);\nscene.add.existing(txt);\n
"},{"location":"canvasinput/#create-instance","title":"Create instance","text":"
var txt = scene.add.rexCanvasInput({\n// Parameters of DynamicText\nx: 0, y: 0,\nwidth: undefined, height: undefined,\nresolution: 1,\n\n// padding: 0,  // {left: 0, right: 0, top: 0, bottom: 0}\n\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null,\n\n// Style when focus\n// 'focus.color': ...\n// 'focus.color2': ...\n// 'focus.stroke': ...\n},\nfocusStyle: undefined,\n\ninnerBounds: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBY: undefined,\noffsetX: 0,\noffsetY: 0,\n\n// Style when cursor move on\n// 'cursor.color': ...\n// 'cursor.backgroundColor': ...\n// 'cursor.xxx': ...\n},\ncursorStyle: undefined,\n\nchildrenInteractive: false,\n\ntext: '',\n\nwrap: {\nlineHeight: undefined,\nuseDefaultLineHeight: true,\nmaxLines: 1,\nwrapWidth: undefined,\nletterSpacing: 0,\nwrapMode: 'char',  // 1|'word'|2|'char'|'character'|3|'mix', for single line text input\nhAlign: 0, // 0|'left'|1|'center'|2|'right'|3|'justify'|'justify-left'|4|'justify-center'|5| justify-right'\nvAlign: 'center',  // For single line text input        \n},\n\ntextArea: false,\n\n// Parameters of hidden-text-editor   \n// inputType: 'text',  // 'text'|'password'|'textarea'|...                \n\n// readOnly: false,\n// maxLength: undefined,\n// minLength: undefined,\n// selectAll: false,\n\n// enterClose: true,\n\n// Callbacks\n// onOpen: function (textObject, hiddenInputText) {\n// },\n\n// onClose: function (textObject, hiddenInputText) {\n// },\n\n// onUpdate: function (text, textObject, hiddenInputText) {\n//     return text;\n// },   \n\n// onAddChar: function(child, index, canvasInput) {\n//    child.modifyStyle({...})\n// },\n\n// onCursorOut: function(child, cursorIndex, canvasInput) {\n//     child.modifyStyle({\n//         \n//     });\n// },\n\n// onCursorIn: function(child, cursorIndex, canvasInput) {\n//     child.modifyStyle({\n//         \n//     });\n// },\n\n// parseTextCallback: function(text) {\n//     return text;\n// }.\n\n});\n
  • textArea :
    • false : Single line text input. Default behavior.
    • true : Multiple lines text input.
  • Parameters of DynamicText...
    • wrap : Some default value in wrap are changed
      • wrap.useDefaultLineHeight : Default value is true
      • wrap.maxLines : Default value is 1
      • wrap.vAlign : Default value is 'center'
  • Parameters of hidden-text-editor
    • inputType : Type of element
      • 'text', 'password', 'textarea', ...
    • enterClose : Set true to close input text when enter-key was pressed. Default value is true.
    • readOnly :
      • true : un-editable.
      • false : Editable. Defaule behavior.
    • maxLength, minLength : Maximun or minimun of input characters
    • selectAll : Set to true to select all characters when focusing.
  • Callbacks
    • onOpen : Callback invoked when focus on this hidden input text.
      function (textObject) {\n// textObject.setInputText(txt);\n}\n
    • onClose : Callback invoked when blur.
      function (textObject) {            }\n
    • onUpdate :
      • A callback invoked in each tick of editing.
        function (text, textObject) {\n// return text;\n}\n
        • Can return a new string for text game object displaying.
      • 'number' : Only output number string.
    • onAddChar : Callback invoked when adding new character child
      function(child, index, canvasInput) {\nchild.modifyStyle({...})\n}\n
      • child : character child
    • onCursorOut : Callback invoked when cursor move out of a character child
      function(child, index, canvasInput) {\nchild.modifyStyle({...})\n}\n
      • child : character child
    • onCursorIn : Callback invoked when cursor move on a character child
      function(child, index, canvasInput) {\nchild.modifyStyle({...})\n}\n
      • child : character child
    • parseTextCallback : Callback of parsing text (txt.text) to value (txt.value)
      • undefined : Bypass text to value. Default behavior.
      • A function object
        function(text) {\nreturn text;\n}\n
  • focusStyle : Will apply this style to background when focusing.
    • undefined : Ignore this behavior.
    • A plain object
      {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null,\n}\n
    • Or add these style settings in background parameter, with prefix 'focus.'.
  • cursorStyle : Will apply this style when cursor move on a character child.
    • undefined : Ignore this behavior.
    • A plain object
      {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBY: undefined,\noffsetX: 0,\noffsetY: 0\n}\n
    • Or add these style settings in style parameter, with prefix 'cursor.'.
"},{"location":"canvasinput/#number-input","title":"Number input","text":"
txt.setNumberInput();\n
"},{"location":"canvasinput/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCanvasInput extends CanvasInput {\nconstructor(textGameObject, x, y, width, height, config)) {\nsuper(textGameObject, x, y, width, height, config)) {\n// ...            \n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyCanvasInput(textGameObject, config);\n
"},{"location":"canvasinput/#open-editor","title":"Open editor","text":"
txt.open();\n

or

txt.open(onCloseCallback);\n
  • onCloseCallback : Callback invoked when closing text-editor
"},{"location":"canvasinput/#close-editor","title":"Close editor","text":"
txt.close();\n
"},{"location":"canvasinput/#is-opened","title":"Is opened","text":"
var isOpened = txt.isOpened;\n
"},{"location":"canvasinput/#text","title":"Text","text":"
  • Display text on dynamic text game object
    • Get
      var text = txt.text;\n
      or
      var text = txt.displayText;\n
    • Set
      txt.setText(text);\n
      or
      txt.setDisplayText(text);\n
  • Input text on hidden text edit behavior
    • Get
      var text = txt.inputText;\n
    • Set
      var text = txt.setInputText(text);\n
"},{"location":"canvasinput/#value","title":"Value","text":"
  • Get. Parse text to value.
    var value = txt.getValue();\n// var value = txt.value;\n
    • Set parseTextCallback
      txt.setParseTextCallback(callback);\n
      • callback :
        • undefined : Bypass text to value. Default behavior.
        • A function object
          function(text) {\nreturn text;\n}\n
  • Set. Conver any type of value to string.
    txt.setValue(value);\n// txt.value = value;\n
"},{"location":"canvasinput/#read-only","title":"Read only","text":"
  • Enable read only
    txt.setReadOnly();\n// txt.setReadOnly(true);\n
    or
    txt.readOnly = true;\n
  • Disable read only
    txt.setReadOnly(false);\n
    or
    txt.readOnly = false;\n
  • Get read only
    var readOnlyEanble = txt.readOnly;\n
"},{"location":"canvasinput/#size","title":"Size","text":"
  • Resize canvas size
    txt.setCanvasSize(width, height)\n
  • Reisze text wrapping size and canvas size.
    txt.setSize(width, height);\n
    or
    txt.setFixedSize(width, height);\n
  • Resize to minimun size to show all visible characters.
    txt.setToMinSize();\n
"},{"location":"canvasinput/#events","title":"Events","text":"
  • On text change
    txt.on('textchange', function(text, txt){\n})\n
  • On character child adding
    txt.on('addchar', function(child, index, canvasInput) {\nchild.modifyStyle({...})\n})\n
    • child : character child
  • On cursor moving out of a character child
    txt.on('cursorout', function(child, index, canvasInput) {\nchild.modifyStyle({...})\n})\n
    • child : character child
  • On cursor moving on a character child
    txt.on('cursorin', function(child, index, canvasInput) {\nchild.modifyStyle({...})\n})\n
    • child : character child
  • On open text-editor
    txt.on('open', function() {\n\n})\n
  • On close text-editor
    txt.on('close', function() {\n\n})\n
  • Close editor by ENTER key down
    txt.on('keydown-ENTER', function(){\n})\n
  • Not a number input
    txt.on('nan', function(text){\n\n})\n
"},{"location":"canvasinput/#select-text","title":"Select text","text":"

This feature does not support.

"},{"location":"canvasinput/#bypass-key-input","title":"Bypass key input","text":"

Registered keyboard events might capture key input.

var keyObj = scene.input.keyboard.addKey('W', enableCapture, emitOnRepeat);\n

Set enableCapture to false to bypass key input to this input-text game objecct.

"},{"location":"canvasinput/#other-properties","title":"Other properties","text":"

See Dynamic text game object game object

"},{"location":"canvasinput/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"canvasinput/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"capitalizes-first/","title":"Capitalizes first","text":""},{"location":"capitalizes-first/#introduction","title":"Introduction","text":"

Capitalizes the first letter of a string, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"capitalizes-first/#usage","title":"Usage","text":"
var result = Phaser.Utils.String.UppercaseFirst(str);\n
"},{"location":"charactercache/","title":"Character cache","text":""},{"location":"charactercache/#introduction","title":"Introduction","text":"

Generate bitmapfont from text game object, or bbcode text game object.

  • Author: Rex
  • Member of scene
"},{"location":"charactercache/#live-demos","title":"Live demos","text":"
  • Set text
  • Textbox
"},{"location":"charactercache/#usage","title":"Usage","text":"

Sample code

"},{"location":"charactercache/#install-plugin","title":"Install plugin","text":""},{"location":"charactercache/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcharactercacheplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcharactercacheplugin.min.js', true);\n
  • Add character-cache object
    var characterCache = scene.plugins.get('rexcharactercacheplugin').add(config);\n
"},{"location":"charactercache/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CharacterCachePlugin from 'phaser3-rex-plugins/plugins/charactercache-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCharacterCache',\nplugin: CharacterCachePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add character-cache object
    var characterCache = scene.plugins.get('rexCharacterCache').add(config);\n
"},{"location":"charactercache/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CharacterCache from 'phaser3-rex-plugins/plugins/charactercache.js';\n
  • Add character-cache object
    var characterCache = new CharacterCache(game, config);\n
    or
    var characterCache = new CharacterCache(scene, config);\n
"},{"location":"charactercache/#create-instance","title":"Create instance","text":"
var characterCache = scene.plugins.get('rexCharacterCache').add({\nkey: '',  cellWidth: 32,\ncellHeight: 32,\nmaxCharacterCount: 4096,\nfreqMode: true,\n\nstyle: textStyle,\n// textObject: textGameOject,\n\n\ncontent: '',\n});\n
  • key : Texture key in texture manager
  • cellWidth, cellHeight : Maximum frame size.
  • maxCharacterCount : Maximun character count.
    • Width of texture = Math.ceil(Math.sqrt(maxCharacterCount)) * cellWidth
    • Height of texture = Math.ceil(Math.sqrt(maxCharacterCount)) * cellHeight
  • freqMode :
    • true : Swap out un-unsed and low-frequence character.
    • false : Swap out any un-unsed character.
  • style : Style of Text game object. Create a text game object by this style setting on systemScene if textObject parameter is not given.
  • textObject : Text game object, or bbcode text game object for drawing character.
  • content : Load these characters into cache.
"},{"location":"charactercache/#create-bitmaptext","title":"Create BitmapText","text":"

Create BitmapText/Dynamci BitmapText game object using this character cache, add this game object into scene's display list

  • BitmapText
    var txt = characterCache.addBitmapText(scene);    // var txt = characterCache.addBitmapText(scene, x, y, text, size, align);\n
  • Dynamci BitmapText
    var txt = characterCache.addDynamicBitmapText(scene);    // var txt = characterCache.addDynamicBitmapText(scene, x, y, text, size, align);\n
"},{"location":"charactercache/#load-characters","title":"Load characters","text":"

Load characters into bitmap font, replace unused characters if no free character space.

characterCache.load(content);\n// characterCache.load(content, lock);\n
  • content : Characters in a string.
  • lock
    • true : Lock these characters, won't be replaced out later.
    • false : Don't lock these characters, can be replaced out later. Default behavior.

Warning

Console.warn messages if no unused character is found.

"},{"location":"charactercache/#events","title":"Events","text":"
  • Add a character
    characterCache.on('add', function(character, textObject) {\n// Can change style of textObject here\n})\n
  • Swap out a character
    characterCache.on('remove', function(character, textObject) {\n})\n
"},{"location":"charactercache/#override-bitmaptext","title":"Override bitmaptext","text":"

Inject characterCache.load(text) into bitmapText.setText(text) method.

characterCache.overrideBitmapText(bitmapText);\n// var bitmapText = characterCache.overrideBitmapText(bitmapText);\n

Now setText method has lock parameter : bitmapText.setText(text, lock).

Or user can override bitmapText.setText by extending Phaser.GameObjects.BitmapText class.

"},{"location":"charactercache/#unlock-all-characters","title":"Unlock all characters","text":"
characterCache.unlock();\n
"},{"location":"charactercache/#get-all-cache-data","title":"Get all cache data","text":"
var cacheData = characterCache.getAllData();\n
  • cacheData : Array of cache data
    {\ncharacter: string,\nfreq: number,\nalive: boolean,\nlock: boolean,\n}\n
"},{"location":"charactercache/#destroy-instance","title":"Destroy instance","text":"
characterCache.destroy();\n
"},{"location":"charactercache/#properties","title":"Properties","text":"
  • characterCache.key : Font key.
  • characterCache.cellWidth, characterCache.cellHeight : Cell size.
  • characterCache.inCacheCount : Amount of characters in cache.
"},{"location":"circlemaskimage/","title":"Circle mask image","text":""},{"location":"circlemaskimage/#introduction","title":"Introduction","text":"

Load a texture, then apply a circle mask. Extended from canvas plugin.

  • Author: Rex
  • Game object
"},{"location":"circlemaskimage/#live-demos","title":"Live demos","text":"
  • Circle-mask-image
"},{"location":"circlemaskimage/#usage","title":"Usage","text":"

Sample code

"},{"location":"circlemaskimage/#install-plugin","title":"Install plugin","text":""},{"location":"circlemaskimage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcirclemaskimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcirclemaskimageplugin.min.js', true);\n
  • Add circle-mask-image object
    var image = scene.add.rexCircleMaskImage(x, y, key, frame, config);\n
"},{"location":"circlemaskimage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CircleMaskImagePlugin from 'phaser3-rex-plugins/plugins/circlemaskimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCircleMaskImagePlugin',\nplugin: CircleMaskImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add circle-mask-image object
    var image = scene.add.rexCircleMaskImage(x, y, key, frame, config);\n
"},{"location":"circlemaskimage/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CircleMaskImage from 'phaser3-rex-plugins/plugins/circlemaskimage.js';\n
  • Add circle-mask-image object
    var image = new CircleMaskImage(scene, x, y, key, frame, config);\nscene.add.existing(image);\n
"},{"location":"circlemaskimage/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCircleMaskImagePlugin',\nplugin: CircleMaskImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"circlemaskimage/#create-instance","title":"Create instance","text":"
var image = scene.add.rexCircleMaskImage(x, y, key, frame, {\nmaskType: 0,\n// radius: undefined,\n\n// backgroundColor: undefined,\n\n// strokeColor: undefined,\n// strokeWidth: 0,\n});\n

or

var image = scene.add.rexCircleMaskImage(x, y, key, {\nmaskType: 0,\n// radius: undefined,\n\n// backgroundColor: undefined,\n\n// strokeColor: undefined,\n// strokeWidth: 0,\n});\n
  • maskType : Type of mask.
    • null : No mask.
    • 'circle', or 0 : Circle mask.
    • 'ellipse', or 1 : Ellipse mask.
    • 'roundRectangle', or 2 : Round rectangle mask.
  • radius : Radius of round rectangle mask.
    • 0 : Disable round corner.
    • Number: 4 corners with the same radius.
    • JSON
      • 4 corners with the same radius X/Y
        {\nx: radiusX,\ny: radiusY\n}\n
      • Eeach radius of corner
        {\ntl: radius,\ntr: radius,\nbl: radius,\nbr: radius\n}\n
        or
        {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n}\n
  • backgroundColor : Fill background with color.
    • undefined, or null : No background filling. Default behavior.
  • strokeColor : Add stroke around masked image.
    • undefined, or null : No stroke line. Default behavior.
  • strokeWidth : Stroke line width.

Add image from JSON

var image = scene.make.rexCircleMaskImage({\nx: 0,\ny: 0,\nkey: key,\nframe: name,\nmaskType: 0,\n// radius: undefined\n// origin: {x: 0.5, y: 0.5},\n\n// backgroundColor: undefined,\n\n// strokeColor: undefined,\n// strokeWidth: 0,\n\nadd: true\n});\n
"},{"location":"circlemaskimage/#custom-class","title":"Custom class","text":"
  • Define class
    class MyImage extends CircleMaskImage {\nconstructor(scene, x, y, key, frame, config) {\nsuper(scene, x, y, key, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyImage(scene, key, frame, config);\n
"},{"location":"circlemaskimage/#set-texture","title":"Set texture","text":"
image.setTexture(key, frame);\n// image.setTexture(key, frame, maskType);\n

or

image.setTexture(key, frame, {\nmaskType: 0,\n// radius: undefined\n});\n
  • maskType : Type of mask
    • null : No mask.
    • 0, or 'circle' : Circle mask. Default value.
    • 1, or 'ellipse' : Ellipse mask.
  • radius : Radius of round rectangle mask.
    • 0 : Disable round corner.
    • Number: 4 corners with the same radius.
    • JSON
      • 4 corners with the same radius X/Y
        {\nx: radiusX,\ny: radiusY\n}\n
      • Eeach radius of corner
        {\ntl: radius,\ntr: radius,\nbl: radius,\nbr: radius\n}\n
        or
        {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n}\n
"},{"location":"circlemaskimage/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"circlemaskimage/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"circlemaskimage/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"clamp/","title":"Clamp","text":""},{"location":"clamp/#introduction","title":"Introduction","text":"

Force a value within the boundaries by clamping it to the range min, max, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"clamp/#usage","title":"Usage","text":"
var result = Phaser.Math.Clamp(value, min, max);\n
  • value : The value to be clamped.
"},{"location":"clickoutside/","title":"Click outside","text":""},{"location":"clickoutside/#introduction","title":"Introduction","text":"

Fires 'clickoutside' event when pointer-down or pointer-up outside of game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"clickoutside/#live-demos","title":"Live demos","text":"
  • Click outside
"},{"location":"clickoutside/#usage","title":"Usage","text":"

Sample code

"},{"location":"clickoutside/#install-plugin","title":"Install plugin","text":""},{"location":"clickoutside/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexclickoutsideplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexclickoutsideplugin.min.js', true);\n
  • Add click-outside behavior
    var clickOutside = scene.plugins.get('rexclickoutsideplugin').add(gameObject, config);\n
"},{"location":"clickoutside/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ClickOutsidePlugin from 'phaser3-rex-plugins/plugins/clickoutside-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexClickOutsiden',\nplugin: ClickOutsidePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add click-outside behavior
    var clickOutside = scene.plugins.get('rexClickOutsiden').add(gameObject, config);\n
"},{"location":"clickoutside/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ClickOutside from 'phaser3-rex-plugins/plugins/clickoutside.js';\n
  • Add clickoutside behavior
    var clickOutside = new ClickOutside(gameObject, config);\n
"},{"location":"clickoutside/#create-instance","title":"Create instance","text":"
var clickOutside = scene.plugins.get('rexClickOutside').add(gameObject, {\n// enable: true,\n// mode: 1,              // 0|'press'|1|'release'\n// clickInterval: 100,   // ms\n// threshold: undefined\n});\n
  • enable : Clickable.
  • mode :
    • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
    • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
  • clickInterval : Interval between 2 'click' events, in ms.
  • threshold : Cancel clicking detecting when dragging distance is larger then this threshold.
    • undefined : Ignore this feature. Default behavior.
"},{"location":"clickoutside/#events","title":"Events","text":"
  • Click-outside
    clickOutside.on('clickoutside', function (clickoutside, gameObject, pointer) {\n// ...\n}, scope);\n
  • Enable
    clickOutside.on('enable', function (clickoutside, gameObject) {\n// ...\n}, scope);\n
  • Disable
    clickOutside.on('disable', function (clickoutside, gameObject) {\n// ...\n}, scope);\n
"},{"location":"clickoutside/#enable","title":"Enable","text":"
  • Get
    var enabled = clickOutside.enable;  // enabled: true, or false\n
  • Set
    clickOutside.setEnable(enabled);  // enabled: true, or false\n// clickOutside.enable = enabled;\n
  • Toggle
    clickOutside.toggleEnable();\n
"},{"location":"clickoutside/#set-mode","title":"Set mode","text":"
clickOutside.setMode(mode);\n
  • mode :
    • 'press', or 0 : Fire 'click' event when touch pressed.
    • 'release', or 1 : Fire 'click' event when touch released after pressed.
"},{"location":"clickoutside/#set-click-interval","title":"Set click interval","text":"
clickOutside.setClickInterval(interval);  // interval in ms\n
"},{"location":"clickoutside/#set-dragging-threshold","title":"Set dragging threshold","text":"
clickOutside.setDragThreshold(distance);  // distance in pixels\n
"},{"location":"clock/","title":"Clock","text":""},{"location":"clock/#introduction","title":"Introduction","text":"

A clock to count elapsed time.

  • Author: Rex
  • Member of scene
"},{"location":"clock/#usage","title":"Usage","text":"

Sample code

"},{"location":"clock/#install-plugin","title":"Install plugin","text":""},{"location":"clock/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexclockplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexclockplugin.min.js', true);\n
  • Add clock object
    var clock = scene.plugins.get('rexclockplugin').add(scene, config);\n
"},{"location":"clock/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ClockPlugin from 'phaser3-rex-plugins/plugins/clock-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexClock',\nplugin: ClockPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add clock object
    var clock = scene.plugins.get('rexClock').add(scene, config);\n
"},{"location":"clock/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Clock from 'phaser3-rex-plugins/plugins/clock.js';\n
  • Add clock object
    var clock = new Clock(scene, config);\n
"},{"location":"clock/#create-instance","title":"Create instance","text":"
var clock = scene.plugins.get('rexClock').add(scene, {\n// timeScale: 1\n});\n
  • timeScale : time-scale for counting elapsed time.
"},{"location":"clock/#start-counting","title":"Start counting","text":"
clock.start();\n// clock.start(startAt);  // start-at time in ms\n
"},{"location":"clock/#force-ticking","title":"Force ticking","text":"
clock.tick(0);\n// clock.tick(delta);\n
"},{"location":"clock/#get-elapsed-time","title":"Get elapsed time","text":"
var now = clock.now;  // Elapsed time in ms\n
"},{"location":"clock/#pause-resume-stop-counting","title":"Pause, Resume, stop counting","text":"
clock.pause();\nclock.resume();\nclock.stop();\n
"},{"location":"clock/#seek-elapsed-time","title":"Seek elapsed time","text":"
clock.seek(time);   // elapsed time in ms\n
"},{"location":"clock/#state-of-counting","title":"State of counting","text":"
var isRunning = clock.isRunning;\n
"},{"location":"clock/#time-scale","title":"Time-scale","text":"
  • Get
    var timeScale = clock.timeScale;\n
  • Set
    clock.setTimeScale(timeScale);\n// clock.timeScale = timeScale;\n
"},{"location":"clock/#events","title":"Events","text":"
  • On ticking
    clock.on('update', function(now, delta){ })\n
    • now : Elapsed time in ms.
    • delta : Delta time in ms.
"},{"location":"color/","title":"Color","text":""},{"location":"color/#introduction","title":"Introduction","text":"

Get color value, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"color/#usage","title":"Usage","text":""},{"location":"color/#get-color-integer","title":"Get color integer","text":"
  • Hex string, or color integer
    var color = Phaser.Display.Color.ValueToColor(input);\n
    • input : Hex string, or color integer
  • RGB to color
    var color = Phaser.Display.Color.GetColor(red, green, blue);\n
    • red, green, blue : 0 ~ 255
  • RGBA to color
    var color = Phaser.Display.Color.GetColor32(red, green, blue, alpha);\n
    • red, green, blue, alpha : 0 ~ 255
  • Hex string to color
    var color = Phaser.Display.Color.HexStringToColor(hex).color;\n
    • hex : #0033ff, #03f, 0x0033ff, or 0x03f
  • RGB string to color
    var color = Phaser.Display.Color.RGBStringToColor(rgb);\n
    • rgb : 'rgb(r,g,b)', or 'rgba(r,g,b,a)'
      • r, g, b : 0 ~ 255
      • a : 0 ~ 1
  • HSV to color
    var color = Phaser.Display.Color.HSVToRGB(h, s, v).color;\n
    • h, s, v : 0 ~ 1
"},{"location":"color/#color-integer-to-rgb","title":"Color integer to RGB","text":"
var rgb = Phaser.Display.Color.IntegerToRGB(color);\n
  • color : Color integer (0xAARRGGBB)
  • rgb : JSON object ({r, g, b, a})
"},{"location":"color/#hsv-color-wheel","title":"HSV color wheel","text":"
  1. Create color array
    var colorArray = Phaser.Display.Color.HSVColorWheel(s, v);\n
  2. Get color
    var color = colorArray[i].color;  // i : 0 ~ 359\n
"},{"location":"color/#color-object","title":"Color object","text":""},{"location":"color/#create-color-object","title":"Create color object","text":"
  • Create via r,g,b,a components
    var color = new Phaser.Display.Color(red, green, blue); // alpha = 255\n// var color = new Phaser.Display.Color(red, green, blue, alpha);\n
    • red, green, blue, alpha: 0 ~ 255
  • Create via color integer
    var color = Phaser.Display.Color.IntegerToColor(colorInteger);\n
    • colorInteger : Color integer (0xAARRGGBB)
"},{"location":"color/#set-color","title":"Set color","text":"
  • Set color
    color.setTo(red, green, blue);  // alpha = 255\n// color.setTo(red, green, blue, alpha);\n
    • red, green, blue, alpha: 0 ~ 255
  • Set color in GL values
    color.setGLTo(red, green, blue);  // alpha = 1\n// color.setTo(red, green, blue, alpha);\n
    • red, green, blue, alpha: 0 ~ 1
  • Set color from color object
    color.setFromRGB(rgba);\n
    • rgba :
      {\nr: 0,\ng: 0,\nb: 0,\n// a: 0\n}\n
  • Set color from HSV
    color.setFromHSV(h, s, v);\n
  • Set to transparent ()
    color.transparent();\n
    • Set (red, green, blue) to 0
  • Set to gray color
    color.gray(value);\n
  • Set to a random color
    color.random();\n
    or
    color.random(min, max);\n
    • min : 0 ~ 255. Default value is 0.
    • max : 0 ~ 255. Default value is 255.
  • Set to random gray
    color.randomGray();\n
    or
    color.randomGray(min, max);\n
  • Set red/green/blue/alpha channel : 0 ~ 255
    color.red = value;\n// color.red += value;\ncolor.green = value;\n// color.green += value;\ncolor.blue = value;\n// color.blue += value;\ncolor.alpha = value;\n// color.alpha += value;\n
  • Set H/S/V channel : 0 ~ 1
    color.h = value;\n// color.h += value;\ncolor.s = value;\n// color.s += value;\ncolor.v = value;\n// color.v += value;\n
  • Set normalized red, green, blue, alpha : 0 ~ 1
    color.redGL = value;\n// color.redGL += value;\ncolor.greenGL = value;\n// color.greenGL += value;\ncolor.blueGL = value;\n// color.blueGL += value;\ncolor.alphaGL = value;\n// color.alphaGL += value;\n
  • Set brighten
    color.brighten(value);\n
    • value : Percentage, 0 ~ 100
  • Saturate : Increase the saturation (S) of this Color by the percentage amount given.
    color.saturate(value);\n
    • value : Percentage, 0 ~ 100
  • Desaturate : Decrease the saturation (S) of this Color by the percentage amount given.
    color.desaturate(value);\n
    • value : Percentage, 0 ~ 100
  • Lighten : Increase the lightness (V) of this Color by the percentage amount given.
    color.lighten(value);\n
    • value : Percentage, 0 ~ 100
  • Darken : Decrease the lightness (V) of this Color by the percentage amount given.
    color.darken(value);\n
    • value : Percentage, 0 ~ 100
"},{"location":"color/#properties","title":"Properties","text":"
  • RGB Color, not including the alpha channel
    var c = color.color;\n
  • RGB Color, including the alpha channel.
    var c = color.color32;\n
  • RGB color string which can be used in CSS color values.
    var c = color.rgba;\n
  • Red, green, blue, alpha : 0 ~ 255
    var r = color.red;\nvar g = color.green;\nvar b = color.blue;\nvar a = color.alpha;\n
  • H, S, V : 0 ~ 1
    var h = color.h;\nvar s = color.s;\nvar v = color.v;\n
  • Normalized red, green, blue, alpha : 0 ~ 1
    var r = color.redGL;\nvar g = color.greenGL;\nvar b = color.blueGL;\nvar a = color.alphaGL;\n
"},{"location":"color/#clone","title":"Clone","text":"
var newColor = color.clone();\n
"},{"location":"color/#to-hex-string","title":"To hex string","text":"
var hexString = Phaser.Display.Color.RGBToString(color.r, color.g, color.b, color.a);\n// var hexString = Phaser.Display.Color.RGBToString(color.r, color.g, color.b, color.a, prefix);\n
"},{"location":"color/#interpolation","title":"Interpolation","text":"

Interpolate between 2 colors.

var colorOut = Phaser.Display.Color.Interpolate.RGBWithRGB(r1, g1, b1, r2, g2, b2, length, index);\nvar colorOut = Phaser.Display.Color.Interpolate.ColorWithColor(color1, color2, length, index);\nvar colorOut = Phaser.Display.Color.Interpolate.ColorWithRGB(color, r, g, b, length, index);\n
  • length, index : t = index/length (0~1)
"},{"location":"conditionstable/","title":"CSV Conditions table","text":""},{"location":"conditionstable/#introduction","title":"Introduction","text":"

Check conditions to find passed tests listed in a csv table.

  • Author: Rex
  • Member of scene
"},{"location":"conditionstable/#usage","title":"Usage","text":"

Sample code

"},{"location":"conditionstable/#install-plugin","title":"Install plugin","text":""},{"location":"conditionstable/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexconditionstableplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexconditionstableplugin.min.js', true);\n
  • Add conditions-table object
    var conditionstable = scene.plugins.get('rexconditionstableplugin').add();\n
"},{"location":"conditionstable/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ConditionsTablePlugin from 'phaser3-rex-plugins/plugins/conditionstable-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexConditionsTable',\nplugin: ConditionsTablePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add conditions-table object
    var conditionstable = scene.plugins.get('rexConditionsTable').add();\n
"},{"location":"conditionstable/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ConditionsTable from 'phaser3-rex-plugins/plugins/conditionstable.js';\n
  • Add conditions-table object
    var conditionstable = new ConditionsTable();\n
"},{"location":"conditionstable/#create-instance","title":"Create instance","text":"
var table = scene.plugins.get('rexConditionsTable').add();\n
"},{"location":"conditionstable/#load-table-from-csv-string","title":"Load table from csv string","text":"
table.loadCSV(csvString, {\n// delimiter: ','\n});\n

For exameple, csv string

name A A B Test1 >= 10 <= 20 Test2 3
,A,A,B\nTest1,>= 10,<= 20,\nTest2,,,3\n

means that:

Test1: (A>=10) && (A<=20)\nTest2: (B==3)\n

Equations will be evaled by new Function.

"},{"location":"conditionstable/#test","title":"Test","text":""},{"location":"conditionstable/#get-test-results","title":"Get test results","text":"
var results = table.getTestResults(context);\n
  • context : Inputs in Key-value pairs
  • results : {name: boolean}, use OR operation to combine result of tests with the same name.
"},{"location":"conditionstable/#get-first-pass-test-name","title":"Get first pass test name","text":"
var testName = table.anyPassTest(context);\n
  • context : Inputs in Key-value pairs
"},{"location":"config-data/","title":"Configuration data","text":""},{"location":"config-data/#introduction","title":"Introduction","text":"

Get parameters from configuration object.

  • Author: Richard Davey
"},{"location":"config-data/#usage","title":"Usage","text":""},{"location":"config-data/#quick-start","title":"Quick start","text":"
const GetValue = Phaser.Utils.Objects.GetValue;\nvar myMethod = function(config) {\nvar x = GetValue(config, 'x', 0);\nvar y = GetValue(config, 'y', 0);\nvar width = GetValue(config, 'width', 0);\nvar height = GetValue(config, 'height', 0);\n// ...\n}\n
"},{"location":"config-data/#get-value","title":"Get value","text":"
  • Retrieves a value from an object.
    var value = Phaser.Utils.Objects.GetValue(source, key, defaultValue);\n
    • source : Configuration object.
    • key : The name of the property to retrieve from the object. For example,
      • Property source.name, key = name
      • Property source.position.x, key = position.x
    • defaultValue : The value to return if the key isn't found in the source object.
  • Finds the key within the top level of the source object, or returns defaultValue.
    var value = Phaser.Utils.Objects.GetFastValue(source, key, defaultValue);\n
    • key : The key for the property on source. Must exist at the top level of the source object.
  • Retrieves a value from an object. Allows for more advanced selection options.
    var value = Phaser.Utils.Objects.GetAdvancedValue(source, key, defaultValue);\n
    • Implicit
      var source = {x: 4};\nvar value = Phaser.Utils.Objects.GetAdvancedValue(source, 'x'); // value = 4\n
    • From function
      var source = {x: function(key){return 4;}};\nvar value = Phaser.Utils.Objects.GetAdvancedValue(source, 'x'); // value = 4\n
      • Pass key to function's 1st parameter, and get return value as final result.
    • Randomly pick one element from the array
      var source = {x: [a, b, c]};\nvar value = Phaser.Utils.Objects.GetAdvancedValue(source, 'x'); // value = random item from array [a, b, c]\n
    • Random integer between min and max
      var source = {x: randInt: [min, max]};\nvar value = Phaser.Utils.Objects.GetAdvancedValue(source, 'x'); // value = random int min~max\n
    • Random float between min and max
      var source = {x: randFloat: [min, max]};\nvar value = Phaser.Utils.Objects.GetAdvancedValue(source, 'x'); // value = random float min~max\n
"},{"location":"config-data/#is-plain-object","title":"Is plain object","text":"
var isPlainObject = Phaser.Utils.Objects.IsPlainObject(object);\n

Plain object:

  • var obj = {};
  • var obj = new Object();
"},{"location":"config-data/#merge-configuration","title":"Merge configuration","text":"
var configOut = Phaser.Utils.Objects.Merge(configIn, defaultConfig);\n
"},{"location":"container/","title":"Container","text":""},{"location":"container/#introduction","title":"Introduction","text":"

Control the position and angle of children game objects, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"container/#usage","title":"Usage","text":""},{"location":"container/#container","title":"Container","text":""},{"location":"container/#add-container-object","title":"Add container object","text":"
var container = scene.add.container(x, y);\n// var container = scene.add.container(x, y, children); // children: an array of game object\n
"},{"location":"container/#custom-class","title":"Custom class","text":"
  • Define class
    class MyContainer extends Phaser.GameObjects.Container {\nconstructor(scene, x, y, children) {\nsuper(scene, x, y, children);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var container = new MyContainer(scene, x, y, children);\n
"},{"location":"container/#destroy","title":"Destroy","text":"
container.destroy();\n

Also destroy all children game objects.

"},{"location":"container/#set-properties","title":"Set properties","text":"

Reference game object, to set position, angle, visible, alpha, etc...

"},{"location":"container/#set-size","title":"Set size","text":"
container.setSize(width, height);\n

Default size is 0x0.

"},{"location":"container/#set-scroll-factor","title":"Set scroll factor","text":"
container.setScrollFactor(x, y);\n

Apply this scrollFactor to all Container children.

container.setScrollFactor(x, y, true);\n
"},{"location":"container/#hit-area","title":"Hit area","text":"
container.setInteractive(new Phaser.Geom.Circle(0, 0, radius), Phaser.Geom.Circle.Contains);\n// container.setInteractive(false); // disable\n

Assign hit area with a circle shape.

"},{"location":"container/#non-exclusive","title":"Non-exclusive","text":"
container.setExclusive(false);\n

Allows a game object added to container many times.

"},{"location":"container/#children","title":"Children","text":""},{"location":"container/#add-child","title":"Add child","text":"
container.add(child);  // child: a game object or an array of game objects\n
container.addAt(child, index);\n
"},{"location":"container/#exist","title":"Exist","text":"
var hasChild = container.exists(child);\n
"},{"location":"container/#get-child","title":"Get child","text":"
var firstChild = container.first;\nvar nextChild = container.next;\nvar prevChild = container.previous;\nvar lastChild = container.last;\n
var child = container.getByName(name);\n
var child = container.getRandom(startIndex, length);\n
var child = container.getFirst(property, value, startIndex, endIndex);\n// value: the value to test the property against. Must pass a strict (`===`) comparison check.\n
var children = container.getAll(property, value, startIndex, endIndex);\n// value: the value to test the property against. Must pass a strict (`===`) comparison check.\n
var amount = container.count(property, value, startIndex, endIndex);\n// value: the value to test the property against. Must pass a strict (`===`) comparison check.\n
"},{"location":"container/#sort-children","title":"Sort children","text":"
container.sort(property);\n
container.sort(property, function(childA, childB){\nreturn 0; // 0, 1, -1\n});\n
"},{"location":"container/#remove-child","title":"Remove child","text":"
container.remove(child);\n// container.remove(child, true);  // remove child object and destroy it\n
container.removeAt(index);\n// container.removeAt(index, true);  // remove child object and destroy it\n
container.removeBetween(startIndex, endIndex);\n// container.removeBetween(startIndex, endIndex, true);  // remove children objects and destroy them\n
container.removeAll();\n// container.removeAll(true);  // remove all children objects and destroy them\n

Removing child from container without destroying will put back into scene's display list.

"},{"location":"container/#order-of-child","title":"Order of child","text":"
container.moveTo(child, index);\n
container.bringToTop(child);\n
container.sendToBack(child);\n
container.moveUp(child);\n
container.moveDown(child);\n
container.moveAbove(child1, child2);  // Move child1 above child2\n
container.moveBelow(child1, child2);  // Move child1 below child2\n
container.swap(child1, child2);\n
container.reverse();\n
container.shuffle();\n
"},{"location":"container/#replace-child","title":"Replace child","text":"
container.replace(oldChild, newChild);\n// container.replace(oldChild, newChild, true);  // destroy oldChild\n
"},{"location":"container/#set-properties_1","title":"Set properties","text":"
container.setAll(property, value, startIndex, endIndex);\n
"},{"location":"container/#for-each-child","title":"For each child","text":"
  • Iterate current children list
    container.iterate(callback);\n// container.iterate(callback, context);\n// container.iterate(callback, context, arg0, arg1, ...);\n
    • callback :
      function(child, arg0, arg1, ...) {\n\n}\n
  • Iterate a copy of current children list
    container.each(callback);\n// container.each(callback, context);\n// container.each(callback, context, arg0, arg1, ...);\n
    • callback :
      function(child, arg0, arg1, ...) {\n\n}\n
"},{"location":"container/#get-world-position-rotation-scale","title":"Get world position, rotation, scale","text":"
var matrix = child.getWorldTransformMatrix();\nvar x = matrix.tx;\nvar y = matrix.ty;\nvar rotation = matrix.rotation;\nvar scaleX = matrix.scaleX;\nvar scaleY = matrix.scaleY;\n
"},{"location":"container/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"container/#create-mask","title":"Create mask","text":"
var mask = container.createBitmapMask();\n

See mask

"},{"location":"container/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"container/#compare-with-group-object","title":"Compare with group object","text":"
  • Container and group objects are all have a children list.
  • Container has position, angle, alpha, visible, ...etc, but group does not have.
  • Container controls properties of children (position, angle, alpha, visible, ...etc), but group won't.
  • A game object could be added to many groups, but it only could be added to one container (exclusive mode).
"},{"location":"containerlite-perspective/","title":"Perspective","text":""},{"location":"containerlite-perspective/#introduction","title":"Introduction","text":"

Snapshot children of containerlite, to a perspective render texture.

  • Author: Rex
  • Behavior of containerlite
"},{"location":"containerlite-perspective/#live-demos","title":"Live demos","text":"
  • Flip ui
"},{"location":"containerlite-perspective/#usage","title":"Usage","text":"

Sample code

"},{"location":"containerlite-perspective/#install-plugin","title":"Install plugin","text":""},{"location":"containerlite-perspective/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add perspective behavior
    // var container = scene.add.rexContainerLite(x, y);\nvar perspective = scene.plugins.get('rexperspectiveimageplugin').addContainerPerspective(container, config);\n
"},{"location":"containerlite-perspective/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add perspective behavior
    // var container = scene.add.rexContainerLite(x, y);\nvar perspective = scene.plugins.get('rexPerspectiveImagePlugin').addContainerPerspective(container, config);\n
"},{"location":"containerlite-perspective/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ContainerPerspective } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add perspective behavior
    // var container = scene.add.rexContainerLite(x, y);\nvar perspective = new ContainerPerspective(container, config);\n
"},{"location":"containerlite-perspective/#create-instance","title":"Create instance","text":"
var perspective = scene.plugins.get('rexPerspectiveImagePlugin').addContainerPerspective(container, {\nuseParentBounds: false,\n// hideCCW: true,\n});\n
  • useParentBounds :
    • true : Use bounds of parent container
    • false : Union all visible children's bounds
  • hideCCW :
    • true : Hide backward facing Faces. Default behavior.
    • false : Show backward facing Faces
"},{"location":"containerlite-perspective/#perspective-mode","title":"Perspective mode","text":""},{"location":"containerlite-perspective/#enter","title":"Enter","text":"
perspective.enter();\n
  1. Snapshot current visible children into perspective render texture
  2. Set current visible children to invisible
  3. Set this perspective render texture to visible
"},{"location":"containerlite-perspective/#exit","title":"Exit","text":"
perspective.exit();\n
  1. Inverse visible of children and perspective render texture
"},{"location":"containerlite-perspective/#is-in-perspective-mode","title":"Is in perspective mode","text":"
var isInPerspectiveMode = perspective.perspectiveState;\n
"},{"location":"containerlite-perspective/#rotation","title":"Rotation","text":"
  • Get rotation angle
    var angleX = perspective.angleX; // Angle in degrees\nvar angleY = perspective.angleY; // Angle in degrees\nvar angleZ = perspective.angleZ; // Angle in degrees\n
    or
    var rotationX = perspective.rotationX; // Angle in radians\nvar rotationY = perspective.rotationY; // Angle in radians\nvar rotationZ = perspective.rotationZ; // Angle in radians\n
  • Set rotation angle
    perspective.angleX = angleX; // Angle in degrees\nperspective.angleY = angleY; // Angle in degrees\nperspective.angleZ = angleZ; // Angle in degrees\n
    or
    perspective.rotationX = rotationX; // Angle in radians\nperspective.rotationY = rotationY; // Angle in radians\nperspective.rotationZ = rotationZ; // Angle in radians\n
"},{"location":"containerlite-perspective/#flip","title":"Flip","text":"
scene.tweens.add({\ntargets: perspective,\nangleY: { start: 0, to: -180}\n})\n
"},{"location":"containerlite-perspective/#other-properties","title":"Other properties","text":"

See Perspective rendertexture game object.

"},{"location":"containerlite-skew/","title":"Skew","text":""},{"location":"containerlite-skew/#introduction","title":"Introduction","text":"

Snapshot children of containerlite, to a skew render texture.

  • Author: Rex
  • Behavior of containerlite
"},{"location":"containerlite-skew/#live-demos","title":"Live demos","text":"
  • Skew ui
"},{"location":"containerlite-skew/#usage","title":"Usage","text":"

Sample code

"},{"location":"containerlite-skew/#install-plugin","title":"Install plugin","text":""},{"location":"containerlite-skew/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquadimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquadimageplugin.min.js', true);\n
  • Add skew behavior
    // var container = scene.add.rexContainerLite(x, y);\nvar skew = scene.plugins.get('rexquadimageplugin').addContainerSkew(container, config);\n
"},{"location":"containerlite-skew/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuadImagePlugin from 'phaser3-rex-plugins/plugins/quadimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuadImagePlugin',\nplugin: QuadImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add skew behavior
    // var container = scene.add.rexContainerLite(x, y);\nvar skew = scene.plugins.get('rexQuadImagePlugin').addContainerSkew(container, config);\n
"},{"location":"containerlite-skew/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ContainerSkew } from 'phaser3-rex-plugins/plugins/quadimage.js';\n
  • Add skew behavior
    // var container = scene.add.rexContainerLite(x, y);\nvar skew = new ContainerSkew(container, config);\n
"},{"location":"containerlite-skew/#create-instance","title":"Create instance","text":"
var quad = scene.plugins.get('rexQuadImagePlugin').addContainerSkew(container, {\nuseParentBounds: false\n});\n
  • useParentBounds :
    • true : Use bounds of parent container
    • false : Union all visible children's bounds
"},{"location":"containerlite-skew/#skew-mode","title":"Skew mode","text":""},{"location":"containerlite-skew/#enter","title":"Enter","text":"
skew.enter();\n
  1. Snapshot current visible children into skew render texture
  2. Set current visible children to invisible
  3. Set this skew render texture to visible
"},{"location":"containerlite-skew/#exit","title":"Exit","text":"
skew.exit();\n
  1. Inverse visible of children and skew render texture
"},{"location":"containerlite-skew/#is-in-skew-mode","title":"Is in skew mode","text":"
var isInSkewMode = skew.skewState;\n
"},{"location":"containerlite-skew/#skew","title":"Skew","text":"
  • Set
    image.setSkewX(skewXRad);\nimage.setSkewXDeg(skewXDeg);\n
    image.setSkewY(skewXRad);\nimage.setSkewYDeg(skewXDeg);\n
    image.setSkew(skewXRad, skewYRad);\nimage.setSkewDeg(skewXDeg, skewYDeg);\n
    image.skewX = skewXRad;\nimage.skewXDeg = skewXDeg;\n
    image.skewY = skewYRad;\nimage.skewYDeg = skewYDeg;\n
  • Get
    var skewXRad = image.skewX;\nvar skewXDeg = image.skewXDeg;\n
    var skewYRad = image.skewY;\nvar skewYDeg = image.skewYDeg;\n
"},{"location":"containerlite-skew/#other-properties","title":"Other properties","text":"

See Skew rendertexture game object.

"},{"location":"containerlite/","title":"Container Lite","text":""},{"location":"containerlite/#introduction","title":"Introduction","text":"

Control the position and angle of children game objects.

It is inspired from Ziao/phaser3-interim-containers.

  • Author: Rex
  • Game object
"},{"location":"containerlite/#live-demos","title":"Live demos","text":"
  • Rotate, alpha
  • Tween child
  • Create tween config
  • Mix timeline
  • Snapshot
  • Destroy:
    • Destroy containerLite
    • Destory scrollablePanel,
  • Add to p3-container
"},{"location":"containerlite/#usage","title":"Usage","text":"

Sample code

"},{"location":"containerlite/#install-plugin","title":"Install plugin","text":""},{"location":"containerlite/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcontainerliteplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcontainerliteplugin.min.js', true);\n
  • Add container object
    var container = scene.add.rexContainerLite(x, y);\n
"},{"location":"containerlite/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ContainerLitePlugin from 'phaser3-rex-plugins/plugins/containerlite-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexContainerLitePlugin',\nplugin: ContainerLitePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add container object
    var container = scene.add.rexContainerLite(x, y);\n
"},{"location":"containerlite/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ContainerLite from 'phaser3-rex-plugins/plugins/containerlite.js';\n
  • Add container object
    var container = new ContainerLite(scene, x, y);\nscene.add.existing(container);\n
"},{"location":"containerlite/#add-container-object","title":"Add container object","text":"
var container = scene.add.rexContainerLite(x, y);  // width = 1, height = 1\n// var container = scene.add.rexContainerLite(x, y, width, height);\n

or

var container = scene.add.rexContainerLite(x, y, children);  // width = 1, height = 1\n// var container = scene.add.rexContainerLite(x, y, width, height, children);\n

Add container from JSON

var container = scene.make.rexContainerLite({\nx: 0,\ny: 0,\nwidth: 1,\nheight: 1,\n\n// angle: 0,\n// alpha: 1,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n});\n
"},{"location":"containerlite/#custom-class","title":"Custom class","text":"
  • Define class
    class MyContainer extends ContainerLite {\nconstructor(scene, x, y, width, height, children) {\nsuper(scene, x, y, width, height, children);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var container = new MyContainer(scene, x, y, width, height, children);\n
"},{"location":"containerlite/#destroy","title":"Destroy","text":"
container.destroy();\n

Also destroy all children.

"},{"location":"containerlite/#other-properties","title":"Other properties","text":"

This container game object inherits from Zone.

"},{"location":"containerlite/#add-child","title":"Add child","text":""},{"location":"containerlite/#pin","title":"Pin","text":"

Add(pin) a game obejct to container

container.add(child);  // child: a game object\n// container.pin(child);\n
  • child : A game object

or

container.pin(child, {\n// syncPosition: true,\n// syncRotation: true,\n// syncScale : true,\n// syncAlpha: true,\n// syncScrollFactor: true,\n// syncCameraFilter: true,\n// syncDisplayList: true\n});\n
  • child : A game object
  • syncPosition :
    • true : Sync position of child, default behavior.
    • false : Don't sync position of child.
  • syncRotation :
    • true : Sync angle of child, default behavior.
    • false : Don't sync angle of child.
  • syncScale :
    • true : Sync scale of child, default behavior.
    • false : Don't sync angle of child.
  • syncAlpha :
    • true : Sync alpha of child, default behavior.
    • false : Don't sync alpha of child.
  • syncScrollFactor :
    • true : Sync scrollFactor of child, default behavior.
    • false : Don't sync scrollFactor of child.
  • syncCameraFilter :
    • true : Sync cameraFilter of child, default behavior.
    • false : Don't sync cameraFilter of child.
  • syncDisplayList :
    • true : Put child into parent's displayList/Layer, default behavior.
      • Child has to belong to any displayList first.
    • false : Don't change child's displayList.

Or add(pin) children

container.addMultiple(children);\n// container.add(children);\n
  • children : An array of game objects

These world properties of children will be changed with container.

  • Position/Angle/Scale
  • Visible
  • Alpha
  • Scroll factor
  • Mask

Note

  • Position of child is the world position, i.e. position of child won't be changed when adding to container initially.
    • For example, container-lite is at (100, 100), and child is at (110, 110), then child will be placed at (110, 110) after adding to container-lite.
  • This behavior is different from official container, which using related position of child when adding to container.
    • For example, official container is at (100, 100), and child is at (10, 10), then child will be placed at (110, 110) after adding to official container.
"},{"location":"containerlite/#add-local","title":"Add local","text":"
container.addLocal(child);\n

or

container.addLocalMultiple(children);\n

or

container.pinLocal(child, {\n// syncPosition: true,\n// syncRotation: true,\n// syncScale : true,\n// syncAlpha: true,\n});\n

Add child to container with related properties, like official container. For example, container-lite is at (100, 100), and child is at (10, 10), then child will be placed at (110, 110) after adding to container-lite.

"},{"location":"containerlite/#remove-child","title":"Remove child","text":"
  • Remove(unpin) a child
    container.remove(child);\n// container.remove(child, destroyChild);\n
    or
    container.unpin(child);\n// container.unpin(child, destroyChild);\n
    • child : Game object
    • destroyChild : Set true to destroy child. Default is false.
  • Remove all children
    container.clear();\n// container.clear(destroyChild);\n
"},{"location":"containerlite/#get-child","title":"Get child","text":"
  • Get first child by name
    var gameObject = container.getByName(name);\n// var gameObject = container.getByName(name, recursive);\n
    • gameObject : A child, or null if not found.
    • recursive : Set true to search all children recursively.
  • Get a random child
    var gameObject = container.getRandom();\n// var gameObject = container.getRandom(startIndex, length);\n
  • Get children in this container-lite
    • Internal children array
      var gameObjects = container.getChildren();\n
    • Copy of children array
      var gameObjects = container.getChildren([]);\n// var gameObjects = container.getChildren(out);\n
  • Get all children under this container-lite recursively
    var gameObjects = container.getAllChildren();\n
    • Put container itself and all children into Layer
      layer.add(container.getAllChildren([container]));\n
    • Draw on render texture
      rt.draw(container.getAllChildren());\n
    • Ignored in camera
      camera.ignore(container.getAllChildren());\n
"},{"location":"containerlite/#traversal","title":"Traversal","text":"
  • Depth-First Search
    container.dfs(function(current) {\n// return true;  // Discard children traveraling\n})\n
    • Return true to discard children traveraling
  • Breadth-First Search
    container.bfs(function(current) {\n// return true;  // Discard children traveraling\n})\n
    • Return true to discard children traveraling
"},{"location":"containerlite/#exist","title":"Exist","text":"

Return true if child is under this container-lite (nested).

var hasChild = container.contains(child);\n
"},{"location":"containerlite/#children","title":"Children","text":"
var children = container.children;\n
  • children : Array of child game objects.
"},{"location":"containerlite/#get-parent","title":"Get parent","text":"
var parentContainer = scene.plugins.get('rexContainerLitePlugin').getParent(child);\n

or

var parentContainer = Container.GetParent(child); // Static method\n
"},{"location":"containerlite/#set-properties-of-child","title":"Set properties of child","text":""},{"location":"containerlite/#position","title":"Position","text":"
container.setChildPosition(child, x, y);\n
"},{"location":"containerlite/#rotation","title":"Rotation","text":"
container.setChildRotation(child, rotation);\n
  • rotation : Angle in radians.
"},{"location":"containerlite/#scale","title":"Scale","text":"
container.setChildScale(child, scaleX, scaleY);\n

or

container.setChildDisplaySize(child, width, height);\n
"},{"location":"containerlite/#visible","title":"Visible","text":"
container.setChildVisible(child, visible);\n
"},{"location":"containerlite/#alpha","title":"Alpha","text":"
container.setChildAlpha(child, alpha);\n
"},{"location":"containerlite/#local-state-of-child","title":"Local state of child","text":"

Get local state

var localState = container.getLocalState(child);\n

or

var localState = child.rexContainer;\n
  • Properties of localState
    • x, y
    • rotation
    • scaleX, scaleY
    • visible
    • alpha
"},{"location":"containerlite/#change-local-state-of-child","title":"Change local state of child","text":"
  • Local position
    container.setChildLocalPosition(child, x, y);\n
  • Local scale
    container.setChildLocalScale(child, scaleX, scaleY);\n
  • Local alpha
    container.setChildLocalAlpha(child, alpha);\n
  • Local visible
    container.setChildLocalVisible(child, visible);\n
"},{"location":"containerlite/#reset-local-state-of-child","title":"Reset local state of child","text":"

Reset local state of child according to current properties of children

  • Reset local state of all properties
    container.resetChildState(child);\n
  • Reset local state of position
    container.resetChildPositionState(child);\n
  • Reset local state of rotation
    container.resetChildRotationState(child);\n
  • Reset local state of scale
    container.resetChildScaleState(child);\n
  • Reset local state of alpha
    container.resetChildAlphaState(child);\n
  • Reset local state of visible
    container.resetChildVisibleState(child);\n
  • Reset local state of active
    container.resetChildActiveState(child);\n
"},{"location":"containerlite/#tween-local-state","title":"Tween local state","text":"
var tweenObj = container.tweenChild({\ntargets: child,\n// x: '+=100',\n// y: '+=100',\n// repeat: -1,\n// yoyo: true\n})\n
  • targets : A game object, or an array of game object.
    • A containerLite child, can tween its local state.

Paramters of configuration is the same as tween task.

Supported properties :

  • x, y,
  • angle, rotation
  • scaleX, scaleY, displayWidth, displayHeight
  • alpha
"},{"location":"containerlite/#tween-local-state-of-a-containerlite-child","title":"Tween local state of a containerlite child","text":"
var tweenObj = containerLiteChild.tweenSelf({    // x: '+=100',\n// y: '+=100',\n// repeat: -1,\n// yoyo: true\n})\n

Equal to

containerLiteChild.tweenChild({\ntargets: containerLiteChild,\n// x: '+=100',\n// y: '+=100',\n// repeat: -1,\n// yoyo: true\n})\n
"},{"location":"containerlite/#create-tween-config","title":"Create tween config","text":"
var tweenConfig = container.createTweenChildConfig({\ntargets: child,\n// x: '+=100',\n// y: '+=100',\n// repeat: -1,\n// yoyo: true\n});\nscene.tweens.add(tweenConfig);\n
  • Input of targets is/are game object(s), will be replaced by local state of game object(S)
  • Wrap onUpdate callback, to update properties of child according to local state.
"},{"location":"containerlite/#depth","title":"Depth","text":"
  • Get depth of container
    var depth = container.depth;\n
  • Set depth of container
    container.setDepth(value, true);\n// container.depth = depth;\n
  • Set depth of container and all children
    container.setDepth(value);\n
  • Bring this container and its children to top
    container.bringMeToTop();\n// container.bringToTop();\n
  • Send this container and its children to back
    container.sendMeToBack();\n// container.sendToBack();\n
  • Swap depth with another container
    containerA.swapDepth(containerB);\n
  • Increase of container and all children
    container.incDepth(value);\n
  • Move game object below this container and all children
    container.moveMyDepthBelow(gameObject);\n// container.moveDepthBelow(gameObject);\n
  • Move game object above this container and all children
    container.moveMyDepthAbove(gameObject);\n// container.moveDepthAbove(gameObject);\n
  • Bring a child of container to top of this container
    container.bringChildToTop(gameObject);\n
  • Send a child of container to bottom of this container
    container.sendChildToBack(gameObject);\n
"},{"location":"containerlite/#render-layer","title":"Render layer","text":"

A containerLite can have a layer. Current children and new children will draw on this layer, instead of display list of scene.

  • Enable layer. Do nothing if layer is existed.
    container.enableLayer();\n
  • Get layer game object. Will enable layer if layer is not existed.
    var layer = container.getLayer();\n
  • Get layer game object, without enable layer.
    var layer = container.privateRenderLayer;\n
  • Has layer game object
    var hasLayer = container.hasLayer();\n
"},{"location":"containerlite/#mask","title":"Mask","text":"
  • Assign mask object to children
    container.setMask(mask);  // container.mask = mask;\n
  • Remove mask object of children
    container.clearMask();\n
  • Remove mask object of children, and destroy mask object
    container.clearMask(true);\n
"},{"location":"containerlite/#shader-effects","title":"Shader effects","text":"

Apply post-fx pipeline on layer of containerLite.

"},{"location":"containerlite/#snapshot","title":"Snapshot","text":"
  • Draw all visible children on a render-texture.
    var renderTexture = container.snapshot({\nrenderTexture: undefined,\npadding: 0\n});\n
    • renderTexture : Draw on this render-texture
      • undefined : Create a new render-texture
    • padding :
      • 0 : No extra padding space. Default value.
      • A number : Add extra padding space around this render-texture.
  • Draw all visible children on a dynamic-texture
    container.snapshot({\npadding: 0,\nsaveTexture: textureKey\n});\n
    • saveTexture : Save render result to texture manager.
"},{"location":"containerlite/#draw-bounds","title":"Draw bounds","text":"
  • Draw bounds of shown game object on a graphics game object
    container.drawBounds(graphics);\n// container.drawBounds(graphics, color);\n
    or
    container.drawBounds(graphics, {\n// color: 0xffffff,\n// lineWidth: 1,\n// padding: 0,\n// drawContainer: true,\n// children: undefined,\n});\n
    • graphics : Graphics game object
    • color : Default value is 0xffffff.
    • lineWidth : Default value is 1.
    • padding : Extra space around bounds. Default value is 0.
    • drawContainer :
      • true : Draw all children game objects included containerLite. Default behavior.
      • false : Draw all children game objects excluded containerLite
    • children :
      • Array of game objects : Only draw bounds of these children
      • undefined : Draw bounds of all children
"},{"location":"containerlite/#scroll-factor","title":"Scroll factor","text":"
  • Set scroll factor to children
    container.setScrollFactor(x, y);\n
"},{"location":"containerlite/#change-origin","title":"Change origin","text":"
container.changeOrigin(originX, originY);\n

This method also will reset all local state of children.

"},{"location":"containerlite/#add-to-container","title":"Add to container","text":"
  • Add to built-in container
    containerLite.addToContainer(p3Container);\n
    or
    p3Container.add(containerLite);\n
    • p3Container : Container game object.
  • Add to Layer
    container.addToLayer(layer);\n
    • layer : Layer game object.
"},{"location":"containerlite/#remove-from-container","title":"Remove from container","text":"
  • Remove from built-in container
    containerLite.removeFromContainer(p3Container);\n
    or
    p3Container.remove(containerLite);\n
    • p3Container : Container game object.
  • Remove from Layer
    container.removeFromLayer(layer);\n
    • layer : Layer game object.
"},{"location":"containerlite/#other-properties_1","title":"Other properties","text":"

See game object

"},{"location":"containerlite/#compare-with-official-container","title":"Compare with Official Container","text":"
  • Position/anlge/scale of a child object :
    • Container : Local position/anlge/scale, responding to parent container, not a world position/anlge/scale.
    • Container-Lite : World position/anlge/scale.
  • Updating period
    • Container : Re-calculate position/anlge/scale of each child every render.
    • Container-Lite: Re-calculate position/anlge/scale of each child when parent container changes position/anlge/scale.
  • Mask
    • Container : It has mask property, and it could become a mask object.
    • Container-Lite : It has mask property, but it could not become a mask object.
  • DOM game object
    • Container : Only 1 level parent container will affect DOM game object. Therefore position of DOM game object in nested container might be incorrect.
    • Container-Lite : DOM game object can work with nested Container-Lite.
"},{"location":"create-number-array/","title":"Number array","text":""},{"location":"create-number-array/#introduction","title":"Introduction","text":"

Create an array representing the range of numbers, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"create-number-array/#usage","title":"Usage","text":""},{"location":"create-number-array/#create-number-array","title":"Create number array","text":"

Create an array representing the range of numbers (usually integers), between, and inclusive of, the given start and end arguments.

var arr = Phaser.Utils.Array.NumberArray(start, end);\n

For example,

var arr = Phaser.Utils.Array.NumberArray(2, 4);\n// arr = [2, 3, 4]\n

"},{"location":"create-number-array/#create-number-array-with-step","title":"Create number array with step","text":"

Create an array of numbers (positive and/or negative) progressing from start up to but not including end by advancing by step.

var arr = Phaser.Utils.Array.NumberArray(start, end, step);\n

For example,

var arr = Phaser.Utils.Array.NumberArrayStep(0, 20, 5);\n// arr =  [0, 5, 10, 15]\n

"},{"location":"create-number-array/#create-prefix-number-suffix-string-array","title":"Create prefix-number-suffix string array","text":"
var arr = Phaser.Utils.Array.NumberArray(start, end, prefix, suffix);\n

For example,

var arr = Phaser.Utils.Array.NumberArray(5, 7, 'HD-', '.png');\n// arr = ['HD-5.png', 'HD-6.png', 'HD-7.png']\n

"},{"location":"csvscenario/","title":"CSV scenario","text":""},{"location":"csvscenario/#introduction","title":"Introduction","text":"

Run script in csv format. Csv could be edited by excel or google document.

  • Author: Rex
  • Member of scene
"},{"location":"csvscenario/#live-demos","title":"Live demos","text":"
  • CSV-scenario
  • With TextPlayer
"},{"location":"csvscenario/#usage","title":"Usage","text":"

Sample code

"},{"location":"csvscenario/#install-plugin","title":"Install plugin","text":""},{"location":"csvscenario/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcsvscenarioplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcsvscenarioplugin.min.js', true);\n
  • Add csv-scenario object
    var scenario = scene.plugins.get('rexcsvscenarioplugin').add(scene);\n
"},{"location":"csvscenario/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CsvScenarioPlugin from 'phaser3-rex-plugins/plugins/csvscenario-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCsvScenario',\nplugin: CsvScenarioPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add csv-scenario object
    var scenario = scene.plugins.get('rexCsvScenario').add(scene);\n
"},{"location":"csvscenario/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CsvScenario from 'phaser3-rex-plugins/plugins/csvscenario.js';\n
  • Add csv-scenario object
    var scenario = new CsvScenario(scene);\n
"},{"location":"csvscenario/#create-instance","title":"Create instance","text":"
var scenario = scene.plugins.get('rexCSVScenario').add(scene, {\n// timeUnit: 0,        // 'ms'|0|'s'|'sec'|1\n// prefix: /^#([a-zA-Z]+)/\n// argsConvert: true,\n// argsConvertScope: undefined,\n// delimiter: ','\n// translateCommandNameCallback: undefined,\n});\n
  • csvString : Commands in csv-string.
  • scope : Running commands via methods in this scope object.
    • Get scope : var scope = scenario.scope
  • timeUnit: time-unit of dt, for delay-execution
    • 'ms', or 0 : dt in millisecond
    • 's', 'sec', or 1 : dt in second
  • prefix: regex of picking control instructions
  • argsConvert: A callback to convert parameters of run-custom-function
    • true : Use defaule value converter. Values will be converted to number (include hex number string like '0xFF'), boolean, null, or string.
    • Function object:
      function(s) {\nreturn s;\n}\n
  • argsConvertScope: scope of argsConvert
  • delimiter : Delimiter of CSV string.
  • translateCommandNameCallback : Callback to translate custom command name
    • undefined : Use original custom command name. Default behavior.
    • A function, return new custom command name.
      function(commandName) {\nreturn newCommandName;\n}\n
"},{"location":"csvscenario/#load-csv-script","title":"Load csv script","text":"
scenario.load(csvString, scope, {\n// timeUnit: 0,        // 'ms'|0|'s'|'sec'|1\n// prefix: /^#([a-zA-Z]+)/\n// argsConvert: true,\n// argsConvertScope: undefined,\n// delimiter: ',',\n// translateCommandNameCallback: undefined,\n})\n
  • csvString : Commands in csv-string.
  • scope : Running commands via methods in this scope object.
    • Get scope : var scope = scenario.scope
  • timeUnit: time-unit of dt, for delay-execution
    • 'ms', or 0 : dt in millisecond
    • 's', 'sec', or 1 : dt in second
  • prefix: regex of picking control instructions
  • argsConvert: A callback to convert parameters of run-custom-function
    • true : Use defaule value converter. Values will be converted to number (include hex number string like '0xFF'), boolean, null, or string.
    • Function object:
      function(s) {\nreturn s;\n}\n
  • argsConvertScope: scope of argsConvert
  • delimiter : Delimiter of CSV string.
"},{"location":"csvscenario/#append-csv-script","title":"Append csv script","text":"
scenario.append(csvString);\n
"},{"location":"csvscenario/#start-running-instructions","title":"Start running instructions","text":"

scenario.start({\n// label: '',\n// offset: 0\n})\n
scenario.play({\n// label: '',\n// offset: 0\n})\n

  • label : Go to the label and execute. '' label is starting from 1st instruction
  • offset : Offset time

or

scenario.playPromise({\n// label: '',\n// offset: 0\n})\n.then(function(){\n// On complete\n})\n
"},{"location":"csvscenario/#events","title":"Events","text":"
  • Complete
    scenario.on('complete', function(scope, scenario){ });\n
  • Wait event
    scenario.on('wait.' + eventName, function(scenario){ });\n
    scenario.on('wait', function(eventName, scenario){ });\n
  • Label has changed
    scenario.on('labelchange', function(lastLabel, prevLabel, scope, scenario){ });\n
  • Dump execution log
    scenario.on('log', function(msg, scope, scenario){ });\n
  • Notify error
    scenario.on('error', function(msg, scope, scenario){ });\n
"},{"location":"csvscenario/#types-of-instructions","title":"Types of instructions","text":"

Each row in csv table is an instruction.

"},{"location":"csvscenario/#run-custom-function","title":"Run custom function","text":"

Run custom function of scope, which passed from scenario.load(...)

Format:

-,fnName,param0,param1,...\n
  • 1st column of instruction: -
  • Parameters will be converted to number, boolean, null, or string by default.
  • Method name of last custom command :
    var methodName = scenario.lastCustomCommandName;\n
  • An error event will be fired if fnName is invalid in scope.
"},{"location":"csvscenario/#delay-execution","title":"Delay execution","text":"

Run custom function after a delay.

Format:

time,fnName,param0,param1,...\n
  • 1st column of instruction: a number
  • time-unit of delay is set from scenario.load(...)
  • Parameters will be converted to number, boolean, null, or string by default.
"},{"location":"csvscenario/#wait-then-execution","title":"Wait then execution","text":"

Run custom function until scenario.continue(eventName)

Format:

eventName,fnName,param0,param1,...\n
  • 1st column of instruction: not a number, not a string start from #
  • Execution will be hang until scenario.continue(eventName) is called
  • Parameters will be converted to number, boolean, null, or string by default.
"},{"location":"csvscenario/#skip-waiting","title":"Skip waiting","text":"
scenario.continue(true);\n
"},{"location":"csvscenario/#task","title":"Task","text":"

Sample code

Scenario will be paused if custom function return an event emitter, resumed when that evnt emitter fires complete event.

See also: Sequence

"},{"location":"csvscenario/#label","title":"Label","text":"

Sample code

A label for #GOTO or #IF instructions.

Format:

#LABEL,label\n
  • 1st column of instruction: #LABEL, case insensitive.
  • Label '' is reserved, don't use '' for label name.

Example: A label named 'AA'

#LABEL,AA\n
  • Last label :
    var label = scenario.lastLabel;\n
  • Previous label :
    var previousLabel = scenario.previousLabel;\n
"},{"location":"csvscenario/#exit","title":"Exit","text":"

Exit current execution.

Format:

#EXIT\n
  • 1st column of instruction: #EXIT, case insensitive.
"},{"location":"csvscenario/#goto","title":"Goto","text":"

Sample code

Go to label and execute.

Format:

#GOTO,label\n
  • 1st column of instruction: #GOTO, case insensitive.
  • An error event will be fired if label is not found.

Example: Goto label 'AA'

#GOTO,AA\n
"},{"location":"csvscenario/#if-goto","title":"If-goto","text":"

Sample code

Go to trueLabel if condition is true, otherwise go to falseLabel.

Format:

#IF,condition,trueLabel,falseLabel\n
  • 1st column of instruction: #IF, case insensitive.
  • conditon: boolean equation
    • this is the scope passed from scenario.load(...)
  • trueLabel/falseLabel: go to this label if condition is true/false
    • run next instruction if label is ''
    • An error event will be fired if label is not found.

Example: Goto label 'AA' if (this.coin > 100), else run next instruction

#IF,this.coin > 100,AA\n
"},{"location":"csvscenario/#wait","title":"Wait","text":"

Run next instruction after a delay time, or scenario.continue(eventName).

Format:

#WAIT,time\n
#WAIT,eventName\n
  • 1st column of instruction: #WAIT, case insensitive.
  • 2nd colume of instruction:
    • a number: a delay time
      • time-unit of delay is set from scenario.load(...)
    • a string: an event name for scenario.continue(eventName)

Example:

  • Wait 1 time-unit
    #WAIT,1\n
  • Wait until 'click'
    #WAIT,click\n
    scenario.continue('click');\n
"},{"location":"csvscenario/#pause","title":"Pause","text":"
scenario.pause();\n
"},{"location":"csvscenario/#resume","title":"Resume","text":"
scenario.resume();\n
"},{"location":"csvscenario/#time-scale","title":"Time-scale","text":"
  • Get
    var timeScale = scenario.timeScale;\n
  • Set
    scenario.setTimeScale(timeScale);\n// scenario.timeScale = timeScale;\n
"},{"location":"csvscenario/#clear","title":"Clear","text":"

Stop running and clear instructions.

scenario.clear();\n
"},{"location":"csvscenario/#states","title":"States","text":"
  • Is running
    var isRunning = scenario.isRunning;\n
  • Is paused
    var isPaused = scenario.isPaused;\n
"},{"location":"csvtoarray/","title":"CSV to array","text":""},{"location":"csvtoarray/#introduction","title":"Introduction","text":"

Generate array from csv string.

  • Reference: Papa Parse
  • Method only
"},{"location":"csvtoarray/#usage","title":"Usage","text":"

Sample code

"},{"location":"csvtoarray/#import-class","title":"Import class","text":"
import rexCSVToArray from './plugins/csvtoarray.js';\n
"},{"location":"csvtoarray/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CSVToArrayPlugin from 'phaser3-rex-plugins/plugins/csvtoarray-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCSVToArray',\nplugin: CSVToArrayPlugin,\nstart: true\n}\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Convert csv
    var arr = scene.plugins.get('rexCSVToArray').convert(csvString, config);\n
"},{"location":"csvtoarray/#convert-csv","title":"Convert csv","text":"
var arr = scene.plugins.get('rexCSVToArray').convert(csvString, {\n// delimiter: ',',\n// convert: true\n});\n

Values will be converted to number (include hex number string like '0xFF'), boolean, null, or string, if convert is true.

"},{"location":"csvtohashtable/","title":"CSV to hash table","text":""},{"location":"csvtohashtable/#introduction","title":"Introduction","text":"

Hash table indexed by (col-key, row-key) from csv string.

  • Author: Rex
  • Member of scene
"},{"location":"csvtohashtable/#usage","title":"Usage","text":"

Sample code

"},{"location":"csvtohashtable/#install-plugin","title":"Install plugin","text":""},{"location":"csvtohashtable/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcsvtohashtableplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcsvtohashtableplugin.min.js', true);\n
  • Add hash-table object
    var table = scene.plugins.get('rexcsvtohashtableplugin').add();\n
"},{"location":"csvtohashtable/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CsvToHashTablePlugin from 'phaser3-rex-plugins/plugins/csvtohashtable-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCsvToHashTable',\nplugin: CsvToHashTablePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add hash-table object
    var table = scene.plugins.get('rexCsvToHashTable').add();\n
"},{"location":"csvtohashtable/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CsvToHashTable from 'phaser3-rex-plugins/plugins/csvtohashtable.js';\n
  • Add hash-table object
    var table = new CsvToHashTable();\n
"},{"location":"csvtohashtable/#create-instance","title":"Create instance","text":"
var table = scene.plugins.get('rexCsvToHashTable').add();\n
"},{"location":"csvtohashtable/#append-rows-from-csv-string","title":"Append rows from csv string","text":"
table.loadCSV(csvString, {\n// delimiter: ',',\n// convert: true\n// convertScope: undefined\n});\n

For exameple, csv string

name hp mp Rex 100 20 Alice 300 40
name,hp,mp\nRex,100,20\nAlice,300,40\n

will be converted to

{\n\"Alice\": {\n\"name\": \"Alice\",\n\"hp\": 300,\n\"mp\": 40\n},\n\"Rex\": {\n\"name\": \"Rex\",\n\"hp\": 100,\n\"mp\": 20\n}\n}\n

Then get value by

var value = table.get('Rex', 'hp');\n
"},{"location":"csvtohashtable/#convert-value-type","title":"Convert value type","text":"

Values will be converted to number (include hex number string like '0xFF'), boolean, null, or string, if convert is true, or assign your convert function by convert and convertScope when loading table (table.loadCSV(...)).

var convertCallback = function(table, rowKey, colKey, value) {\n// value = ...\nreturn value;\n};\n

Or uses these metheds to convert columns or rows.

  • convert values in column
    table.convertCol(colKey);  // colKey: a colKey, or an array of colKeys\n// table.convertCol(colKey, convertCallback, convertCallbackScope);\n
  • convert values in row
    table.convertRow(rowKey);  // rowKey: a rowKey, or an array of rowKeys\n// table.convertRow(rowKey, convertCallback, convertCallbackScope);\n
"},{"location":"csvtohashtable/#get-value","title":"Get value","text":"
var val = table.get(rowKey, colKey);\n
  • rowKey : Row key string, or row index number.
  • colKey : Column key string, or column index number.
"},{"location":"csvtohashtable/#set-value","title":"Set value","text":"
table.set(rowKey, colKey, value);\n
table.add(rowKey, colKey, value);\n// equal to table.set(rowKey, colKey, table.get(rowKey, colKey) + value);\n
  • rowKey : Row key string, or row index number.
  • colKey : Column key string, or column index number.
"},{"location":"csvtohashtable/#has-columnrow-key","title":"Has column/row key","text":"
var hasRow = table.hasRowKey(rowKey);\n
var hasCol = table.hasColKey(colKey);\n
var hasCell = table.hasKey(rowKey, colKey);\n
  • rowKey : Row key string, or row index number.
  • colKey : Column key string, or column index number.
"},{"location":"csvtohashtable/#value-in-column-or-row","title":"Value in column or row","text":"
var existed = table.isValueInRol(rowKey, value);\n
var existed = table.isValueInCol(colKey, value);\n
  • rowKey : Row key string, or row index number.
  • colKey : Column key string, or column index number.
"},{"location":"csvtohashtable/#create-table","title":"Create table","text":""},{"location":"csvtohashtable/#clear-table","title":"Clear table","text":"
table.clear();\n
"},{"location":"csvtohashtable/#append-a-column","title":"Append a column","text":"
table.appendCol(colKey, initValue);\n// table.appendCol(colKey, callback, scope);  // get initValue from callback\n

Callback

var callback = function (table, rowKey, colKey) { // value = ...\nreturn value;\n};\n
  • colKey : Column key string, or column index number.
"},{"location":"csvtohashtable/#append-a-row","title":"Append a row","text":"
table.appendRow(rowKey, initValue);\n// table.appendRow(rowKey, callback, scope);  // get initValue from callback\n

Callback

var callback = function (table, rowKey, colKey) { // value = ...\nreturn value;\n};\n
  • rowKey : Row key string, or row index number.
"},{"location":"csvtohashtable/#remove-a-column","title":"Remove a column","text":"
table.removeCol(colKey);\n
  • colKey : Column key string, or column index number.
"},{"location":"csvtohashtable/#remove-a-row","title":"Remove a row","text":"
table.removeRol(rowKey);\n
  • rowKey : Row key string, or row index number.
"},{"location":"csvtohashtable/#sort-column-or-row","title":"Sort column or row","text":"
table.sortCol(colKey, mode);\n// table.sortCol(callback, scope);  // sort columns by callback\n
table.sortRow(rowKey, mode);\n// table.sortRow(callback, scope);  // sort rows by callback\n
  • rowKey : Row key string, or row index number.
  • colKey : Column key string, or column index number.

Mode:

  • 'ascending', or 0
  • 'descending', or 1
  • 'logical ascending', or 2
  • 'logical descending', or 3

Sorting callback

var callback = function(rowKeyA, rowKeyB) {\nreturn result; // 1, -1, or 0\n};\n
"},{"location":"csvtohashtable/#retrieve-columns-or-rows","title":"Retrieve columns or rows","text":"
table.eachCol(rowKey, callback, scope);\n
table.eachRow(colKey, callback, scope);\n
  • rowKey : Row key string, or row index number.
  • colKey : Column key string, or column index number.

Callback

var callback = function(table, rowKey, colKey, value) {\n// ...\n};\n
"},{"location":"csvtohashtable/#json","title":"JSON","text":"
  • Table to json
    var jsonData = table.toJSON();\n
  • Reset table by JSON
    table.resetFromJSON(jsonData);\n
"},{"location":"cursor/","title":"Cursor","text":""},{"location":"cursor/#introduction","title":"Introduction","text":"

Custom cursor, built-in feature of phaser.

  • Author: Richard Davey
"},{"location":"cursor/#usage","title":"Usage","text":"

References:

  • Cursor
  • Using URL values for the cursor property
"},{"location":"cursor/#set-default-cursor","title":"Set default cursor","text":"
scene.input.setDefaultCursor(CSSString);\n// CSSString: 'url(assets/input/cursors/sword.cur), pointer'\n
"},{"location":"cursor/#set-cursor-of-a-game-object","title":"Set cursor of a Game Object","text":"

Change cursor image when cursor is over that Game Object.

gameObject.setInteractive({\ncursor: CSSString\n});\n// CSSString: 'url(assets/input/cursors/sword.cur), pointer'\n

Set cursor image directly after gameObject.setInteractive().

gameObject.input.cursor = CSSString;\n// CSSString: 'url(assets/input/cursors/sword.cur), pointer'\n

Use pointer (hand cursor).

gameObject.setInteractive({\nuseHandCursor: true\n});\n
"},{"location":"cursor/#change-current-cursor","title":"Change current cursor","text":"
scene.input.canvas.style.cursor = cursor;\n
  • cursor : CSSString

or

scene.input.setCursor(gameObject.input);\n
"},{"location":"cursor/#reset-to-default-cursor","title":"Reset to default cursor","text":"
scene.input.resetCursor(null, true);\n
"},{"location":"cursoratbounds/","title":"Cursor at bounds","text":""},{"location":"cursoratbounds/#introduction","title":"Introduction","text":"

Map cursor-at-(left/right/top/botttom-)bound to (left/right/up/down) cursor key state.

  • Author: Rex
  • Member of scene
"},{"location":"cursoratbounds/#live-demos","title":"Live demos","text":"
  • Custom bounds
  • Camera scrolling
"},{"location":"cursoratbounds/#usage","title":"Usage","text":"

Sample code

"},{"location":"cursoratbounds/#install-plugin","title":"Install plugin","text":""},{"location":"cursoratbounds/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcursoratboundsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcursoratboundsplugin.min.js', true);\n
  • Add cursor-at-bound object
    var cursorAtBound = scene.plugins.get('rexcursoratboundsplugin').add(scene, config);\n
"},{"location":"cursoratbounds/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CursorAtBoundsPlugin from 'phaser3-rex-plugins/plugins/cursoratboundss-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCursorAtBounds',\nplugin: CursorAtBoundsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add cursor-at-bound object
    var cursorAtBound = scene.plugins.get('rexCursorAtBounds').add(scene, config);\n
"},{"location":"cursoratbounds/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CursorAtBounds from 'phaser3-rex-plugins/plugins/cursoratboundss.js';\n
  • Add cursor-at-bound object
    var cursorAtBound = new CursorAtBounds(scene, config);\n
"},{"location":"cursoratbounds/#create-instance","title":"Create instance","text":"
var cursorAtBound = scene.plugins.get('rexCursorAtBounds').add(scene, {\n// enable: true,\n// bounds: undefined,\n// sensitiveDistance: 20,\n// pointerOutGameRelease: true,\n// pointerOutBoundsRelease: false,\n});\n
  • bounds : A rectangle object for detecting the position of cursor.
    • undefined : Current viewport. Will update bounds when window resizing.
  • sensitiveDistance : A sensitive distance in pixels.
  • pointerOutGameRelease :
    • true : All cursor keys are released when pointer is out of game window. Default behavior.
    • false : Don't change status of cursor keys when pointer is out of game window.
  • pointerOutBoundsRelease
    • true : All cursor keys are released when pointer is out of bounds.
    • false : Continue cursor key detection when pointer is out of bounds. Default behavior.

Map position of cursor to state of cursor key

  • left cursor key is pressed :
    • Position x is between left bound and left bound + sensitive distance
    • Position x at left side of left bound, if pointerOutBoundsRelease is false
  • Right cursor key is pressed :
    • Position x is between right bound and right bound - sensitive distance
    • Position x at right side of right bound, if pointerOutBoundsRelease is false
  • Up cursor key is pressed :
    • Position y is between top bound and top bound + sensitive distance
    • Position y at up side of top bound, if pointerOutBoundsRelease is false
  • Down cursor key is pressed :
    • Position y is between bottom bound and bottom bound - sensitive distance
    • Position y at down side of bottom bound, if pointerOutBoundsRelease is false
"},{"location":"cursoratbounds/#state-of-cursor-keys","title":"State of cursor keys","text":"
var cursorKeys = cursorAtBound.createCursorKeys();\n\nvar leftKeyDown = cursorKeys.left.isDown;\nvar rightKeyDown = cursorKeys.right.isDown;\nvar upKeyDown = cursorKeys.up.isDown;\nvar downKeyDown = cursorKeys.down.isDown;\n

Or

var leftKeyDown = cursorAtBound.left;\nvar rightKeyDown = cursorAtBound.right;\nvar upKeyDown = cursorAtBound.up;\nvar downKeyDown = cursorAtBound.down;\nvar noKeyDown = cursorAtBound.noKey;\n
"},{"location":"cursoratbounds/#destroy","title":"Destroy","text":"
cursorAtBound.destroy();\n
"},{"location":"cursoratbounds/#enable","title":"Enable","text":"
  • Get
    var enable = joystick.enable;\n
  • Set
    joystick.setEnable(enable);  // enable: true, or false\n//joystick.enable = enable;\n
  • Toggle
    joystick.toggleEnable();\n
"},{"location":"cursoratbounds/#bounds","title":"Bounds","text":"
  • Get
    var bounds = cursorAtBound.bounds;\n
    • bounds : A rectangle object
  • Set
    cursorAtBound.setBounds(bounds);\n
    or
    cursorAtBound.bounds = bounds;;\n
    • bounds : A rectangle object
"},{"location":"cursoratbounds/#sensitive-distance","title":"Sensitive distance","text":"
  • Get
    var distance = cursorAtBound.sensitiveDistance;\n
  • Set
    cursorAtBound.setSensitiveDistance(distance);\n
    or
    cursorAtBound.sensitiveDistance = distance;\n
"},{"location":"curve-spiral/","title":"Spiral curve","text":""},{"location":"curve-spiral/#introduction","title":"Introduction","text":"

Spiral curve.

  • Author: Rex
  • Curve object
"},{"location":"curve-spiral/#live-demos","title":"Live demos","text":"
  • Spiral curve
  • Particles along spiral curve
"},{"location":"curve-spiral/#usage","title":"Usage","text":"

Sample code

"},{"location":"curve-spiral/#install-plugin","title":"Install plugin","text":""},{"location":"curve-spiral/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexspiralcurveplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexspiralcurveplugin.min.js', true);\n
  • Add spiral curve object
    var spiral = scene.plugins.get('rexspiralcurveplugin').add(config);\n
"},{"location":"curve-spiral/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SpiralCurvePlugin from 'phaser3-rex-plugins/plugins/spiralcurve-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexSpiralCurve',\nplugin: SpiralCurvePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add spiral curve object
    var spiral = scene.plugins.get('rexSpiralCurve').add(config);\n
"},{"location":"curve-spiral/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import SpiralCurve from 'phaser3-rex-plugins/plugins/spiralcurve.js';\n
  • Add spiral curve object
    var spiral = new SpiralCurve(config);\n
"},{"location":"curve-spiral/#create-shape","title":"Create shape","text":"
  • All properties
    var spiral = scene.plugins.get('rexSpiralCurve').add({\n// Origin point\n// Ease origin point\n// startX:0, endX: 0, easeX: 'Linear',\n// startY:0, endY: 0, easeY: 'Linear',\n// Fixed point\n// x, y,\n\n// x-radius\n// startXRadius: 0, endXRadius, easeXRadius: 'Linear',\n// y-radius\n// startYRadius: 0, endYRadius, easeYRadius: 'Linear',\n// start-end radius\n// startRadius, endRadiux\n\n// angle\n// startAngle: 0, endAngle: 360, easeAngle: 'Linear',\n\n// rotation: 0\n});\n
    • Origin point
      • startX, endX, easeX, startY, endY, easeY : Ease origin point.
        • easeX, easeY : Ease equation, default value is 'Linear'.
      • x, y : Fixed origin point, i.e. start point is equal to end point.
    • Radius
      • startXRadius, endXRadius, easeXRadius : Ease x-radius.
        • easeXRadius : Ease equation, default value is 'Linear'.
      • startYRadius, endYRadius, easeYRadius : Ease y-radius.
        • easeYRadius : Ease equation, default value is 'Linear'.
      • startRadius, endRadiux :
        • Set startXRadius, and startYRadius to startRadius.
        • Set endXRadius, and endYRadius to endRadius.
    • Angle
      • startAngle, endAngle, easeAngle : Ease angle, in degrees.
        • easeAngle : Ease equation, default value is 'Linear'.
    • rotation : Rotate curve.
  • Simple spiral curve
    var spiral = scene.plugins.get('rexSpiralCurve').add(x, y, startRadius, endRadius, startAngle, endAngle, rotation);\n
    • x : Set startX, endX to x, and easeX to 'Linear'.
    • y : Set startY, endY to y, and easeY to 'Linear'.
    • startRadius : Set startXRadius, startYRadius to startRadius
    • endRadius : Set endXRadius, endYRadius to endRadius, and easeXRadius, easeYRadius to Linear.
    • Set easeAngle to 'Linear'
"},{"location":"curve-spiral/#properties","title":"Properties","text":"
  • Origin point
    • Get
      var startX = spiral.startX;\nvar startY = spiral.startY;\nvar endX = spiral.endX;\nvar endY = spiral.endY;\n
      or
      var startPoint = spiral.p0; // {x, y}\nvar endPoint = spiral.p1; // {x, y}\n
    • Set
      spiral.setStartX(x);\nspiral.setStartY(y);\nspiral.setEndX(x);\nspiral.setEndY(y);\n
      or
      spiral.startX = x;\nspiral.startY = y;\nspiral.endX = x;\nspiral.endY = y;\n
  • Radius
    • Get
      var startXRadius = spiral.startXRadius;\nvar startYRadius = spiral.startYRadius;\nvar endXRadius = spiral.endXRadius;\nvar endYRadius = spiral.endYRadius;\n
    • Set
      spiral.setStartXRadius(startXRadius);\nspiral.setStartYRadius(startYRadius);\nspiral.setEndXRadius(endXRadius);\nspiral.setEndYRadius(endYRadius);\n
      or
      spiral.startXRadius = startXRadius;\nspiral.startYRadius = startYRadius;\nspiral.endXRadius = endXRadius;\nspiral.endYRadius = endYRadius;\n
  • Angle, in degrees.
    • Get
      var startAnlge = spiral.startAngle;\nvar endAnlge = spiral.endAngle;\n
    • Set
      spiral.setStartAngle(startAnlge);\nspiral.setEndAngle(endAnlge);\n
      spiral.startAngle = startAnlge;\nspiral.endAngle = endAnlge;\n
"},{"location":"curve-spiral/#other-methods","title":"Other methods","text":"

See path

"},{"location":"cutjigsawimage/","title":"Cut Jigsaw Image","text":""},{"location":"cutjigsawimage/#introduction","title":"Introduction","text":"

Cut image into pieces for jigsaw application.

  • Author: Rex
  • Method only
"},{"location":"cutjigsawimage/#live-demos","title":"Live demos","text":"
  • Create pieces
  • Custom piece shape
  • Drag drop with pixelPerfect
"},{"location":"cutjigsawimage/#usage","title":"Usage","text":"

Sample code

"},{"location":"cutjigsawimage/#install-plugin","title":"Install plugin","text":""},{"location":"cutjigsawimage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcutjigsawimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcutjigsawimageplugin.min.js', true);\n
  • Cut image into pieces
    var pieces = scene.plugins.get('rexcutjigsawimageplugin').gridCut(gameObject, config);\n
"},{"location":"cutjigsawimage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CutJigsawImagePlugin from 'phaser3-rex-plugins/plugins/cutjigsawimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCutJigsawImage',\nplugin: CutJigsawImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Cut image into pieces
    var pieces = scene.plugins.get('rexCutJigsawImage').gridCut(gameObjects, config);\n
"},{"location":"cutjigsawimage/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import CutJigsawImage from 'phaser3-rex-plugins/plugins/cutjigsawimage.js';\n
  • Cut image into pieces
    var images = CutJigsawImage(gameObjects, config);\n
"},{"location":"cutjigsawimage/#create-pieces","title":"Create pieces","text":"
var pieces = scene.plugins.get('rexCutJigsawImage').gridCut(gameObject, {\npiecesKey: ,\ncolumns: , rows: ,\nedgeWidth: , edgeHeight: ,\nuseDynamicTexture: true,\n\n// drawShapeCallback: undefined,\n// edges: undefined,    \n\n// createImageCallback: undefined,\n// ImageClass: Phaser.GameObjects.Image,\n\n// originX: 0.5,\n// originY: 0.5,\n// add: true,\n// align: true,\n// objectPool: undefined\n});\n
  • gameObjects : Target game object which has a texture, ex Image, RenderTexture.
  • piecesKey : Store frame of each piece in this dynamic texture.
    • undefined : Use 'gameObjects.texture.key' + '_pieces' as texture key.
  • columns, rows : Cut texture in columns x rows grids
  • edgeWidth, edgeHeight : Padding around piece.
  • useDynamicTexture : Generate frame of pieces on dynamic texture or canvas texture.
    • true : Generate frame of pieces on dynamic texture. Default value.
    • false : Generate frame of pieces on canvas texture.
  • drawShapeCallback : Callback of creating piece shape
    • undefined : Use default piece shape.
    • A function object
      function(graphics, width, height, edgeWidth, edgeHeight, edgeMode) {\n}\n
      • graphics : Graphics game object, or canvas.
        • Draw piece shape on a Graphics game object, if useDynamicTexture is set to true
        • Draw piece shape on canvas, if useDynamicTexture is set to false
      • width, height : Frame size of this piece
      • edgeWidth, edgeHeigh : Padding around piece.
      • edgeMode :
        {\nleft: 0,   // 0|1|2\nright: 0,  // 0|1|2\ntop: 0,    // 0|1|2\nbottom: 0  // 0|1|2\n}\n
        • left, right, top, bottom
          • 0 : Flat edge
          • 1 : Convex edge
          • 2 : Concave edge
  • edges : edgeMode in a 2d array for each piece
    • undefined : Create random edges for each piece.
  • createImageCallback : Custom callback to return an image game object, optional.
    function(scene, texture, frame) {\nreturn gameObject;\n}\n
    • texture : A texture object.
    • frame : Frame name.
  • ImageClass : Create image game object from this class. Default value is built-in Image class. Used when createImageCallback is undefined.
  • originX, originY : Origin of created image game objects
  • add :
    • true : Add these created image game objects to scene. Default value.
    • false : Don't add created image game objects to scene.
  • align :
    • true : Align position of created image game objects to target game object (gameObjects). Default value when add is set to true.
    • false : Don't set position of created image game objects. Default value when add is set to false.
  • objectPool : An array of image game objects, will reuse image game objects from this pool. Optional.
  • pieces : Return piece game objects.
    • Size of any piece game object (frame size) :
      • width : (gameObjects.width / columns) + (2 * edgeWidth)
      • height : (gameObjects.height / rows) + (2 * edgeHeigh)
    • Frame name of a piece game object : columnIndex + ',' + rowIndex
"},{"location":"datamanager/","title":"Built-in data","text":""},{"location":"datamanager/#introduction","title":"Introduction","text":"

Store data in key-value pairs, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"datamanager/#usage","title":"Usage","text":""},{"location":"datamanager/#write","title":"Write","text":""},{"location":"datamanager/#set-value","title":"Set value","text":"
  • Set value
    parent.data.set(key, value);\n
    or
    parent.data.values[key] = value;\n
    • key : Key string.
  • Increase number value. If the key doesn't already exist in the Data Manager then it is increased from 0.
    parent.data.inc(key, data);\n
    or
    parent.data.values[key] += value;\n
    • data : The value to increase.
  • Toggle boolean value. If the key doesn't already exist in the Data Manager then it is toggled from false.
    parent.data.toggle(key);\n
    or
    parent.data.values[key] = !parent.data.values[key];\n
"},{"location":"datamanager/#set-values","title":"Set values","text":"
parent.data.set(data);    // data: {key:value, ...}\n
"},{"location":"datamanager/#merge-values","title":"Merge values","text":"
parent.data.merge(data);  // data: {key:value, ...}\nparent.data.merge(data, false);  // won't overwrite existed keys\n
"},{"location":"datamanager/#events","title":"Events","text":"

Fires setdata event when a value is first set.

parent.data.events.on('setdata', function(parent, key, value){ /* ... */ });\n

Fires changedata, and changedata- + key events when a value is set that already exists.

parent.data.events.on('changedata', function(parent, key, value, previousValue){ /* ... */ });\n
parent.data.events.on('changedata-' + key, function(parent, value, previousValue){ /* ... */ });\n
"},{"location":"datamanager/#read","title":"Read","text":""},{"location":"datamanager/#get-value","title":"Get value","text":"

var value = parent.data.get(key);\n
or
var value = parent.data.values[key];\n

"},{"location":"datamanager/#get-values","title":"Get values","text":"
var values = parent.data.get(keys); // values: [value, value, ...], keys: [key, key, ...]\n
"},{"location":"datamanager/#get-all-values","title":"Get all values","text":"
var allValues = parent.data.getAll();  // return a copy of data\n
"},{"location":"datamanager/#query","title":"Query","text":"

Using string.match() to pick matched keys.

var result = parent.data.query(rgExp);\n
"},{"location":"datamanager/#remove","title":"Remove","text":""},{"location":"datamanager/#remove-key","title":"Remove key","text":"
parent.data.remove(key);\n
"},{"location":"datamanager/#remove-keys","title":"Remove keys","text":"
parent.data.remove(keys);  // keys: [key, key, ...]\n
"},{"location":"datamanager/#pop-key","title":"Pop key","text":"
var value = parent.data.pop(key);\n

Get and remove that key.

"},{"location":"datamanager/#delet-all-keys","title":"Delet all keys","text":"

Delete all data in this Data Manager and unfreeze it.

parent.data.reset();\n
"},{"location":"datamanager/#events_1","title":"Events","text":"

Fires removedata event when a key is removed.

parent.data.events.on('removedata', function(parent, key, value){ /* ... */ });\n
"},{"location":"datamanager/#freeze","title":"Freeze","text":"
var isFrozen = parent.data.freeze;\nparent.data.freeze = true;\n

No changes can be written to it.

"},{"location":"datamanager/#has-key","title":"Has key","text":"
var hasKey = parent.data.has(key);\n
"},{"location":"datamanager/#for-each-key","title":"For each key","text":"
parent.data.each(function(parent, key, value){\n/* ... */\n}, scope);\n
"},{"location":"datamanager/#count-of-data","title":"Count of data","text":"
var cnt = parent.data.count;\n
"},{"location":"datamanager/#reset","title":"Reset","text":"

Reset status and clear all keys.

parent.data.reset()\n
"},{"location":"date/","title":"Date","text":""},{"location":"date/#introduction","title":"Introduction","text":"

Get current date or unix-timestamp.

  • Author: Built-in javascript function
"},{"location":"date/#usage","title":"Usage","text":"

Reference

"},{"location":"date/#create-instance","title":"Create instance","text":"
var d = new Date();\nvar d = new Date(timestamp);\nvar d = new Date(dateString);\nvar d = new Date(year, month, day, hours, minutes, seconds, milliseconds);\n
"},{"location":"date/#get-date","title":"Get date","text":"
var year = d.getFullYear();    // returns the year\nvar month = d.getMonth();      // returns the month (0-11)\nvar date = d.getDate();        // returns the day of the month (1-31)\nvar day = d.getDay();          // returns the day of the week\nvar hour = d.getHours();       // returns the hour (0-23)\nvar min = d.getMinutes();      // returns the minutes (0-59)\nvar sec = d.getSeconds();      // returns the seconds (0-59)\nvar ms = d.getMilliseconds();  // returns the milliseconds (0-999)\n
"},{"location":"date/#get-unix-timestamp","title":"Get unix-timestamp","text":"
var timestamp = d.getTime();;   // unix-timestamp in milliseconds\n

or

var timestamp = Date.now();;    // unix-timestamp in milliseconds\n
"},{"location":"date/#to-string","title":"To string","text":"
var s = d.toLocaleString();   // locale conventions\nvar iso = d.toISOString();    // ISO standard\n
"},{"location":"device/","title":"Device","text":""},{"location":"device/#introduction","title":"Introduction","text":"

Get information of device, built-in properties of phaser.

  • Author: Richard Davey
"},{"location":"device/#usage","title":"Usage","text":""},{"location":"device/#os","title":"OS","text":"
  • Platform
    scene.sys.game.device.os.android      // Is running on android?\nscene.sys.game.device.os.chromeOS     // Is running on chromeOS?\nscene.sys.game.device.os.cordova      // Is the game running under Apache Cordova?\nscene.sys.game.device.os.crosswalk    // Is the game running under the Intel Crosswalk XDK?\nscene.sys.game.device.os.desktop      // Is running on a desktop?\nscene.sys.game.device.os.ejecta       // Is the game running under Ejecta?\nscene.sys.game.device.os.electron     // Is the game running under GitHub Electron?\nscene.sys.game.device.os.iOS          // Is running on iOS?\nscene.sys.game.device.os.iPad         // Is running on iPad?\nscene.sys.game.device.os.iPhone       // Is running on iPhone?\nscene.sys.game.device.os.kindle       // Is running on an Amazon Kindle?\nscene.sys.game.device.os.linux        // Is running on linux?\nscene.sys.game.device.os.macOS        // Is running on macOS?\nscene.sys.game.device.os.node         // Is the game running under Node.js?\nscene.sys.game.device.os.nodeWebkit   // Is the game running under Node-/Webkit?\nscene.sys.game.device.os.webApp       // Set to true if running as a WebApp, i.e. within a WebView\nscene.sys.game.device.os.windows      // Is running on windows?\nscene.sys.game.device.os.windowsPhone // Is running on a Windows Phone?\n
  • Major version number of ios
    var version = scene.sys.game.device.os.iOSVersion;\n
  • Pixel-ratio of the host device
    var pixelRatio = scene.sys.game.device.os.pixelRatio;\n
"},{"location":"device/#browser","title":"Browser","text":"
  • Platform
    scene.sys.game.device.browser.chrome       // Is running in Chrome?\nscene.sys.game.device.browser.edge         // Is running in Microsoft Edge browser?\nscene.sys.game.device.browser.firefox      // Is running in Firefox?\nscene.sys.game.device.browser.ie           // Is running in Internet Explorer 11 or less (not Edge)?\nscene.sys.game.device.browser.mobileSafari // Is running in Mobile Safari?\nscene.sys.game.device.browser.opera        // Is running in Opera?\nscene.sys.game.device.browser.safari       // Is running in Safari?\nscene.sys.game.device.browser.silk         // Is running in the Silk browser (as used on the Amazon Kindle)?\nscene.sys.game.device.browser.trident       // Is running a Trident version of Internet Explorer (IE11+)?\n
  • Version
    var version = scene.sys.game.device.browser.chromeVersion;\nvar version = scene.sys.game.device.browser.firefoxVersion;\nvar version = scene.sys.game.device.browser.ieVersion;\nvar version = scene.sys.game.device.browser.safariVersion;\nvar version = scene.sys.game.device.browser.tridentVersion;\n
"},{"location":"device/#audio","title":"Audio","text":"
var flac = scene.sys.game.device.audio.flac;\nvar aac = scene.sys.game.device.audio.aac;\nvar dolby = scene.sys.game.device.audio.dolby;\nvar m4a = scene.sys.game.device.audio.m4a;\nvar mp3 = scene.sys.game.device.audio.mp3;\nvar ogg = scene.sys.game.device.audio.ogg;\nvar opus = scene.sys.game.device.audio.opus;\nvar wav = scene.sys.game.device.audio.wav;\nvar webm = scene.sys.game.device.audio.webm;\nvar webAudio = scene.sys.game.device.audio.webAudio;\nvar audioData = scene.sys.game.device.audio.audioData;\n
"},{"location":"device/#video","title":"Video","text":"
var h264Video = scene.sys.game.device.video.h264;  // Can this device play h264 mp4 video files?\nvar hlsVideo = scene.sys.game.device.video.hls;    // Can this device play hls video files?\nvar mp4Video = scene.sys.game.device.video.mp4;    // Can this device play h264 mp4 video files?\nvar m4vVideo = scene.sys.game.device.video.m4v;    // Can this device play m4v (typically mp4) video files?\nvar oggVideo = scene.sys.game.device.video.ogg;    // Can this device play ogg video files?\nvar vp9Video = scene.sys.game.device.video.vp9;    // Can this device play vp9 video files?\nvar webmVideo = scene.sys.game.device.video.webm;  // Can this device play webm video files?\n
"},{"location":"dialog-quest/","title":"Dialog-quest","text":""},{"location":"dialog-quest/#introduction","title":"Introduction","text":"

Flow control of question manager with a dialog.

  • Author: Rex
  • Template
"},{"location":"dialog-quest/#live-demos","title":"Live demos","text":"
  • Branch
  • Shuffle
"},{"location":"dialog-quest/#usage","title":"Usage","text":"

Sample code

"},{"location":"dialog-quest/#install-plugin","title":"Install plugin","text":""},{"location":"dialog-quest/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');    scene.load.script('rexdialogquest', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdialogquest.min.js');\n
  • Add dialog and quest object
    var dialog = scene.rexUI.add.dialog(config); var quest = new rexdialogquest({\ndialog: dialog,\n// ...\n});\n
"},{"location":"dialog-quest/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nimport DialogQuest from 'phaser3-rex-plugins/templates/dialog-quest/DialogQuest.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add dialog and quest object
    var dialog = scene.rexUI.add.dialog(config); var quest = new DialogQuest({\ndialog: dialog,\n// ...\n});\n
"},{"location":"dialog-quest/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Dialog } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\nimport DialogQuest from 'phaser3-rex-plugins/templates/dialog-quest/DialogQuest.js';\n
  • Add dialog object
    var dialog = new Dialog(scene, config);\nscene.add.existing(dialog);\nvar quest = new DialogQuest({\ndialog: dialog,\n// ...\n});\n
"},{"location":"dialog-quest/#create-dialog-quest-object","title":"Create dialog-quest object","text":"
var quest = new DialogQuest({\ndialog: dialog,\n\nquestions: undefined,\n// format: undefined,\n// delimiter: ',',\n// types: {\n//     question: 'q',\n//     option: '',\n// },\n// convert: true,\n\nquest: true,\n// quest: {\n//     shuffleQuestions: false,\n//     shuffleOptions: false,\n// }\n});\n
  • dialog : A dialog game object.
    • UI plugin does not included in this template, install it before creating a dialog game object.
    • Reuse/update dialog game object for each question.
    • The number of choice buttons should be equal or larger than the maximun number of options.
  • Other parameters : See quest
"},{"location":"dialog-quest/#flow-chart","title":"Flow chart","text":"
graph TB\n\nStart[\"quest.start()\"] --> EventUpdateChoice[\"quest.emit('update-choice', choice, option, quest)<br>----<br>Update each choice button via question.option[i]\"]\n\nEventUpdateChoice --> EventUpdateDialog[\"quest.emit('update-dialog', dialog, question, quest)<br>----<br>Update dialog, action button via question\"]\n\nEventUpdateDialog --> EventClickChoice[\"quest.emit('click-choice', choice, dialog, quest)<br>----<br>Click any choice button\"]\n\nEventClickChoice --> EventClickAction[\"quest.emit('click-action', action, dialog, quest)<br>----<br>Click any action button\"]\n\nEventClickAction --> IsLast{\"quest.isLast()\"}\nEventClickChoice --> IsLast\n\nIsLast --> |No| Next[\"quest.next()\"]\nIsLast --> |Yes| Complete(\"Complete\")\n\nNext --> EventUpdateChoice
"},{"location":"dialog-quest/#events","title":"Events","text":"
  • Update dialog events
    • Update each choice button via question.option[i]
      quest.on('update-choice', function(choice, option, quest){\n}, scope);\n
      • choice : Choice button game object.
        • Unused choice button game object will be hideen.
      • option : Option object.
      • quest : Quest object.
    • Update dialog, action buttos via question
      quest.on('update-dialog', function(dialog, question, quest){\n}, scope);\n
      • dialog : Dialog game object.
        • Call dialog.layout() if needs.
      • question : Question object.
      • quest : Quest object.
  • Button clicking events
    • Click choice button
      quest.on('click-choice', function(choice, dialog, quest) {\n\n}, scope);\n
      • choice : Clicked choice button game object.
      • dialog : Dialog game object.
      • quest : Quest object.
    • Click choice button
      quest.on('click-action', function(action, dialog, quest) {\n\n}, scope);\n
      • choice : Clicked action button game object.
      • dialog : Dialog game object.
      • quest : Quest object.
"},{"location":"dialog-quest/#quest-methods","title":"Quest methods","text":"
  • Start quest
    quest.start();\n
  • Next quest
    quest.next();\n
    or
    quest.next(key);\n
  • Is last question
    var isLast = quest.isLast();\n
  • Remove all questions
    quest.removeAll();\n
  • Add questions
    quest.add(questions, config);\n
    • questions : An array of question objects, or a csv string. See questions section in Create question manager instance section.
    • config :
      • delimiter : Delimiter of csv string. Default value is ','
      • types : Define value of row type.
        • types.question : Define value of question row. Default value is q.
        • types.option : Define value of option row. Default value is '' (empty string).
      • convert : Convert string values to other types.
        • Default type converting : Convert string to number, boolean, null, or string
          • '0', '1', ... (number string) -> number
          • 'true', or 'false' -> true or false
          • '' (empty string) -> null
          • Others : string.
        • Set false to ignore types converting, i.e. all values are string.
        • A custom type converting function :
          function(stringValue, key) {\n// return value;\n}\n
"},{"location":"dialog-quest/#private-data-methods","title":"Private data methods","text":"
  • Get data
    var value = quest.getData(key, defaultValue);\n
  • Get all data
    var data = quest.getData();\n
  • Set value
    quest.setData(key, value);\n
  • Increase value
    quest.incData(key, inc, defaultValue);\n
  • Multiple value
    quest.mulData(key, mul, defaultValue);\n
  • Clear all data
    quest.clearData();\n
"},{"location":"distance/","title":"Distance","text":""},{"location":"distance/#introduction","title":"Introduction","text":"

Get distance, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"distance/#usage","title":"Usage","text":""},{"location":"distance/#distance","title":"Distance","text":"
  • Get distance between 2 points
    var d = Phaser.Math.Distance.Between(x1, y1, x2, y2);\n
    or
    var d = Phaser.Math.Distance.BetweenPoints(a, b); // a, b: {x, y}\n
  • Get squared distance
    var d = Phaser.Math.Distance.BetweenPointsSquared(a, b); // a, b: {x, y}\n
  • Get Chebyshev distance (the maximum of the horizontal and vertical distances)
    var d = Phaser.Math.Distance.Chebyshev(x1, y1, x2, y2);\n
  • Get snake distance(i.e. rectilinear distance, Manhattan distance, the sum of the horizontal and vertical distance)
    var d = Phaser.Math.Distance.Snake(x1, y1, x2, y2);\n
  • Get power distance (the sum of the horizontal power distance and vertical power distance)
    var d = Phaser.Math.Distance.Power(x1, y1, x2, y2);\n
"},{"location":"distance/#speed","title":"Speed","text":"
  • Get speed
    var d = Phaser.Math.GetSpeed(distance, time);\n
    • distance : The distance to travel in pixels.
    • time : The time, in ms, to cover the distance in.
"},{"location":"domelement/","title":"DOM element","text":""},{"location":"domelement/#introduction","title":"Introduction","text":"

Carry DOM element, built-in game object of phaser.

Limitations

Dom elements appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have a DOM Element, then a Sprite, then another DOM Element behind it.

  • Author: Richard Davey
"},{"location":"domelement/#usage","title":"Usage","text":""},{"location":"domelement/#configuration","title":"Configuration","text":"
  • Set parent to divId
  • Set dom.createContainer to true.
var config = {\n// ...\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n}\nvar game = new Phaser.Game(config);\n
"},{"location":"domelement/#add-dom-element-object","title":"Add DOM element object","text":""},{"location":"domelement/#add-html-string","title":"Add html string","text":"
  1. Load html string in preload stage
    scene.load.html(key, url);\n
    Reference: load html
  2. Add DOM element object with html string from cache
    var domElement = scene.add.dom(x, y).createFromCache(key);  // elementType = 'div'\n// var domElement = scene.add.dom(x, y).createFromCache(key, elementType);\n
    • Add DOM element object with html string
      var domElement = scene.add.dom(x, y).createFromHTML(htmlString);  // elementType = 'div'\n// var domElement = scene.add.dom(x, y).createFromHTML(htmlString, elementType);\n
      • `elementType : The tag name of the element into which all of the html will be inserted. Defaults to a plain div tag.
"},{"location":"domelement/#create-element","title":"Create element","text":"
scene.add.dom(x, y).createElement(tagName);\n// scene.add.dom(x, y).createElement(tagName, style, innerText);\n
  • tagName : A string that specifies the type of element to be created. For example, 'div'
  • style : Either a DOMString that holds the CSS styles to be applied to the created element, or an object the styles will be readyfrom. Optional.
  • innerText : A DOMString that holds the text that will be set as the innerText of the created element. Optional.
"},{"location":"domelement/#add-existing-dom","title":"Add existing DOM","text":"
  1. Create DOM element
    var el = document.createElement('div');\n// el.style = '...';\n// el.innerText = '...';\n
  2. Add to scene
    var domElement = scene.add.dom(x, y, el);\n// var domElement = scene.add.dom(x, y, el, style, innerText);\n
"},{"location":"domelement/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDOMElement extends Phaser.GameObjects.DOMElement {\nconstructor(scene, x, y, element, style, innerText) {\nsuper(scene, x, y, element, style, innerText);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var domElement = new MyDOMElement(scene, x, y, element);\n
"},{"location":"domelement/#event-of-dom-element","title":"Event of DOM element","text":"
  • Add listener
    domElement.addListener(eventName);\n
    • eventName : Event name
      • Single string. ex. 'click'
      • Event name joined with ' '
  • Add event handler
    var callback = function(event) {\n// event.target.name\n};\ndomElement.on(eventName, callback, scope);\n// domElement.once(eventName, callback, scope);\n
    Reference: event emitter
  • Remove listener
    domElement.removeListener(eventName);\n
    • eventName : Event name
      • Single string. ex. 'click'
      • Event name joined with ' '
"},{"location":"domelement/#get-child","title":"Get child","text":"
  • Get child by name
    var child = domElement.getChildByName(name)\n
  • Get child by id
    var child = domElement.getChildByID(id)\n
  • Get child by property
    var child = domElement.getChildByProperty(property, value)\n
"},{"location":"domelement/#set-inner-html-string","title":"Set inner html string","text":"
scene.setHTML(html);\n

or

scene.setText(html);\n
"},{"location":"domelement/#dom-element","title":"DOM Element","text":"

Each DOM element object has 1 DOM element.

  • Set
    domElement.setElement(el);\n// domElement.setElement(el, style, innerText);\n
  • Get
    var el = domElement.node;\n
"},{"location":"domelement/#depth","title":"Depth","text":"
domElement.setDepth(value);\n
"},{"location":"domelement/#set-size","title":"Set size","text":"
var style = domElement.node.style;\nstyle.width = width + 'px';\nstyle.height = height + 'px';\ndomElement.updateSize();\n
"},{"location":"domelement/#skew","title":"Skew","text":"
domElement.setSkew(x, y);\n

or

domElement.skewX = x;\ndomElement.skewY = y;\n
"},{"location":"domelement/#rotate-3d","title":"Rotate 3d","text":"

The rotate3d() CSS function defines a transformation that rotates an element around a fixed axis in 3D space, without deforming it.

domElement.rotate3d.set(x, y, z, a);\n

or

domElement.rotate3d.x = x;\ndomElement.rotate3d.y = y;\ndomElement.rotate3d.z = z;\ndomElement.rotate3d.w = a;\n

Reference

"},{"location":"domelement/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"
  1. DOM game object always put above game canvas, i.e. DOM game object will render above any other kind of game object.
  2. DOM game object will receive touch event even if it is not the first touched game object.
  3. P3's 'pointerdown', 'pointerup' events will be fired above/under DOM game object.
  4. P3's 'pointermove' event won't be fired above/under DOM game object, except
    • Setting DOM game object to be invisilbe.
    • Assign input.mouse.target parameter of game config.
  5. DOM game object only can be displayed by main camera. i.e. dom game object can't add to other camera.
"},{"location":"domelement/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"drag/","title":"Drag","text":""},{"location":"drag/#introduction","title":"Introduction","text":"

Drag game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"drag/#live-demos","title":"Live demos","text":"
  • Try dragging
"},{"location":"drag/#usage","title":"Usage","text":"

Sample code

"},{"location":"drag/#install-plugin","title":"Install plugin","text":""},{"location":"drag/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexdragplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdragplugin.min.js', true);\n
  • Add drag behavior
    var drag = scene.plugins.get('rexdragplugin').add(gameObject, config);\n
"},{"location":"drag/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import DragPlugin from 'phaser3-rex-plugins/plugins/drag-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexDrag',\nplugin: DragPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add drag behavior
    var drag = scene.plugins.get('rexDrag').add(gameObject, config);\n
"},{"location":"drag/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Drag from 'phaser3-rex-plugins/plugins/drag.js';\n
  • Add drag behavior
    var drag = new Drag(gameObject, config);\n
"},{"location":"drag/#create-instance","title":"Create instance","text":"
var drag = scene.plugins.get('rexDrag').add(gameObject, {\n// enable: true,\n// axis: 0,      //0|'both'|'h&v'|1|'horizontal'|'h'|2|'vertical'|'v'\n// rotation: Phaser.Math.DegToRad(45)  // axis rotation in rad\n});\n
  • enable : Set false to disable input events.
  • axis :
    • 'both','h&v', 'x&y', or 0 : Dragging on all directions.
    • 'horizontal','h', 'x', or 1 : Dragging on horizontal/x axis.
    • 'vertical','v', 'y', or 2 : Dragging on vertical/y axis.
  • rotation : Axis rotation in rad, available in horizontal or vertical axis mode.
"},{"location":"drag/#events","title":"Events","text":"

Built-in dragging events

gameObject.on('dragstart', function(pointer, dragX, dragY){ /*...*/ });\ngameObject.on('drag', function(pointer, dragX, dragY){ /*...*/ });\ngameObject.on('dragend', function(pointer, dragX, dragY, dropped){ /*...*/ });\n
"},{"location":"drag/#enable","title":"Enable","text":"
  • Get
    var enable = drag.enable;  // enable: true, or false\n
  • Set
    drag.setEnable(enable);  // enable: true, or false\n// drag.enable = enable;\n
  • Toggle
    drag.toggleEnable();\n
"},{"location":"drag/#get-dragging-state","title":"Get dragging state","text":"
var isDragging = drag.isDragging;\n
"},{"location":"drag/#set-rotation-of-axis","title":"Set rotation of axis","text":"
drag.setAxisRotation(rad);\n// drag.axisRotation = rad;\n
"},{"location":"drag/#set-axis-mode","title":"Set axis mode","text":"
drag.setAxisMode(axis);\n
  • axis :
    • 'both','h&v', 'x&y', or 0 : Dragging on all directions.
    • 'horizontal','h', 'x', or 1 : Dragging on horizontal/x axis.
    • 'vertical','v', 'y', or 2 : Dragging on vertical/y axis.
"},{"location":"drag/#try-drag","title":"Try drag","text":"

Game object will be dragged if there is any point above it.

drag.drag();\n
"},{"location":"drag/#drop","title":"Drop","text":"

Game object will be dropped(dragend) manually.

drag.dragend();\n
"},{"location":"dragrotate/","title":"Drag rotate","text":""},{"location":"dragrotate/#introduction","title":"Introduction","text":"

Get dragging angle around a specific point.

  • Author: Rex
  • Member of scene
"},{"location":"dragrotate/#live-demos","title":"Live demos","text":"
  • Spin-button
  • Origin game object
"},{"location":"dragrotate/#usage","title":"Usage","text":"

Sample code

"},{"location":"dragrotate/#install-plugin","title":"Install plugin","text":""},{"location":"dragrotate/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexdragrotateplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdragrotateplugin.min.js', true);\n
  • Add drag-rotate input
    var dragRotate = scene.plugins.get('rexdragrotateplugin').add(scene, config);\n
"},{"location":"dragrotate/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import DragRotatePlugin from 'phaser3-rex-plugins/plugins/dragrotate-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexDragRotate',\nplugin: DragRotatePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add drag-rotate input
    var dragRotate = scene.plugins.get('rexDragRotate').add(scene, config);\n
"},{"location":"dragrotate/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import DragRotate from 'phaser3-rex-plugins/plugins/dragrotate.js';\n
  • Add drag-rotate input
    var dragRotate = new DragRotate(scene, config);\n
"},{"location":"dragrotate/#create-instance","title":"Create instance","text":"
var dragRotate = scene.plugins.get('rexDragRotate').add(scene, {\norigin: undefined,\nx: 0,\ny: 0,\n\nmaxRadius: undefined\nminRadius: 0,\n\n// enable: true,\n});\n
  • origin : Use game object's position as origin point.
    • undefined : Use fixed origin position.
  • x, y : Fixed orgin point, in world position.
  • maxRadius, minRadius : Dragging is valid when distance between touch pointer and origin position is larger then minRadius and less then maxRadius.
  • enable : Set false to disable input events.
"},{"location":"dragrotate/#enable","title":"Enable","text":"
  • Get
    var enable = dragRotate.enable;  // enable: true, or false\n
  • Set
    dragRotate.setEnable(enable);  // enable: true, or false\n// dragRotate.enable = enable;\n
  • Toggle
    dragRotate.toggleEnable();\n
"},{"location":"dragrotate/#origin-point","title":"Origin point","text":"
  • Use game object's position as origin point.
    dragRotate.setOrigin(gameObject);\n
  • Fixed orgin point
    • Get
      var x = dragRotate.x;\nvar y = dragRotate.y;\n
    • Set
      dragRotate.setOrigin(x, y);\n
      or
      dragRotate.setOrigin(pointer); // pointer: {x, y}\n

Note

Parameter (x,y) is world position, not camera position.

"},{"location":"dragrotate/#radius","title":"Radius","text":"
  • Get
    var maxRadius = dragRotate.maxRadius;\nvar minRadius = dragRotate.minRadius;\n
  • Set
    dragRotate.setRadius(maxRadius, minRadius);\n
"},{"location":"dragrotate/#get-dragging-state","title":"Get dragging state","text":"
var state = dragRotate.state;\n
  • 0 : No touch pointer
  • 1 : Catch touch pointer
    • Fire 'dragstart' event when catching touch pointers.
    • Fire 'drag' event when any catched touch pointer moved.
    • Fire 'dragend' event when releasing catched touch pointer.
"},{"location":"dragrotate/#is-drag","title":"Is drag","text":"
var isDrag = dragRotate.isDrag;\n

Return true if (dragRotate.state === 1) and catched touch pointer just moved.

"},{"location":"dragrotate/#drag-cancel","title":"Drag cancel","text":"
dragRotate.dragCancel();\n
"},{"location":"dragrotate/#events","title":"Events","text":""},{"location":"dragrotate/#on-dragging","title":"On dragging","text":"
  • On dragging
    dragRotate.on('drag', function(dragRotate) {\n// gameObject.rotation += dragRotate.deltaRotation;\n}, scope);\n
    • dragRotate.deltaRotation : Dragging angle around origin position, in radians.
      • Add to gameObject.rotation to spin target game object.
        gameObject.rotation += dragRotate.deltaRotation;\n
    • dragRotate.deltaAngle : Dragging angle around origin position, in degrees.
      • Add to gameObject.angle to spin target game object.
        gameObject.angle += dragRotate.deltAangle;\n
    • dragRotate.cw : Return true if dragging is dragrotate-wise.
    • dragRotate.ccw : Return true if dragging is counter-dragrotate-wise.
"},{"location":"dragrotate/#on-drag-start-on-drag-end","title":"On drag start, on drag end","text":"
  • On drag touch pointer start, fired when catching touch pointer.
    dragRotate.on('dragstart', function(dragRotate) {\n\n}, scope);\n
  • On drag touch pointer end, fired when releasing the catched touch pointer.
    dragRotate.on('dragend', function(dragRotate) {\n\n}, scope);\n
"},{"location":"dragrotate/#catched-touch-pointer","title":"Catched touch pointer","text":"
  • Pointer, available when state is 1
    var pointer = dragRotate.pointer;\n
    • World position of pointer
      var x = pointer.worldX;\nvar y = pointer.worldY;\n
"},{"location":"dropdown/","title":"Drop down","text":""},{"location":"dropdown/#introduction","title":"Introduction","text":"

Drop down game object below another target game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"dropdown/#live-demos","title":"Live demos","text":"
  • Drop-down
"},{"location":"dropdown/#usage","title":"Usage","text":"

Sample code

"},{"location":"dropdown/#install-plugin","title":"Install plugin","text":""},{"location":"dropdown/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexdropdownplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdropdownplugin.min.js', true);\n
  • Add drop-down behavior
    var dropDown = scene.plugins.get('rexdropdownplugin').add(gameObject, config);\n
"},{"location":"dropdown/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add drop-down behavior
    var dropDown = scene.plugins.get('rexDropDown').add(gameObject, config);\n
"},{"location":"dropdown/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import DropDownBehavior from 'phaser3-rex-plugins/plugins/dropdown.js';\n
  • Add drop-down behavior
    var dropDown = new DropDownBehavior(gameObject, config);\n
"},{"location":"dropdown/#create-instance","title":"Create instance","text":"
var dropDown = scene.plugins.get('rexDropDown').add(gameObject, {        // expandDirection: 0,\n// alignTargetX: \n// alignTargetY: \n// alignOffsetX: \n// alignOffsetY: \n// bounds:\n\n// When to close dropdown dialog?\n// touchOutsideClose: false,\n// anyTouchClose: false,\n\n// duration: {\n//     in: 200,\n//     out: 200\n// }\n\n// transitIn: undefined,\n// transitOut: undefined,\n\n// destroy: true\n});\n
  • expandDirection : Expand direction
    • 0, 'down' : Expand game object down. i.e. game object will put below target game object. Defatut behavior.
    • 1, 'up' : Expand game object up. i.e. game object will put above target game object.
  • alignTargetX : Align left side game object to left side of target game object
  • alignTargetY : Required parameter
    • Align top side game object to bottom side of target game object, if expandDirection is 0('down').
    • Align bottom side game object to top side of target game object, if expandDirection is 1('up').
  • alignOffsetX, alignOffsetY : Extra position offset. Default value ares 0, 0.
  • bounds : Put game object below target game object if bottom of game object is inside bounds (Rectangle)
    • undefined : Use viewport as bounds
    • Rectangle
  • touchOutsideClose : Set to true to close dropdown dialog when clicking out side of gameObject.
    • Default value is false. Will be set to false if anyTouchClose is set to true.
  • anyTouchClose : Set to true to close dropdown dialog when any clicking.
    • Default value is false.
  • duration : Duration of transition-in, hold, trantion-out.
    • duration.in : Duration of transition-in (open dialog).
      • 0 : No transition, open dialog immediately.
    • duration.out : Duration of transition-out (close dialog).
      • 0 : No transition, close dialog immediately.
  • transitIn : Tween behavior of opening dialog. Default behavior is scale up the height of game object.
    • Custom callback
      function(gameObject, duration) {\n\n}\n
  • transitOut : Tween behavior of closing dialog. Default behavior is scale down the height of game
    • Custom callback
      function(gameObject, duration) {\n\n}\n
  • destroy
    • true : Destroy dialog when closing completed. Default behavior.
    • fasle : Don't destroy dialog.
"},{"location":"dropdown/#close","title":"Close","text":"
dropDown.requestClose();\n// dropDown.requestClose();\n
"},{"location":"dropdown/#events","title":"Events","text":"
  • On opened dialog
    dropDown.on('open', function(gameObject, dropdown) {\n})\n
  • On closed dialog
    dropDown.on('close', function(closeEventData) {\n})\n
"},{"location":"dynamic-texture/","title":"Dynamic texture","text":""},{"location":"dynamic-texture/#introduction","title":"Introduction","text":"

Canvas Dynamic Texture stored in texture cache, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"dynamic-texture/#usage","title":"Usage","text":""},{"location":"dynamic-texture/#create-dynamic-texture","title":"Create dynamic texture","text":"
var texture = scene.textures.addDynamicTexture(key, width, height);\n

Disable texture.isSpriteTexture if this texture is not a base texture for Sprite Game Objects.

texture.setIsSpriteTexture(false);\n// texture.isSpriteTexture = false;\n
"},{"location":"dynamic-texture/#set-size","title":"Set size","text":"
texture.setSize(width, height);\n
"},{"location":"dynamic-texture/#fill-color","title":"Fill color","text":"
texture.fill(rgb);\n// texture.fill(rgb, alpha, x, y, width, height);\n
  • rgb : The number color to fill this Dynamic Texture with.
  • alpha : The alpha value used by the fill. Default value is 1.
  • x, y, width, height : The area of the fill rectangle. Default behavior is filling whole size.
"},{"location":"dynamic-texture/#clear","title":"Clear","text":"
texture.clear();\n
texture.clear(x, y, width, height);\n
"},{"location":"dynamic-texture/#draw-game-object","title":"Draw game object","text":"
texture.draw(entries);\n// texture.draw(entries,x, y);\n// texture.draw(entries, x, y, alpha, tint);\n
  • entries :
    • Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
    • Tilemap Layers.
    • A Group. The contents of which will be iterated and drawn in turn.
    • A Container. The contents of which will be iterated fully, and drawn in turn.
    • A Scene Display List. Pass in Scene.children to draw the whole list.
    • Another Dynamic Texture, or a Render Texture.
    • A Texture Frame instance.
    • A string. This is used to look-up the texture from the Texture Manager.
  • x, y : The x/y position to draw the Frame at, or the offset applied to the object.
    • If the object is a Group, Container or Display List, the coordinates are added to the positions of the children.
    • For all other types of object, the coordinates are exact.
  • alpha, tint : Only used by Texture Frames.
    • Game Objects use their own alpha and tint values when being drawn.
"},{"location":"dynamic-texture/#erase","title":"Erase","text":"
texture.erase(entries);\n// texture.erase(entries, x, y);\n
  • entries :
    • Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
    • Tilemap Layers.
    • A Group. The contents of which will be iterated and drawn in turn.
    • A Container. The contents of which will be iterated fully, and drawn in turn.
    • A Scene Display List. Pass in Scene.children to draw the whole list.
    • Another Dynamic Texture, or a Render Texture.
    • A Texture Frame instance.
    • A string. This is used to look-up the texture from the Texture Manager.
  • x, y : The x/y position to draw the Frame at, or the offset applied to the object.
    • If the object is a Group, Container or Display List, the coordinates are added to the positions of the children.
    • For all other types of object, the coordinates are exact.
"},{"location":"dynamic-texture/#draw-frame","title":"Draw frame","text":"
texture.stamp(key, frame, x, y, {\nalpha: 1,\ntint: 0xffffff,\nangle: 0,\nrotation: 0,\nscale: 1,\nscaleX: 1,\nscaleY: 1,\noriginX: 0.5,\noriginY: 0.5,\nblendMode: 0,\nerase: false,\nskipBatch: false\n})\n

or

texture.drawFrame(key, frame, x, y);\n// texture.drawFrame(key, frame, x, y, alpha, tint);\n
  • x, y : Top-left position
"},{"location":"dynamic-texture/#draw-repeat-frames","title":"Draw repeat frames","text":"
  • Repeat frames full of size
    texture.repeat(key, frame);\n
  • Repeat in an area
    texture.repeat(key, frame, x, y, width, height);\n// texture.repeat(key, frame, x, y, width, height, alpha, tint, skipBatch);\n
"},{"location":"dynamic-texture/#add-frame","title":"Add frame","text":"
texture.add(name, sourceIndex, x, y, width, height);\n
  • name : The name of this Frame. The name is unique within the Texture.
  • sourceIndex : The index of the TextureSource that this Frame is a part of.
  • x : The x coordinate of the top-left of this Frame.
  • y : The y coordinate of the top-left of this Frame.
  • width : The width of this Frame.
  • height : The height of this Frame.
"},{"location":"dynamic-texture/#batch-draw","title":"Batch draw","text":"
  1. Begin
    texture.beginDraw();\n
  2. Draw
    • Draw game object
      texture.batchDraw(entries, x, y, alpha, tint);\n
      • entries :
        • Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
        • Tilemap Layers.
        • A Group. The contents of which will be iterated and drawn in turn.
        • A Container. The contents of which will be iterated fully, and drawn in turn.
        • A Scene Display List. Pass in Scene.children to draw the whole list.
        • Another Dynamic Texture, or a Render Texture.
        • A Texture Frame instance.
        • A string. This is used to look-up the texture from the Texture Manager.
    • Draw frame
      texture.batchDrawFrame(key, frame, x, y, alpha, tint);\n
    • Draw image
      texture.stamp(key, frame, x, y, {\n// ...\nskipBatch: true\n})\n
    • Draw repeat images
      texture.repeat(key, frame, x, y, width, height, alpha, tint, true);\n
  3. End
    texture.endDraw();\n
"},{"location":"dynamic-texture/#internal-camera","title":"Internal camera","text":"

Internal camera texture.camera

  • Scroll (offset)
    texture.camera.setScroll(x, y);\n
  • Zoom (scale)
    texture.camera.setZoom(zoom);\n
  • Rotate
    texture.camera.setAngle(angle);  // angle in degrees\n
"},{"location":"dynamic-texture/#snapshot","title":"Snapshot","text":""},{"location":"dynamic-texture/#snapshot-area","title":"Snapshot area","text":"
texture.snapshot(callback);\n// texture.snapshot(callback, type, encoderOptions);\n

or

texture.snapshotArea(x, y, width, height, callback, type, encoderOptions);\n
  • callback : The Function to invoke after the snapshot image is created.
    function(imageElement) {\n}\n
    • imageElement : HTMLImageElement.
  • type : The format of the image to create, usually 'image/png' or 'image/jpeg'. Default value is 'image/png'.
  • encoderOptions : The image quality, between 0 and 1. Used for image formats with lossy compression, such as 'image/jpeg'. Default value is 0.92.
  • x, y, width, height : Snapshot area.
"},{"location":"dynamic-texture/#get-color-of-a-pixel","title":"Get color of a pixel","text":"
texture.snapshotPixel(x, y, callback);\n
  • x, y : The x/y coordinate of the pixel to get.
  • callback : The Function to invoke after the snapshot image is created.
    function(color) {        }\n
    • color : Color object.
"},{"location":"dynamicbitmaptext/","title":"Dynamic bitmap text","text":""},{"location":"dynamicbitmaptext/#introduction","title":"Introduction","text":"

Drawing text by texture with a callback for each character triggered at every tick, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"dynamicbitmaptext/#usage","title":"Usage","text":""},{"location":"dynamicbitmaptext/#load-bitmap-font","title":"Load bitmap font","text":"

Reference: load bitmap font

"},{"location":"dynamicbitmaptext/#add-bitmap-text-object","title":"Add bitmap text object","text":"
var txt = scene.add.dynamicBitmapText(x, y, key, text);\n// var txt = scene.add.dynamicBitmapText(x, y, key, text, size, align);\n
  • size : The size of the font
  • align : The alignment of the text in a multi-line BitmapText object.
    • 0 : Left aligned (default)
    • 1 : Middle aligned
    • 2 : Right aligned

Add text from JSON

var txt = scene.make.dynamicBitmapText({\nx: 0,\ny: 0,\ntext: 'Text\\nGame Object\\nCreated from config',\nfont: '',\nsize: false,\nalign: 0,\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
"},{"location":"dynamicbitmaptext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyText extends Phaser.GameObjects.DynamicBitmapText {\nconstructor(scene, x, y, key, text, size, align) {\nsuper(scene, x, y, key, text, size, align);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyText(scene, x, y, key, text);\n
"},{"location":"dynamicbitmaptext/#set-callback","title":"Set callback","text":"
var callback = function(data) {\n// input\n// data.index, data.charCode\n// data.x, data.y, data.scale, data.rotation\n// data.data\n// data.tint.topLeft, data.tint.topRight, data.tint.bottomLeft, data.tint.bottomRight    \n\n// modify input `data` then return it\n// ...\n// offset: data.y += 2\n// set tint: data.color = tint\nreturn data;\n}\ntxt.setDisplayCallback(callback);\n
"},{"location":"dynamicbitmaptext/#set-text","title":"Set text","text":"
txt.setText('...');\n

or

txt.text = '...';\n
"},{"location":"dynamicbitmaptext/#crop","title":"Crop","text":"
  • Set size
    txt.setSize(width, height);\n
    or
    txt.cropWidth = width;\ntxt.cropHeight = height;\n
  • Set offset
    txt.setScrollX(scrollX);\ntxt.setScrollY(scrollY);\n
    or
    this.scrollX = scrollX;\nthis.scrollY = scrollY;\n
"},{"location":"dynamicbitmaptext/#other-properties","title":"Other properties","text":"

See bitmap text, game object

"},{"location":"dynamicbitmaptext/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"dynamicbitmaptext/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"dynamictext/","title":"Dynamic text","text":""},{"location":"dynamictext/#introduction","title":"Introduction","text":"

Control position, angle of each character drawn on a canvas.

  • Author: Rex
  • Game object
"},{"location":"dynamictext/#live-demos","title":"Live demos","text":"
  • Wrap
    • Wrap modes
    • Horizontal alignment modes
  • Page typing
  • Align, rotation, drawBelowCallback
  • Vertical wrap
  • Character's world position
  • Child input event
"},{"location":"dynamictext/#usage","title":"Usage","text":"

Sample code

"},{"location":"dynamictext/#install-plugin","title":"Install plugin","text":""},{"location":"dynamictext/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexdynamictextplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdynamictextplugin.min.js', true);\n
  • Add dynamic-text object
    var txt = scene.add.rexDynamicText(x, y, width, height, config);\n
"},{"location":"dynamictext/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import DynamicTextPlugin from 'phaser3-rex-plugins/plugins/dynamictext-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexDynamicTextPlugin',\nplugin: DynamicTextPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add dynamic-text object
    var txt = scene.add.rexDynamicText(x, y, width, height, config);\n
"},{"location":"dynamictext/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import DynamicText from 'phaser3-rex-plugins/plugins/dynamictext.js';\n
  • Add dynamic-text object
    var txt = new DynamicText(scene, x, y, width, height, config);\nscene.add.existing(txt);\n
"},{"location":"dynamictext/#create-instance","title":"Create instance","text":"
var txt = scene.add.rexDynamicText({\nx: 0, y: 0,\nwidth: undefined, height: undefined,\nresolution: 1,\n\npadding: 0,  // {left: 0, right: 0, top: 0, bottom: 0}\n\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\n\ninnerBounds: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\n\nchildrenInteractive: false,\n\ntext: '',\n\nwrap: undefined,\n\ntestString: '|M\u00c9qgy',\n});\n
  • x, y : Position of this dynamic-text game object.
  • width : Fixed width.
    • A number : Width of this dynamic-text game object.
      • Wrap-width is width - padding.left - padding.right.
    • undefined : Width of this dynamic-text game object will be set after invoked runWordWrap method.
  • height : Fixed height.
    • A number : Height of this dynamic-text game object.
    • undefined : Height of this dynamic-text game object will be set after invoked runWordWrap method.
  • resolution : The resolution the content is rendered to its internal canvas at. Default value is 1.
  • padding : Padding of bounds.
    • A number
    • padding.left, padding.right, padding.top, padding.bottom
  • background : Properties of background round-rectangle.
    • background.color : Fill color, number or string.
      • null : No filling.
    • background.color2 : Gradient fill color, number or string.
      • null : No gradient filling.
    • background.horizontalGradient : Horizontal or vertical gradient filling.
      • true : Horizontal gradient filling.
      • false : Vertical gradient filling.
    • background.stroke : Stroke color, number or string.
      • null : No stroke.
    • background.strokeThickness : Line width of stroke.
    • background.cornerRadius : Corner-radius of round rectangle.
    • background.cornerIteration : Iteration of corner-radius.
      • null : Draw corner-radius via arc directly.
      • A number : Draw corner-radius via lines
  • innerBounds : Properties of inner-bounds.
    • innerBounds.color : Fill color, number or string.
      • null : No filling.
    • innerBounds.color2 : Gradient fill color, number or string.
      • null : No gradient filling.
    • innerBounds.horizontalGradient : Horizontal or vertical gradient filling.
      • true : Horizontal gradient filling.
      • false : Vertical gradient filling.
    • innerBounds.stroke : Stroke color, number or string.
      • null : No stroke.
    • innerBounds.strokeThickness : Line width of stroke.
  • style : Initial text-style.
    • style.bold : Bold
    • style.italic : Italic
    • style.fontSize : Font size, number or string.
    • style.fontFamily : Font family
    • style.color : Fill color, number or string.
    • style.stroke : Stroke color, number or string.
    • style.strokeThickness : Line width of stroke.
    • style.shadowColor : Shadow color, number or string.
      • null : No shadow.
    • style.shadowOffsetX : OffsetX of shadow.
    • style.shadowOffsetY : OffsetY of shadow.
    • style.shadowBlur : Blur of shadow.
    • style.backgroundColor : Background color of a character.
    • style.backgroundHeight, style.backgroundBottomY : Background position and height of a character.
      • undefined, or null : Use height of character as background height. Default behavior.
    • style.offsetX : OffsetX.
    • style.offsetY : OffsetY.
    • style.align : Override default line-alignment setting.
      • 0, 'left', 'top' : Align remainder lines to left/top.
      • 1, 'center' : Align remainder lines to center.
      • 2, 'right', 'bottom' : Align remainder lines to right/bottom.
      • undefined : Use default line-alignment setting.
  • childrenInteractive :
    • true : Fire input events ('child.pointerdown', 'child.pointerup', 'child.pointerover', 'child.pointerout') of any child after text.setInteractive().
    • false : Won't fire any input events of child. Default behavior.
  • text : Content of text.
  • wrap : Default configuration Horizontal/Vertical wrapping.
  • testString : Test string to get text ascent and text height with default text style.

or

var txt = scene.add.rexDynamicText(x, y, width, height, config);\n

or

var txt = scene.add.rexDynamicText(x, y, config);\n

Add dynamictext from JSON

var txt = scene.make.rexDynamicText({\nx: 0,\ny: 0,\n\n// origin: {x: 0.5, y: 0.5},\n// fill: null,\n\nadd: true\n});\n
"},{"location":"dynamictext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDynamicText extends DynamicText {\nconstructor(scene, x, y, width, height, config)) {\nsuper(scene, x, y, width, height, config));\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyDynamicText(scene, x, y, config);\n
"},{"location":"dynamictext/#clear-content","title":"Clear content","text":"
txt.clearContent();\n
"},{"location":"dynamictext/#text","title":"Text","text":""},{"location":"dynamictext/#append-text","title":"Append text","text":"
txt.appendText(text);\n

or

txt.appendText(text, {\n// bold: false,\n// italic: false,\n// fontSize: '16px',\n// fontFamily: 'Courier',\n// color: '#fff',\n// stroke: '#fff',\n// strokeThickness: 0,\n// shadowColor: null,\n// shadowOffsetX: 0,\n// shadowOffsetY: 0,\n// shadowBlur: 0,\n// backgroundColor: null,\n// backgroundHeight: undefined,\n// backgroundBottomY: undefined,\n// offsetY: 0,\n// offsetY: 0,\n// align: undefined\n}\n);\n

To overwrite some properties of text-style.

Each character will be placed at position (0,0), without rotation. Uses word-wrap method to rearrange position of characters.

"},{"location":"dynamictext/#set-text","title":"Set text","text":"
txt.setText(text);\n

or

txt.setText(text, {\n// bold: false,\n// italic: false,\n// fontSize: '16px',\n// fontFamily: 'Courier',\n// color: '#fff',\n// stroke: '#fff',\n// strokeThickness: 0,\n// shadowColor: null,\n// shadowOffsetX: 0,\n// shadowOffsetY: 0,\n// shadowBlur: 0,\n// backgroundColor: null,\n// backgroundHeight: undefined,\n// backgroundBottomY: undefined,\n// offsetY: 0,\n// offsetY: 0,\n// align: undefined\n}\n);\n
"},{"location":"dynamictext/#insert-text","title":"Insert text","text":"

txt.insertText(index, text);\n
or

txt.insertText(index, text, {\n// bold: false,\n// italic: false,\n// fontSize: '16px',\n// fontFamily: 'Courier',\n// color: '#fff',\n// stroke: '#fff',\n// strokeThickness: 0,\n// shadowColor: null,\n// shadowOffsetX: 0,\n// shadowOffsetY: 0,\n// shadowBlur: 0,\n// backgroundColor: null,\n// backgroundHeight: undefined,\n// backgroundBottomY: undefined,\n// offsetY: 0,\n// offsetY: 0,\n// align: undefined\n}\n);\n
"},{"location":"dynamictext/#remove-text","title":"Remove text","text":"
txt.removeText(index);\n
"},{"location":"dynamictext/#get-text","title":"Get text","text":"
  • Get active characters
    var text = txt.text;\n
    or
    var text = txt.getText();\n
  • Get all characters
    var text = txt.getText(false);\n
"},{"location":"dynamictext/#image","title":"Image","text":""},{"location":"dynamictext/#append-image","title":"Append image","text":"
txt.appendImage(key, frame, {\n// width: ,\n// height: ,\n// scaleX: ,\n// scaleY: ,\n// color: ,\n})\n
  • width : Scaled-width. Aspect-ratio will be kept if no height, or scaleY is set.
  • height : Scaled-height. Aspect-ratio will be kept if no width, or scaleX is set.
  • color : Tint-fill color. Default is undefined.
"},{"location":"dynamictext/#background","title":"Background","text":"
  • Fill style
    txt.setBackgroundColor(color);\n// txt.setBackgroundColor(color, color2, isHorizontalGradient);\n
  • Stroke style
    txt.setBackgroundStroke(color, lineWidth);\n
  • Corner radius
    txt.setBackgroundCornerRadius(radius);\n// txt.setBackgroundCornerRadius(radius, iteration)\n
"},{"location":"dynamictext/#inner-bounds","title":"Inner bounds","text":"
  • Fill style
    txt.setInnerBoundsColor(color);\n// txt.setInnerBoundsColor(color, color2, isHorizontalGradient);\n
  • Stroke style
    txt.setInnerBoundsStroke(color, lineWidth);\n
"},{"location":"dynamictext/#wrap","title":"Wrap","text":"

Control characters :

  • '\\n' : New line
  • '\\f' : Page break
"},{"location":"dynamictext/#horizontal-wrap","title":"Horizontal wrap","text":"
var result = txt.runWordWrap({\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n},\nascent: undefined,\nlineHeight: undefined,\nuseDefaultTextHeight: false,\nmaxLines: undefined,\nwrapWidth: undefined,\nwrapMode: 'word',  // 1|'word'|2|'char'|'character'|3|'mix'\nletterSpacing: 0,\nhAlign: 0,\nvAlign: 0,\n\n\n});\n
  • padding :
    • padding.top, padding.bottom, padding.left, padding.right : Extra space around lines.
  • ascent, lineHeight : Height of first line and remainder lines
    • ascent will set to lineHeight if ascent is undefined but lineHeight is not undefined (backward compatible)
    • Get ascent, lineHeight from default text style and test string, if ascent, lineHeight are both undefined
  • useDefaultTextHeight : If parameter lineHeight is not given,
    • false : Set line height to (total line height / maxLines), if parameter maxLines is larger than 0. Default behavior.
    • true : Set line height to default text height.
  • maxLines : Lines number of this page.
    • 0 : Wrapping whole content.
    • undefined : It will be set if lineHeight and height is given
  • wrapWidth : Width of wrapping. Use inner width if this parameter is undefined.
  • wrapMode :
    • No wrapping if wrapWidth, or inner width is not given.
    • 1, or 'word' : Word wrapping. Default behavior.
    • 2, or 'char', or 'character' : Character wrapping.
    • 3, or 'mix' : Word wrapping for ASCII word, Character wrapping for other (unicode) word.
  • letterSpacing : Space between each character.
  • hAlign : Horizontal alignment.
    • 0, or 'left' : Align to left bound.
    • 1, or 'center' : Align to center.
    • 2, or 'right' : Align to right bound.
    • 3, 'justify', 'justify-left' : If remainder space is less or equal than 25%, then justify children. Else align children to left/top side.
    • 4, 'justify-right' : If remainder space is less or equal than 25%, then justify children. Else align children to right/bottom side.
    • 5, 'justify-cneter' : If remainder space is less or equal than 25%, then justify children. Else align children to center.
  • vAlign : Vertical alignment.
    • 0, or 'top' : Align to top bound.
    • 1, or 'center' : Align to center.
    • 2, or 'bottom' : Align to bottom bound.
"},{"location":"dynamictext/#align","title":"Align","text":"
  • Set vertical align mode
    txt.setVAlign(vAlign);\n
    • vAlign : Vertical alignment.
      • 0, or 'top' : Align to top bound.
      • 1, or 'center' : Align to center.
      • 2, or 'bottom' : Align to bottom bound.
  • Set horizontal align mode
    txt.setHAlign(hAlign);\n
    • hAlign : Horizontal alignment.
      • 0, or 'left' : Align to left bound.
      • 1, or 'center' : Align to center.
      • 2, or 'right' : Align to right bound.
"},{"location":"dynamictext/#test-string","title":"Test string","text":"
txt.setTestString(text);\n
"},{"location":"dynamictext/#vertical-wrap","title":"Vertical wrap","text":"
var result = txt.runVerticalWrap({\npadding: {\ntop: 0,\nleft: 0,\nright: 0,\nbottom: 0\n},\nlineWidth: undefined,\nmaxLines: undefined,\nfixedChildHeight: undefined,\ncharPerLine: undefined,\nwrapHeight: undefined,\nletterSpacing: 0,\nrtl: true,\nhAlign: 0,\nvAlign: 0,\n});\n
  • padding :
    • padding.top, padding.bottom, padding.left, padding.right : Extra space around lines.
  • lineWidth : Line width.
    • undefined : It will be set if maxLines and fixedWidth is given.
  • maxLines : Lines number of this page.
    • 0 : Wrapping whole content.
    • undefined : It will be set if lineWidth and fixedWidth is given.
  • fixedChildHeight : Each character has the same fixed height.
    • undefined : Get fixedChildHeight according to charPerLine parameter. Or use height of each character if fixedChildHeight and charPerLine parameters are undefined.
  • charPerLine : Amount of characters in each line, to get fixedChildHeight.
  • wrapHeight : Height of wrapping
  • letterSpacing : Space between each character.
  • rtl :
    • true : Place lines from right to left.
    • false : Place lines from left to right.
  • hAlign : Horizontal alignment.
    • 0, or 'left' : Align to left bound. Default value if rtl is set to false.
    • 1, or 'center' : Align to center.
    • 2, or 'right' : Align to right bound. Default value if rtl is set to true.
  • vAlign : Vertical alignment.
    • 0, or 'top' : Align to top bound.
    • 1, or 'center' : Align to center.
    • 2, or 'bottom' : Align to bottom bound.
"},{"location":"dynamictext/#result","title":"Result","text":"
{\nchildren: [],\nlines: [],\nisLastPage: false\n}\n
  • children : Character/Image data in this page.
  • lines : Array of line data. A line data contains
    {\nchildren: [],\nwidth: 0,     // Horizontal-wrapping\nheight: 0,    // Vertical-wrapping.        \n}\n
    • children : Character/Image data in this line.
    • width : Width of this line, in result of horizontal-wrapping.
    • height : Height of this line, in result of vertical-wrapping.
  • isLastPage :
    • false : Run txt.runWordWrap(result)/txt.runVerticalWrap(result) to get next page of word-wrapping result.
    • true : No remainder of characters.
"},{"location":"dynamictext/#wrap-next-page","title":"Wrap next page","text":"
var result = txt.runWordWrap(prevResult);\n
  • prevResult : Result of previous word-wraping.
  • result : Current result of word-wraping.
"},{"location":"dynamictext/#default-configuration-of-wrapping","title":"Default configuration of wrapping","text":"
txt.setWrapConfig(config);\n
  • config : Default configuration Horizontal/Vertical wrapping.
"},{"location":"dynamictext/#scroll-content","title":"Scroll content","text":"

Scroll content by setting textOX, textOY members

  • Set
    txt.setTextOXY(x, y).updateTexture();    // txt.setTextOX(x).updateTexture();\n// txt.setTextOY(x).updateTexture(); \n
    or
    txt.addTextOXY(incX, incY).updateTexture(); // txt.addTextOX(incX).updateTexture(); \n// txt.addTextOY(incY).updateTexture(); \n
    or
    txt.textOX = x;\ntxt.textOY = y;\ntxt.updateTexture();\n
  • Get
    var ox = txt.textOX;\nvar oy = txt.textOY;\n
"},{"location":"dynamictext/#child","title":"Child","text":""},{"location":"dynamictext/#general-properties","title":"General properties","text":"
  • Visible :
    • Get
      var visible = child.visible;\n
    • Set
      child.setVisible();\n// child.visible = true;\n
      or
      child.setVisible(false);  // Set to invisible\n// child.visible = false;\n
  • Alpha
    • Get
      var alpha = child.alpha;\n
    • Set
      child.setAlpha(alpha);\n// child.alpha = alpha;\n
  • Position :
    • Get
      var x = child.x;\nvar y = child.y;\n
    • Set
      child.setPosition(x, y);\n// child.x = x;\n// child.y = y;\n
  • Angle :
    • Get
      var degrees = child.angle;\n// var radians = child.rotation;\n
    • Set
      child.setAngle(degrees);\nchild.setRotation(radians);\n// child.angle = degrees;\n// child.rotation = radians;\n
  • Scale
    • Get
      var scaleX = child.scaleX;\nvar scaleY = child.scaleY;\n
    • Set
      child.setScale(scaleX, scaleY);\n// child.scaleX = scaleX;\n// child.scaleY = scaleY;\n
  • Draw callbacks
    • Set
      child.setDrawBelowCallback(callback);\nchild.setDrawAboveCallback(callback);\n
      • callback :
        function(child) {\nvar text = child.text;                var context = child.context;\n// ...\n}\n
  • World position
    var worldXY = child.getWorldPosition();\n// out = child.getWorldPosition(out);\n
    or
    var worldXY = txt.getCharWorldPosition(char);\n// out = txt.getCharWorldPosition(char, out);\n
"},{"location":"dynamictext/#character","title":"Character","text":""},{"location":"dynamictext/#text-style","title":"Text-style","text":"
  • Get
    var bold = char.style.bold;\nvar italic = char.style.italic;\nvar fontSize = char.style.fontSize;\nvar fontFamily = char.style.fontFamily;\nvar color = char.style.color;\nvar stroke = char.style.stroke;\nvar strokeThickness = char.style.strokeThickness;\nvar shaodwColor = char.style.shadowColor;\nvar shadowBlur = char.style.shadowBlur;\nvar shadowOffsetX = char.style.shadowOffsetX;\nvar shadowOffsetY = char.style.shadowOffsetY;\nvar backgroundColor = char.style.backgroundColor;\nvar backgroundHeight = char.style.backgroundHeight;\nvar backgroundBottomY = char.style.backgroundBottomY;\nvar xOffset = char.style.x;\nvar yOffset = char.style.y;\n
  • Set
    char.modifyStyle({\n// bold: false,\n// italic: false,\n// fontSize: '16px',\n// fontFamily: 'Courier',\n// color: '#fff',\n// stroke: '#fff',\n// strokeThickness: 0,\n// shaodwColor: null,\n// shadowBlur: 0,\n// shadowOffsetX: 0,\n// shadowOffsetY: 0,\n// backgroundColor: null,\n// backgroundHeight: undefined,\n// backgroundBottomY: undefined,\n// offsetX: 0,\n// offsetY: 0\n})\n
    or
    char.setBold();\n// char.setBold(false);\n
    char.setItalic();\n// char.setItalic(false);\n
    char.setFontSize(fontSize); // number, string\n
    char.setFontFamily(fontFamily);\n
    char.setColor(color); // number, string\n// char.setColor(); // No filling color\n
    char.setStrokeStyle(color, thickness);\n// char.setStrokeStyle();  // No stroke\n
    char.setShadowColor(color);\n// char.setShadowColor();  // No shadow\n
    char.setShadowOffset(offsetX, offsetY);\n
    char.setShadowBlur(blur);\n
    char.setBackgroundColor(color);\n// char.setBackgroundColor();  // No shadow\n
    char.setOffsetX(offsetX);\nchar.setOffsetY(offsetY);\n
"},{"location":"dynamictext/#image_1","title":"Image","text":"
  • Size
    • Get
      var width = image.width;\nvar height = image.height;\n
    • Set
      image.setWidth(width);\n// image.setWidth(width, true);  // Resize and keep aspect- ratio\nimage.setHeight(height);\n// image.setHeight(height, true);  // Resize and keep aspect- ratio\n
"},{"location":"dynamictext/#for-each-child","title":"For each child","text":"
  • Any child
    • For each active child
      txt.forEachChild(function(child, childIndex){\n}, scope)\n
    • For each character child
      txt.forEachChild(function(child, childIndex){\n}, scope, false);\n
  • Renderable child
    • For each active renderable child
      txt.forEachRenderableChild(function(child, charIndex){\n}, scope)\n
    • For each renderable child
      txt.forEachRenderableChild(function(child, charIndex){\n}, scope, false);\n
  • Character child
    • For each active character child
      txt.forEachCharChild(function(child, charIndex){\n}, scope)\n
    • For each character child
      txt.forEachCharChild(function(child, charIndex){\n}, scope, false);\n
"},{"location":"dynamictext/#get-children","title":"Get children","text":"
  • Get all children
    var children = txt.getChildren();\n
  • Get last appended children
    var children = txt.getLastAppendedChildren();\n
  • Get active children, after wrapping
    var children = txt.getActiveChildren();\n
"},{"location":"dynamictext/#get-character-children","title":"Get character children","text":"
  • Get active character children
    var children = txt.getCharChildren();\n
  • Get all character children
    var children = txt.getCharChildren(false);\n
  • Get character child by character index
    var child = txt.getCharChild(charIndex);\n
"},{"location":"dynamictext/#move-child","title":"Move child","text":"
  • Move child to fist
    txt.moveChildToFist(child);\n
  • Move child to last
    txt.moveChildToLast(child);\n
  • Move child up
    txt.movechildUp(child);\n
  • Move child to down
    txt.movechildDown(child);\n
  • Move child above another child
    txt.movechildAbove(child, baseChild);\n
  • Move child below another child
    txt.movechildBelow(child, baseChild);\n
"},{"location":"dynamictext/#size","title":"Size","text":"
  • Resize canvas size
    txt.setCanvasSize(width, height)\n
  • Reisze text wrapping size and canvas size.
    txt.setSize(width, height);\n
    or
    txt.setFixedSize(width, height);\n
  • Resize to minimun size to show all visible characters.
    txt.setToMinSize();\n
"},{"location":"dynamictext/#input-events-of-child","title":"Input events of child","text":"
  • Enable input events of child on config of constructor, or via method
    txt.setChildrenInteractiveEnable();\n
  • Pointer down/up on child
    txt.on('child.pointerdown', function(child, pointer, localX, localY, event) {        })\n
    txt.on('child.pointerup', function(child, pointer, localX, localY, event) {        })\n
    • child : Any Character or Image child
  • Pointer over/out on child
    txt.on('child.pointerover', function(child, pointer, localX, localY, event) {        })\n
    txt.on('child.pointerout', function(child, pointer, localX, localY, event) {        })\n
    • child : Any Character or Image child
"},{"location":"dynamictext/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"dynamictext/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"dynamictext/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"dynamictext/#compare-with-other-kinds-of-text-game-object","title":"Compare with other kinds of text game object","text":"
  • Built-in text:
    • Single color per game object.
    • Draw content line by line.
    • Best render performance.
  • BBCode text:
    • Multiple colors, multiple font size per gaem object.
    • Draw content segment by segment.
    • Slower than built-in text game object.
  • Dynamic text:
    • Multiple colors, multiple font size per gaem object.
    • Draw content character by character.
    • Slower than bbcode text game object.
"},{"location":"ease-function/","title":"Ease","text":""},{"location":"ease-function/#introduction","title":"Introduction","text":"

Ease functions, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"ease-function/#usage","title":"Usage","text":""},{"location":"ease-function/#ease-functions","title":"Ease functions","text":"
  • Linear : Phaser.Math.Easing.Linear
  • Quadratic, Power1
    • Quadratic ease-out : Phaser.Math.Easing.Quadratic.Out
    • Quadratic ease-in : Phaser.Math.Easing.Quadratic.In
    • Quadratic ease-in/out : Phaser.Math.Easing.Quadratic.InOut
  • Cubic, Power2
    • Cubic ease-out : Phaser.Math.Easing.Cubic.Out
    • Cubic ease-in : Phaser.Math.Easing.Cubic.In
    • Cubic ease-in/out : Phaser.Math.Easing.Cubic.InOut
  • Quartic, Power3
    • Quartic ease-out : Phaser.Math.Easing.Quartic.Out
    • Quartic ease-in : Phaser.Math.Easing.Quartic.In
    • Quartic ease-in/out : Phaser.Math.Easing.Quartic.InOut
  • Quintic, Power4
    • Quintic ease-out : Phaser.Math.Easing.Quintic.Out
    • Quintic ease-in : Phaser.Math.Easing.Quintic.In
    • Quintic ease-in/out : Phaser.Math.Easing.Quintic.InOut
  • Sinusoidal
    • Sinusoidal ease-out : Phaser.Math.Easing.Sine.Out
    • Sinusoidal ease-in : Phaser.Math.Easing.Sine.In
    • Sinusoidal ease-in/out : Phaser.Math.Easing.Sine.InOut
  • Exponential
    • Exponential ease-out : Phaser.Math.Easing.Expo.Out
    • Exponential ease-in : Phaser.Math.Easing.Expo.In
    • Exponential ease-in/out : Phaser.Math.Easing.Expo.InOut
  • Circular
    • Circular ease-out : Phaser.Math.Easing.Circular.Out
    • Circular ease-in : Phaser.Math.Easing.Circular.In
    • Circular ease-in/out : Phaser.Math.Easing.Circular.InOut
  • Elastic
    • Elastic ease-out : Phaser.Math.Easing.Elastic.Out
    • Elastic ease-in : Phaser.Math.Easing.Elastic.In
    • Elastic ease-in/out : Phaser.Math.Easing.Elastic.InOut
  • Bounce
    • Bounce ease-out : Phaser.Math.Easing.Bounce.Out
    • Bounce ease-in : Phaser.Math.Easing.Bounce.In
    • Bounce ease-in/out : Phaser.Math.Easing.Bounce.InOut
  • Back
    • Back ease-out : Phaser.Math.Easing.Back.Out
    • Back ease-in : Phaser.Math.Easing.Back.In
    • Back ease-in/out : Phaser.Math.Easing.Back.InOut
  • Stepped : Phaser.Math.Easing.Stepped(v, step)
"},{"location":"ease-function/#get-ease-function-via-string","title":"Get ease function via string","text":"
var easeFunction = Phaser.Tweens.Builders.GetEaseFunction(ease);\n// var easeFunction = Phaser.Tweens.Builders.GetEaseFunction(ease, easeParams);\n
  • ease :
    • A string :
      • Power0 : Linear
      • Power1 : Quadratic.Out
      • Power2 : Cubic.Out
      • Power3 : Quartic.Out
      • Power4 : Quintic.Out
      • Linear
      • Quad : Quadratic.Out
      • Cubic : Cubic.Out
      • Quart : Quartic.Out
      • Quint : Quintic.Out
      • Sine : Sine.Out
      • Expo : Expo.Out
      • Circ : Circular.Out
      • Elastic : Elastic.Out
      • Back : Back.Out
      • Bounce : Bounce.Out
      • Stepped
      • Quad.easeIn
      • Cubic.easeIn
      • Quart.easeIn
      • Quint.easeIn
      • Sine.easeIn
      • Expo.easeIn
      • Circ.easeIn
      • Back.easeIn
      • Bounce.easeIn
      • Quad.easeOut
      • Cubic.easeOut
      • Quart.easeOut
      • Quint.easeOut
      • Sine.easeOut
      • Expo.easeOut
      • Circ.easeOut
      • Back.easeOut
      • Bounce.easeOut
      • Quad.easeInOut
      • Cubic.easeInOut
      • Quart.easeInOut
      • Quint.easeInOut
      • Sine.easeInOut
      • Expo.easeInOut
      • Circ.easeInOut
      • Back.easeInOut
      • Bounce.easeInOut
    • A custom function
      function(v) {\nreturn v;\n}\n
      function(v, param0, param1, ...) {\nreturn v;\n}\n
      • v : 0 ~ 1
"},{"location":"ease-function/#get-result","title":"Get result","text":"
var result = easeFunction(t);\n
  • t : 0 ~ 1
"},{"location":"easedata/","title":"Ease-data","text":""},{"location":"easedata/#introduction","title":"Introduction","text":"

Easing data value of game object's data-manager.

  • Author: Rex
  • Method only
"},{"location":"easedata/#usage","title":"Usage","text":"

Sample code

"},{"location":"easedata/#install-plugin","title":"Install plugin","text":""},{"location":"easedata/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexeasedataplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexeasedataplugin.min.js', true);\n
  • Add ease-data behavior
    var easedata = scene.plugins.get('rexeasedataplugin').add(gameObject);\n
"},{"location":"easedata/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import EaseDataPlugin from 'phaser3-rex-plugins/plugins/easedata-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexEaseData',\nplugin: EaseDataPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add ease-data behavior
    var easedata = scene.plugins.get('rexEaseData').add(gameObject);\n
"},{"location":"easedata/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import { EaseData } from 'phaser3-rex-plugins/plugins/easedata.js';\n
  • EaseData-out-destroy
    var easedata = new EaseData(gameObject);\n
"},{"location":"easedata/#create-instance","title":"Create instance","text":"
var easedata = scene.plugins.get('rexEaseData').add(gameObject);\n
"},{"location":"easedata/#ease-data","title":"Ease data","text":"
  • Start
    easedata.easeTo(key, value, duration);\n// easedata.easeTo(key, value, duration, ease);\n
    or
    easedata.easeTo({\nkey:key,\nvalue:value,\nduration:1000,\nease:'Linear'\n});\n
    or
    easedata.easeTo({\nkey:key,\nvalue:value,\nspeed: 10,    // value changing rate, per second\nease:'Linear'\n});\n
  • Stop
    easedata.stopEase(key);           // Set to end value\n// easedata.stopEase(key, false); // Stop at current value\n
    or
    easedata.stopAll();           // Set to end value\n// easedata.stopAll(false);   // Stop at current value\n
"},{"location":"easedata/#events","title":"Events","text":"
  • Easing complete
    easedata.on('complete-' + key, function(gameObject, easedata){\n\n}, scope);\n
    easedata.on('complete', function(key, gameObject, easedata){\n\n}, scope);\n
"},{"location":"easemove/","title":"Ease-move","text":""},{"location":"easemove/#introduction","title":"Introduction","text":"

Ease-move game object.

  • Author: Rex
  • Method only
"},{"location":"easemove/#usage","title":"Usage","text":"

Sample code

"},{"location":"easemove/#install-plugin","title":"Install plugin","text":""},{"location":"easemove/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexeasemoveplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexeasemoveplugin.min.js', true);\n
  • Ease-move to/from
    var easemove = scene.plugins.get('rexeasemoveplugin').moveTo(gameObject, duration, x, y, ease);\nvar easemove = scene.plugins.get('rexeasemoveplugin').moveFrom(gameObject, duration, x, y, ease);\n
"},{"location":"easemove/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import EaseMovePlugin from 'phaser3-rex-plugins/plugins/easemove-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexEaseMove',\nplugin: EaseMovePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Ease-move to/from
    var easemove = scene.plugins.get('rexEaseMove').moveTo(gameObject, duration, x, y, ease);\nvar easemove = scene.plugins.get('rexEaseMove').moveFrom(gameObject, duration, x, y, ease);\n
"},{"location":"easemove/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import { EaseMoveTo, EaseMoveFrom } from 'phaser3-rex-plugins/plugins/easemove.js';\n
  • EaseMove-out-destroy
    var easemove = EaseMoveTo(gameObject, duration, x, y, ease);\nvar easemove = EaseMoveFrom(gameObject, duration, x, y, ease);\n
"},{"location":"easemove/#move-to","title":"Move to","text":"
var easemove = scene.plugins.get('rexEaseMove').moveTo(gameObject, duration, x, y);\n// var easemove = scene.plugins.get('rexEaseMove').moveTo(gameObject, duration, x, y, ease);\n// easemove = scene.plugins.get('rexEaseMove').moveTo(gameObject, duration, x, y, ease, easemove);\n
  • x, y : End position.
    • Number : End position x/y.
    • String(+=300) : Related position of current position x/y.
    • undefined : Don't move along x/y axis.
  • ease : 'Linear', 'Cubic', 'Elastic', 'Bounce', 'Back' ...
  • easemove : Ease-move behavior.
"},{"location":"easemove/#move-from","title":"Move from","text":"
var easemove = scene.plugins.get('rexEaseMove').moveFrom(gameObject, duration, x, y);\n// var easemove = scene.plugins.get('rexEaseMove').moveFrom(gameObject, duration, x, y, ease);\n// easemove = scene.plugins.get('rexEaseMove').moveFrom(gameObject, duration, x, y, ease, easemove);\n
  • x, y : Start position.
    • Number : Start position x/y.
    • String(-=300) : Related position of current position x/y.
    • undefined : Don't move along x/y axis.
  • ease : 'Linear', 'Cubic', 'Elastic', 'Bounce', 'Back' ...
  • easemove : Ease-move behavior.
"},{"location":"easemove/#events","title":"Events","text":"

See Events of tween task

  • Move completes or is stopped.
    easemove.on('complete', function(gameObject, easemove){\n\n}, scope);\n
"},{"location":"easemove/#inject-methods","title":"Inject methods","text":"
  • Inject methods into game object
    scene.plugins.get('rexEaseMove').injectMethods(gameObject);\n
  • Inject methods into class of game object
    scene.plugins.get('rexEaseMove').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexEaseMove').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into class of game object
    scene.plugins.get('rexEaseMove').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexEaseMove').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into root class of game object
    scene.plugins.get('rexEaseMove').injectMethodsToRootClass(e);\n// scene.plugins.get('rexEaseMove').injectMethods(Phaser.GameObjects.GameObject.prototype);\n
"},{"location":"easemove/#injected-methods","title":"Injected methods","text":"
  • Move from
    gameObject.moveFrom(duration, x, y);\n// gameObject.moveFrom(duration, x, y, ease);\n// gameObject.moveFrom({x, y, duration, ease});\n// gameObject.moveFrom({x, y, speed, ease});\n
    or
    gameObject\n.moveFromPromise(duration, x, y, ease)\n// .moveFromPromise({x, y, duration, ease})\n// .moveFromPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
    • x, y : Start position.
      • Number : Start position x/y.
      • String(+=300) : Related position of current position x/y.
      • undefined : Current position x/y.
    • speed : Get duration according to speed and distance between current gameObject position to {x, y}
    • ease : 'Linear', 'Cubic', 'Elastic', 'Bounce', 'Back' ...
  • Move-from destroy
    gameObject.moveFromDestroy(duration, x, y);\n// gameObject.moveFrom(duration, x, y, ease);\n// gameObject.moveFrom({x, y, duration, ease});\n// gameObject.moveFrom({x, y, speed, ease});\n
    or
    gameObject\n.moveFromDestroyPromise(duration, x, y, ease)\n// .moveFromDestroyPromise({x, y, duration, ease})\n// .moveFromDestroyPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
  • Move to
    gameObject.moveTo(duration, x, y);\n// gameObject.moveTo(duration, x, y, ease);\n// gameObject.moveTo({x, y, duration, ease});\n// gameObject.moveTo({x, y, speed, ease});\n
    or
    gameObject\n.moveToPromise(duration, x, y, ease)\n// .moveToPromise({x, y, duration, ease})\n// .moveToPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
    • x, y : End position.
      • Number : End position x/y.
      • String(+=300) : Related position of current position x/y.
      • undefined : Current position x/y.
    • speed : Get duration according to speed and distance between current gameObject position to {x, y}
    • ease : 'Linear', 'Cubic', 'Elastic', 'Bounce', 'Back' ...
  • Move-to destroy
    gameObject.moveToDestroy(duration, x, y);\n// gameObject.moveTo(duration, x, y, ease);\n// gameObject.moveTo({x, y, duration, ease});\n// gameObject.moveTo({x, y, speed, ease});\n
    or
    gameObject\n.moveToDestroyPromise(duration, x, y, ease)\n// .moveToDestroyPromise({x, y, duration, ease})\n// .moveToDestroyPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
  • Move-stop
    gameObject.moveStop();\n// gameObject.moveStop(true);  // Set to end position\n
  • Events
    • Move-from complete
      gameObject.on('movefrom.complete', function(gameObject) { });\n
    • Move-to complete
      gameObject.on('moveto.complete', function(gameObject) { });\n
"},{"location":"effect-properties/","title":"Effect properties","text":""},{"location":"effect-properties/#introduction","title":"Introduction","text":"

Attach properties to a game object or camera, to add/remove/control builtin preFX or postFX effects.

  • Author: Rex
  • Method only
  • Pre-fx, and Post-fx shader effects

WebGL only

Only work in WebGL render mode.

"},{"location":"effect-properties/#live-demos","title":"Live demos","text":"
  • Color effects
  • Reveal
  • Interactive
  • Camera
"},{"location":"effect-properties/#usage","title":"Usage","text":"

Sample code

"},{"location":"effect-properties/#install-plugin","title":"Install plugin","text":""},{"location":"effect-properties/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexeffectpropertiesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexeffectpropertiesplugin.min.js', true);\n
  • Attach properties to a game object/camera.
    scene.plugins.get('rexeffectpropertiesplugin').add(gameObject);\n
    scene.plugins.get('rexeffectpropertiesplugin').add(camera);\n
"},{"location":"effect-properties/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import EffectPropertiesPlugin from 'phaser3-rex-plugins/plugins/effectproperties-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexEffectProperties',\nplugin: EffectPropertiesPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Attach properties to a game object/camera.
    scene.plugins.get('rexEffectProperties').add(gameObject);\n
    scene.plugins.get('rexEffectProperties').add(camera);\n
"},{"location":"effect-properties/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import AddEffectPropertiesProperties from 'phaser3-rex-plugins/plugins/effectproperties.js';\n
  • Attach properties to a game object/camera.
    AddEffectPropertiesProperties(gameObject);\n
    AddEffectPropertiesProperties(camera);\n
"},{"location":"effect-properties/#attach-properties","title":"Attach properties","text":"

Supported effects are barrel, blackWhite, bloom, blur, bokeh, brightness, brown, circle, contrast, desaturate, desaturateLuminance, displacement, glow, gradient, grayscale, hue, kodachrome, lsd, negative, pixelate, polaroid, reveal, saturate, sepia, shadow, shiftToBGR, shine, technicolor, tiltShift, vignette, vintagePinhole, wipe.

  • Attatch properties of all effects to a game object/camera.
    scene.plugins.get('rexEffectProperties').add(gameObject);\n
    scene.plugins.get('rexEffectProperties').add(camera);\n
  • Attatch properties of some preFX/postFX effects to a game object/camera.
    scene.plugins.get('rexEffectProperties').add(gameObject, {\nbarrel: true,\nblackWhite: true,\nbloom: true,\nblur: true,\nbokeh: true,\nbrightness: true,\nbrown: true,\ncircle: true,\ncontrast: true,\ndesaturate: true,\ndesaturateLuminance: true,\ndisplacement: true,\nglow: true,\ngradient: true,\ngrayscale: true,\nhue: true,\nkodachrome: true,\nlsd: true,\nnegative: true,\npixelate: true,\npolaroid: true,\nreveal: true,\nsaturate: true,\nsepia: true,\nshadow: true,\nshiftToBGR: true,\nshine: true,\ntechnicolor: true,\ntiltShift: true,\nvignette: true,\nvintagePinhole: true,\nwipe: true,\n});\n
    or
    scene.plugins.get('rexEffectProperties').add(gameObject, [\n'barrel', 'blackWhite', 'bloom', 'blur', 'bokeh', 'brightness', 'brown',\n'circle', 'contrast',\n'desaturate', 'desaturateLuminance', 'displacement',\n'glow', 'gradient', 'grayscale',\n'hue',\n'kodachrome',\n'lsd',\n'negative',\n'pixelate', 'polaroid',\n'reveal',\n'saturate', 'sepia', 'shadow', 'shiftToBGR', 'shine',\n'technicolor', 'tiltShift',\n'vignette', 'vintagePinhole',\n'wipe'\n]);\n
    or
    scene.plugins.get('rexEffectProperties').add(gameObject, effectName);\n
    • A plain object with effect names.
    • A list of effect name string.
    • A effect name string.
"},{"location":"effect-properties/#effect-properties","title":"Effect properties","text":"

Will try to create preFX effect if gameObject has preFX, otherwise, try to create postFX effect.

"},{"location":"effect-properties/#barrel","title":"Barrel","text":"
  • barrel :
    • A number : Enable this effect and set intensity of barrel (1: origin).
    • null : Remove this effect
"},{"location":"effect-properties/#blackwhite","title":"BlackWhite","text":"
  • blackWhite :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#bloom","title":"Bloom","text":"
  • bloomColor :
    • A number : Enable this effect and set color of bloom (0xffffff).
    • null : Remove this effect
  • bloomOffsetX, bloomOffsetY, bloomBlurStrength, bloomStrength, bloomSteps :
    • A number
"},{"location":"effect-properties/#blur","title":"Blur","text":"
  • blurColor :
    • A number : Enable this effect and set color of blur (0xffffff).
    • null : Remove this effect
  • blurQuality, blurX, blurY, blurStrength, blurSteps :
    • A number
"},{"location":"effect-properties/#bokeh","title":"Bokeh","text":"
  • bokehRadius :
    • A number : Enable this effect and set radius of bokeh (0~1).
    • null : Remove this effect
  • bokehAmount, bokehContrast :
    • A number
"},{"location":"effect-properties/#brightness","title":"Brightness","text":"
  • brightness :
    • A number : Enable this effect and set brightness (0~1).
    • null : Remove this effect
"},{"location":"effect-properties/#brown","title":"Brown","text":"
  • brown :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#circle","title":"Circle","text":"
  • circleColor :
    • A number : Enable this effect and set color of circle (0xffffff).
    • null : Remove this effect
  • circleThickness, circleBackgroundColor, circleBackgroundAlpha, circleScale, circleFeather :
    • A number
"},{"location":"effect-properties/#contrast","title":"Contrast","text":"
  • contrast :
    • A number : Enable this effect and set contrast (0~1).
    • null : Remove this effect
"},{"location":"effect-properties/#desaturate","title":"Desaturate","text":"
  • desaturate :
    • A number : Enable this effect and set desaturate (0~1).
    • null : Remove this effect
"},{"location":"effect-properties/#desaturateluminance","title":"DesaturateLuminance","text":"
  • desaturateLuminance :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#displacement","title":"Displacement","text":"
  • displacementKey :
    • A string : Enable this effect and set displacement reference texture.
    • null : Remove this effect
  • displacementX, displacementY :
    • A number
"},{"location":"effect-properties/#glow","title":"Glow","text":"
  • glowColor :
    • A number : Enable this effect and set color of glow (0xffffff).
    • null : Remove this effect
  • glowOuterStrength, glowInnerStrength :
    • A number
"},{"location":"effect-properties/#gradient","title":"Gradient","text":"
  • gradientColor :
    • [number, number] : Enable this effect and set gradient color1 and gradient color2 (0xffffff).
    • null : Remove this effect
  • gradientAlpha, gradientFromX, gradientFromY, gradientToX, gradientToY, gradientSize :
    • A number
"},{"location":"effect-properties/#grayscale","title":"Grayscale","text":"
  • grayscale :
    • A number : Enable this effect and set intensity of grayscale (0~1).
    • null : Remove this effect
"},{"location":"effect-properties/#hue","title":"Hue","text":"
  • hue :
    • A number : Enable this effect and set hue rotation, in degrees.
    • null : Remove this effect
"},{"location":"effect-properties/#kodachrome","title":"Kodachrome","text":"
  • kodachrome :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#lsd","title":"Lsd","text":"
  • lsd :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#negative","title":"Negative","text":"
  • negative :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#pixelate","title":"Pixelate","text":"
  • pixelate :
    • A number : Enable this effect and set size of pixelate, in pixels.
    • null : Remove this effect
"},{"location":"effect-properties/#polaroid","title":"Polaroid","text":"
  • polaroid :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#reveal","title":"Reveal","text":"
  • revealLeft, revealRight, revealUp, or revealDown :
    • A number : Enable this effect with specific reveal direction and set progress (0~1).
    • null : Remove this effect
  • revealWidth :
    • A number
"},{"location":"effect-properties/#saturate","title":"Saturate","text":"
  • saturate :
    • A number : Enable this effect and set saturate (0~1).
    • null : Remove this effect
"},{"location":"effect-properties/#sepia","title":"Sepia","text":"
  • sepia :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#shadow","title":"Shadow","text":"
  • shadowColor :
    • A number : Enable this effect and set color of shadow (0xffffff).
    • null : Remove this effect
  • shadowX, shadowY, shadowDecay, shadowPower, shadowSamples, shadowIntensity :
    • A number
"},{"location":"effect-properties/#shifttobgr","title":"ShiftToBGR","text":"
  • shiftToBGR :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#shine","title":"Shine","text":"
  • shineSpeed :
    • A number : Enable this effect and set speed of shine, in seconds.
    • null : Remove this effect
  • shineLineWidth, shineGradient :
    • A number
"},{"location":"effect-properties/#technicolor","title":"Technicolor","text":"
  • technicolor :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#tiltshift","title":"TiltShift","text":"
  • tiltShiftRadius :
    • A number : Enable this effect and set radius of tiltShift (0~1).
    • null : Remove this effect
  • tiltShiftAmount, tiltShiftContrast, tiltShiftBlurX, tiltShiftBlurY, tiltShiftStrength :
    • A number
"},{"location":"effect-properties/#vignette","title":"Vignette","text":"
  • vignetteRadius :
    • A number : Enable this effect and set radius of vignette (0~1).
    • null : Remove this effect
  • vignetteX, vignetteY, vignetteStrength :
    • A number
"},{"location":"effect-properties/#vintagepinhole","title":"VintagePinhole","text":"
  • vintagePinhole :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#wipe","title":"Wipe","text":"
  • wipeLeft, wipeRight, wipeUp, or wipeDown :
    • A number : Enable this effect with specific wipe direction and set progress (0~1).
    • null : Remove this effect
  • wipeWidth :
    • A number
"},{"location":"effect-properties/#clear-all-effects","title":"Clear all effects","text":"
gameObject.clearAllEffects();\n
"},{"location":"effectlayer-outline/","title":"Effectlayer outline","text":""},{"location":"effectlayer-outline/#introduction","title":"Introduction","text":"

Draw outline of target game objects.

  • Author: Rex
  • Game object
"},{"location":"effectlayer-outline/#live-demos","title":"Live demos","text":"
  • Outline
"},{"location":"effectlayer-outline/#usage","title":"Usage","text":"

Sample code

"},{"location":"effectlayer-outline/#install-plugin","title":"Install plugin","text":""},{"location":"effectlayer-outline/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexoutlineeffectlayerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexoutlineeffectlayerplugin.min.js', true);\n
  • Add outline effect layer object
    var effectLayer = scene.add.rexOutlineEffectLayer(config);\n
"},{"location":"effectlayer-outline/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import OutlineEffectLayerPlugin from 'phaser3-rex-plugins/plugins/outlineeffectlayer-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexOutlineEffectLayerPlugin',\nplugin: OutlineEffectLayerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add outline effect layer object
    var effectLayer = scene.add.rexOutlineEffectLayer(config);\n
"},{"location":"effectlayer-outline/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import OutlineEffectLayer from 'phaser3-rex-plugins/plugins/outlineeffectlayer.js';\n
  • Add outline effect layer object
    var effectLayer = new OutlineEffectLayer(scene, config);\nscene.add.existing(effectLayer);\n
"},{"location":"effectlayer-outline/#create-instance","title":"Create instance","text":"
var effectLayer = scene.add.rexOutlineEffectLayer({\n// knockout: false,\n// thickness: 3,\n// outlineColor: 0x000000\n});\n
  • knockout :
    • true : Draw outline only.
    • false : Draw source texture and outline both.
  • thickness : Thickness of outline.
  • outlineColor : Color of outline.
"},{"location":"effectlayer-outline/#custom-class","title":"Custom class","text":"
  • Define class
    class MyOutlineEffectLayer extends OutlineEffectLayer {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var effectLayer = new MyOutlineEffectLayer(scene, config);\n
"},{"location":"effectlayer-outline/#thickness","title":"Thickness","text":"
  • Get
    var thickness = effectLayer.thickness;\n
  • Set
    effectLayer.thickness = thickness;\n// effectLayer.thickness += value;\n
    or
    effectLayer.setThickness(value);\n
"},{"location":"effectlayer-outline/#outline-color","title":"Outline color","text":"
  • Get
    var color = effectLayer.outlineColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    effectLayer.setOutlineColor(value);\n
    effectLayer.outlineColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"effectlayer-outline/#target-game-objects","title":"Target game objects","text":"

Draw outline of added target game objects.

  • Add
    effectLayer.add(gameObject);\n
  • Remove
    effectLayer.remove(gameObject);\n
  • Clear
    effectLayer.clear();\n
  • Contains
    var hasGameObject = effectLayer.contains(gameObject);\n
"},{"location":"effectlayer-outline/#limitation","title":"Limitation","text":"
  • Can't support if camera.zoom is less then 1

  • Can't support if camera.startFollow(gameObject), i.e. please scroll camera before target game objects draw on effect layer game object.

"},{"location":"eightdirection/","title":"8 direction","text":""},{"location":"eightdirection/#introduction","title":"Introduction","text":"

Move game object by cursor keys, with a constant speed.

  • Author: Rex
  • Arcade behavior of game object
"},{"location":"eightdirection/#live-demos","title":"Live demos","text":"
  • Virtual-joyStick + Eight-direction
"},{"location":"eightdirection/#usage","title":"Usage","text":"

Sample code

"},{"location":"eightdirection/#install-plugin","title":"Install plugin","text":""},{"location":"eightdirection/#load-minify-file","title":"Load minify file","text":"
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexeightdirectionplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexeightdirectionplugin.min.js', true);\n
  • Add eight-direction behavior
    var eightDirection = scene.plugins.get('rexeightdirectionplugin').add(gameObject, config);\n
"},{"location":"eightdirection/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine and install plugin in configuration of game
    import EightDirectionPlugin from 'phaser3-rex-plugins/plugins/eightdirection-plugin.js';\nvar config = {\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexEightDirection',\nplugin: EightDirectionPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add eight-direction behavior
    var eightDirection = scene.plugins.get('rexEightDirection').add(gameObject, config);\n
"},{"location":"eightdirection/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Import class
    import EightDirection from 'phaser3-rex-plugins/plugins/eightdirection.js';\n
  • Add eight-direction behavior
    var eightDirection = new EightDirection(gameObject, config);\n
"},{"location":"eightdirection/#create-instance","title":"Create instance","text":"
var eightDirection = scene.plugins.get('rexEightDirection').add(gameObject, {\nspeed: 200,\n// dir: '8dir',     // 0|'up&down'|1|'left&right'|2|'4dir'|3|'8dir'\n// rotateToDirection: false,\n// wrap: false,\n// padding: 0,\n// enable: true,\n// cursorKeys: scene.input.keyboard.createCursorKeys()\n});\n
  • speed : moving speed, pixels in second.
  • dir :
    • 'up&down', or 0 :Aaccept up or down cursor keys only.
    • 'left&right', or 1 : Aaccept left or right cursor keys only.
    • '4dir', or 2 : Aaccept up, down, left or right cursor keys.
    • '8dir', or 3 : Aaccept up, up-left, up-right, down, down-left, down-right, left, or right cursor keys.
  • rotateToDirection : Set true to change angle towards moving direction.
  • Wrap
    • wrap : Set true to enable wrap mode. Default value is false.
    • padding
  • enable : set false to disable moving.
  • cursorKeys : CursorKey object, using keyboard's cursorKeys by default.
"},{"location":"eightdirection/#set-speed","title":"Set speed","text":"
eightDirection.setSpeed(speed);\n// eightDirection.speed = speed;\n
"},{"location":"eightdirection/#set-rotate-to-direction","title":"Set rotate-to-direction","text":"
eightDirection.setRotateToDirection(rotateToDirection);\n
  • rotateToDirection : Set true to change angle towards moving direction
"},{"location":"eightdirection/#set-direction-mode","title":"Set direction mode","text":"
eightDirection.setDirMode(dir);\n
  • dir :
    • 'up&down', or 0 :Aaccept up or down cursor keys only.
    • 'left&right', or 1 : Aaccept left or right cursor keys only.
    • '4dir', or 2 : Aaccept up, down, left or right cursor keys.
    • '8dir', or 3 : Aaccept up, up-left, up-right, down, down-left, down-right, left, or right cursor keys.
"},{"location":"eightdirection/#set-wrap-mode","title":"Set wrap mode","text":"
ship.setWrapMode(wrap, padding);\n
  • wrap : Set true to enable wrap mode.
"},{"location":"eventemitter3/","title":"Event emitter","text":""},{"location":"eventemitter3/#introduction","title":"Introduction","text":"

Event emitter.

"},{"location":"eventemitter3/#usage","title":"Usage","text":""},{"location":"eventemitter3/#get-event-emitter","title":"Get event emitter","text":"
  • Scene:
    var ee = scene.events;\n
  • Game object:
    var ee = gameObject;\n
"},{"location":"eventemitter3/#attach-listener","title":"Attach listener","text":"
ee.on(eventName, callback, scope);\nee.once(eventName, callback, scope);  // only fire listeners one time\n

Alias

ee.addListener(eventName, callback, scope);\nee.addListener(eventName, callback, scope, true);  // only fire listeners one time\n
"},{"location":"eventemitter3/#fire-event","title":"Fire event","text":"
ee.emit(eventName, parameter0, ...);\n
"},{"location":"eventemitter3/#remove-listeners","title":"Remove listeners","text":"
  • Remove a linstener
    ee.off(eventName, callback, scope);\nee.off(eventName, callback, scope, true);   // only remove one-time listeners\n
    or
    ee.removeListener(eventName, callback, scope); ee.removeListener(eventName, callback, scope, true);  // only remove one-time listeners\n
  • Remove listeners of an event
    ee.off(eventName);\n
    or
    ee.removeListener(eventName); 
  • Remove listeners of all events
    ee.removeAllListeners();\n
"},{"location":"eventemitter3/#get-listeners-count","title":"Get listeners count","text":"
var count = ee.listenerCount(eventName);\n//var noListener = (ee.listenerCount(eventName) === 0);\n
"},{"location":"eventemitter3/#get-listeners","title":"Get listeners","text":"
var listeners = ee.listeners(eventName);\n
"},{"location":"eventemitter3/#get-event-names","title":"Get event names","text":"
var names = ee.eventNames();\n
"},{"location":"eventemitter3/#listener","title":"Listener","text":"
{\nfn: callback,\ncontext: scope,\nonce: once\n}\n
"},{"location":"eventemitter3/#custom-event-emitter-class","title":"Custom event emitter class","text":"
class MyEventEmitter extends Phaser.Events.EventEmitter {\n// construct() {\n//     super();\n// }\n\n// destroy() {\n//     super.destroy();\n// }\n}\n
"},{"location":"eventpromise/","title":"Event promise","text":""},{"location":"eventpromise/#introduction","title":"Introduction","text":"

Return a promise of an event.

  • Author: Rex
  • Method only
"},{"location":"eventpromise/#live-demos","title":"Live demos","text":"
  • Wait complete
"},{"location":"eventpromise/#usage","title":"Usage","text":"

Sample code

"},{"location":"eventpromise/#install-plugin","title":"Install plugin","text":""},{"location":"eventpromise/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexeventpromiseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexeventpromiseplugin.min.js', true);\n
  • Get event promise
    var promoise = scene.plugins.get('rexeventpromiseplugin').waitEvent(eventEmitter, eventName);\n// var promoise = scene.plugins.get('rexeventpromiseplugin').waitComplete(eventEmitter);\n
"},{"location":"eventpromise/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import EventPromisePlugin from 'phaser3-rex-plugins/plugins/eventpromise-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexEventPromise',\nplugin: EventPromisePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Get event promise
    var promoise = scene.plugins.get('rexEventPromise').waitEvent(eventEmitter, eventName);\n// var promoise = scene.plugins.get('rexEventPromise').waitComplete(eventEmitter);\n
"},{"location":"eventpromise/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { WaitEvent, WaitComplete } from 'phaser3-rex-plugins/plugins/eventpromise.js';\n
  • Get event promise
    var promoise = WaitEvent(eventEmitter, eventName);\n// var promoise = WaitComplete(eventEmitter);\n
"},{"location":"eventpromise/#get-event-promise","title":"Get event promise","text":"
var promoise = scene.plugins.get('rexEventPromise').waitEvent(eventEmitter, eventName)\n.then(function() {\n\n})\n
  • eventEmitter : Any kind of event emitter. for example, game object, or tween task, or scene event
"},{"location":"eventpromise/#get-complete-event-promise","title":"Get complete event promise","text":"
var promoise = scene.plugins.get('rexEventPromise').waitComplete(eventEmitter)\n.then(function() {\n\n})\n
  • eventEmitter : Event emitter which will fire 'complete' event, for example, tween task.
"},{"location":"expression-parser/","title":"Expression parser","text":""},{"location":"expression-parser/#introduction","title":"Introduction","text":"

Parse expression string into function. Parser is generated from jison

  • Author: Rex
  • Member of scene
"},{"location":"expression-parser/#live-demos","title":"Live demos","text":"
  • Dot-notation
  • Custom method
  • Proxy as context
"},{"location":"expression-parser/#usage","title":"Usage","text":"

Sample code

"},{"location":"expression-parser/#install-plugin","title":"Install plugin","text":""},{"location":"expression-parser/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexexpressionparserplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexexpressionparserplugin.min.js', true);\n
  • Add parser
    var parser = scene.plugins.get('rexexpressionparserplugin').add();\n
  • Or, parse expression to function object.
    var f = scene.plugins.get('rexexpressionparserplugin').compile(expressionString);\n// var value = f(context);\n
"},{"location":"expression-parser/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ExpressionParserPlugin from 'phaser3-rex-plugins/plugins/expressionparser-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexExpressionParserPlugin',\nplugin: ExpressionParserPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add parser
    var parser = scene.plugins.get('rexExpressionParserPlugin').add();\n
  • Or, parse expression to function object.
    var f = scene.plugins.get('rexExpressionParserPlugin').compile(expressionString);\n// var value = f(context);\n
"},{"location":"expression-parser/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ExpressionParser from 'phaser3-rex-plugins/plugins/expressionparser.js';\n
  • Add parser
    var parser = new ExpressionParser();\n
"},{"location":"expression-parser/#create-instance","title":"Create instance","text":"
var parser = scene.plugins.get('rexExpressionParserPlugin').add();\n
"},{"location":"expression-parser/#execute","title":"Execute","text":""},{"location":"expression-parser/#compile-then-execute","title":"Compile then execute","text":"
  1. Compile expression string into function
    var f = parser.compile(expressionString);\n
    or
    var f = scene.plugins.get('rexExpressionParserPlugin').compile(expressionString);\n
    • expressionString :
      • Number : 1, 1.5, 0xf.
      • Variable : a, $a, _a, a.$b._c_, a['b'].c
      • Arithmetic : +, -, *, \\, %, (, ), ex : '(a + b.c) * 3 + (2 % 3)'.
      • Boolean : >, <, >=, <=, ==, !=, &&, ||, ex '(a > 10) && (a < 30) || (b.c > c)'.
      • Condition : (cond)? v0:v1, ex'(a > b.c)? a:b.c'.
      • Custom method : randomInt(a, b.c).
      • String concat : 'Hello ' + name.
  2. Invoke function
    var value = f(context);\n
    • f : Function object from compiled result.
    • context : Varables used in expression.
      {\na: 10,  // Number\nb: {c: 10},  // Objet with number property\nc: 20,\nrandomInt(a, b) {  // Custom method\nreturn Math.floor(Math.random()*(b-a)+a);\n}\n}\n
"},{"location":"expression-parser/#execute-directly","title":"Execute directly","text":"
var value = parser.exec(expressionString, context);\n

or

var value = parser.exec(f, context);\n
"},{"location":"expression-parser/#custom-method","title":"Custom method","text":"
  • Add method into parser instance
    var parser = scene.plugins.get('rexExpressionParserPlugin').add();\nparser.randomInt = function(a, b) {\nreturn Math.floor(Math.random()*(b-a)+a); }\n// var value = parser.exec('randomInt(a, b)', {a:10, b:20});\n
  • Declare method into class of parser
    class MyParser extends ExpressionParser {\nrandomInt(a, b) {\nreturn Math.floor(Math.random()*(b-a)+a); }\n}\nvar parser = new MyParser();\n// var value = parser.exec('randomInt(a, b)', {a:10, b:20});\n
  • Add method into context
    var context = {\na: 10,\nb: 20,\nrandomInt(a, b) {  // Custom method\nreturn Math.floor(Math.random()*(b-a)+a);\n}\n}\nvar value = parser.exec('randomInt(a, b)', context);\n
"},{"location":"expression-parser/#proxy-as-context","title":"Proxy as context","text":"

Proxy with has and get handlers could be a context.

For example, proxy scene data :

var context = new Proxy({}, {\nhas(target, key) {\nreturn scene.data.has(key);\n},\nget(target, prop) {\nreturn scene.data.get(prop);\n}\n})\n

or

var context = scene.plugins.get('rexExpressionParserPlugin').createProxyContext({\nhas(target, key) {\n// return boolean\n},\nget(target, prop) {\n// return any;\n}\n})\n
"},{"location":"fadeoutdestroy/","title":"Fade out destroy","text":""},{"location":"fadeoutdestroy/#introduction","title":"Introduction","text":"

Fade out game object then destroy it.

  • Author: Rex
  • Method only
"},{"location":"fadeoutdestroy/#usage","title":"Usage","text":"

Sample code

"},{"location":"fadeoutdestroy/#install-plugin","title":"Install plugin","text":""},{"location":"fadeoutdestroy/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfadeplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfadeplugin.min.js', true);\n
  • Fade-out-destroy
    var fade = scene.plugins.get('rexfadeplugin').fadeOutDestroy(gameObject, duration);\n
"},{"location":"fadeoutdestroy/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FadePlugin from 'phaser3-rex-plugins/plugins/fade-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFade',\nplugin: FadePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Fade-out-destroy
    var fade = scene.plugins.get('rexFade').fadeOutDestroy(gameObject, duration);\n
"},{"location":"fadeoutdestroy/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import FadeOutDestroy from 'phaser3-rex-plugins/plugins/fade-out-destroy.js';\n
  • Fade-out-destroy
    var fade = FadeOutDestroy(gameObject, duration);\n
"},{"location":"fadeoutdestroy/#fade-out-destroy","title":"Fade-out-destroy","text":"
var fade = scene.plugins.get('rexFade').fadeOutDestroy(gameObject, duration);\n
"},{"location":"fadeoutdestroy/#events","title":"Events","text":"

See Events of tween task

  • Scale completes or is stopped.
    fade.on('complete', function(gameObject, fade){\n\n}, scope);\n
"},{"location":"fadeoutdestroy/#inject-methods","title":"Inject methods","text":"
  • Inject methods into game object
    scene.plugins.get('rexFade').injectMethods(gameObject);\n
  • Inject methods into class of game object
    scene.plugins.get('rexFade').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexFade').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into class of game object
    scene.plugins.get('rexFade').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexFade').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into root class of game object
    scene.plugins.get('rexFade').injectMethodsToRootClass(e);\n// scene.plugins.get('rexFade').injectMethods(Phaser.GameObjects.GameObject.prototype);\n
"},{"location":"fadeoutdestroy/#injected-methods","title":"Injected methods","text":"
  • Fade-in
    gameObject.fadeIn(duration);\n
    or
    gameObject.fadeIn(duration, endAlpha);\n
    or
    gameObject.fadeIn(duration, {start:0, end:1});\n
    or
    gameObject.fadeInPromise(duration, endAlpha)\n.then(function(){\n// ...\n})\n
    or
    gameObject.fadeInPromise(duration, {start:0, end:1})\n.then(function(){\n// ...\n})\n
  • Fade-out destroy
    gameObject.fadeOutDestroy(duration);\n
    or
    gameObject.fadeOutDestroyPromise(duration)\n.then(function(){\n// ...\n})\n
  • Fade-out without destroy
    gameObject.fadeOut(duration);\n
    or
    gameObject.fadeOutPromise(duration)\n.then(function(){\n// ...\n})\n
  • Events
    • Fade-in complete
      gameObject.on('fadein.complete', function(gameObject) { });\n
    • Fade-out, fade-out destroy complete
      gameObject.on('fadeout.complete', function(gameObject) { });\n
"},{"location":"fadevolume/","title":"Volume fading","text":""},{"location":"fadevolume/#introduction","title":"Introduction","text":"

Fade-in/fade-out volume of sound.

  • Author: Rex
  • Method only
"},{"location":"fadevolume/#usage","title":"Usage","text":"

Sample code

"},{"location":"fadevolume/#install-plugin","title":"Install plugin","text":""},{"location":"fadevolume/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexsoundfadeplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexsoundfadeplugin.min.js', true);\n
  • Sound fade-in/fade-out
    var sound = scene.plugins.get('rexsoundfadeplugin').fadeIn(sound, duration);\nvar sound = scene.plugins.get('rexsoundfadeplugin').fadeOut(sound, duration);\n
"},{"location":"fadevolume/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SoundFadePlugin from 'phaser3-rex-plugins/plugins/soundfade-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexSoundFade',\nplugin: SoundFadePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Sound fade-in/fade-out
    var sound = scene.plugins.get('rexSoundFade').fadeIn(sound, duration);\nvar sound = scene.plugins.get('rexSoundFade').fadeOut(sound, duration);\n
"},{"location":"fadevolume/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import SoundFade from 'phaser3-rex-plugins/plugins/soundfade.js';\n
  • Sound fade-in/fade-out
    var sound = SoundFade.fadeIn(sound, duration);\nvar sound = SoundFade.fadeOut(sound, duration);\n
"},{"location":"fadevolume/#fade-in","title":"Fade in","text":"
  • Play and fade in voluem.
    var sound = scene.plugins.get('rexSoundFade').fadeIn(sound, duration);\n// var sound = scene.plugins.get('rexSoundFade').fadeIn(sound, duration, endVolume, startVolume);\n
    • sound : Sound instance, or a key of audio cache.
"},{"location":"fadevolume/#fade-out","title":"Fade out","text":"
  • Fade out volume then destroy it
    scene.plugins.get('rexSoundFade').fadeOut(sound, duration);\n
    • sound : Sound instance.
  • Fade out volume then stop it
    scene.plugins.get('rexSoundFade').fadeOut(sound, duration, false);\n
    • sound : Sound instance.
"},{"location":"filechooser/","title":"File chooser","text":""},{"location":"filechooser/#introduction","title":"Introduction","text":"

Create a transparent file chooser button (<input type=\"file\">).

  • Author: Rex
  • DOM Game object
"},{"location":"filechooser/#live-demos","title":"Live demos","text":"
  • File chooser button
  • Open file chooser dialog
"},{"location":"filechooser/#usage","title":"Usage","text":"

Sample code

"},{"location":"filechooser/#install-plugin","title":"Install plugin","text":""},{"location":"filechooser/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfilechooserplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfilechooserplugin.min.js', true);\n
  • Add file chooser object
    var fileChooser = scene.add.rexFileChooser(config);\n
"},{"location":"filechooser/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FileChooserPlugin from 'phaser3-rex-plugins/plugins/filechooser-plugin.js';\nvar config = {    parent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFileChooser',\nplugin: FileChooserPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add file chooser object
    var fileChooser = scene.add.rexFileChooser(config);\n
"},{"location":"filechooser/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import { FileChooser } from 'phaser3-rex-plugins/plugins/filechooser.js';\n
  • Add file chooser object
    var fileChooser = new FileChooser(config);\nscene.add.existing(fileChooser);\n
"},{"location":"filechooser/#add-file-chooser-object","title":"Add file chooser object","text":"
var fileChooser = scene.add.rexFileChooser({\naccept: '',\nmultiple: false\n});\n// var fileChooser = scene.add.rexFileChooser(x, y, width, height, config);\n
  • accept : A filter for what file types the user can pick from the file input dialog box.
    • 'image/*' : The user can pick all image files.
    • 'audio/*' : The user can pick all sound files.
    • 'video/*' : The user can pick all video files.
    • file_extension : Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can pick from.
  • multiple : Set true to select multiple files.
"},{"location":"filechooser/#custom-class","title":"Custom class","text":"
  • Define class
    class MyFlieChooser extends FileChooser {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config) {\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var fileChooser = new MyFlieChooser(scene, x, y, width, height, config);\n
"},{"location":"filechooser/#sync","title":"Sync","text":"

Sync position, size and origin to another game object.

fileChooser.syncTo(gameObject);\n
"},{"location":"filechooser/#selected-files","title":"Selected files","text":"
var files = fileChooser.files;\n
  • files : Array of file object.
"},{"location":"filechooser/#set-accept-filter","title":"Set accept filter","text":"
fileChooser.setAccept(accept);\n
  • accept : A filter for what file types the user can pick from the file input dialog box.
    • 'image/*' : The user can pick all image files.
    • 'audio/*' : The user can pick all sound files.
    • 'video/*' : The user can pick all video files.
    • file_extension : Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can pick from.
"},{"location":"filechooser/#multiple-files","title":"Multiple files","text":"
  • Enable
    fileChooser.setMultiple();\n
  • Disable
    fileChooser.setMultiple(false);\n
"},{"location":"filechooser/#events","title":"Events","text":"
  • Selected file(s) changed
    fileChooser.on('change', function(fileChooser) {\nvar files = fileChooser.files;\nif (files.length === 0) { // No selected file\nreturn;\n}\n\nvar file = files[0];\nvar url = URL.createObjectURL(file);\n// ...\n})\n
"},{"location":"filechooser/#load-file-to-cache","title":"Load file to cache","text":"
fileChooser.loadFile(file, loaderType, key);\n// fileChooser.loadFile(file, loaderType, key, cahceType);\n

or

fileChooser.loadFilePromise(file, loaderType, key, cahceType)\n.then(function(content) {\n\n})\n
  • file : File object, see Events
  • loaderType : image, text, binary, ... See Loader
  • key : Unique string key.
  • cahceType :
    • undefined : Use default value.
  • content : Content of file.
"},{"location":"filechooser/#create-object-url","title":"Create object URL","text":"
  • Create object url
    var objectURL = URL.createObjectURL(file);\n
  • Release object url
    URL.revokeObjectURL(objectURL);\n
"},{"location":"filechooser/#open-file-chooser","title":"Open file chooser","text":"

Failure

This method won't work at ios.

Note

Open a file chooser dialog under any touch event. i.e. User can't open file chooser dialog directly.

scene.plugins.get('rexFileChooser').open({\n// accept: '',\n// multiple: false,\n// closeDelay: 200\n})\n.then(function(result) {\n// var files = result.files;\n})\n
  • accept : A filter for what file types the user can pick from the file input dialog box.
    • 'image/*' : The user can pick all image files.
    • 'audio/*' : The user can pick all sound files.
    • 'video/*' : The user can pick all video files.
    • file_extension : Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can pick from.
  • multiple : Set true to select multiple files.
  • closeDelay : Add a small delay to detect dialog canceled after game focus.
    • File chooser dialog dose not have cancel event.
  • files : Array of selected files.
    • Each file object (files[i]) has properties
      • file.name : File name with file extension.
      • file.type : File type. (ex. 'image/jpeg')
      • file.size : File size in bytes.
      • file.lastModified : Timestamp of last-modified time.
      • file.lastModifiedDate : Date object of last-modified time. Equal to new Data(lastModified).
      • Get object url :
        var objectURL = URL.createObjectURL(file);\n
    • Length files is 0 : User cancels file chooser dialog.
"},{"location":"filechooser/#enable-clicking-open","title":"Enable clicking-open","text":"
  • Enable
    fileChooser.setOpenEnable();\n// fileChooser.setOpenEnable(true);\n
  • Disable
    fileChooser.setOpenEnable(false)\n
"},{"location":"filechooser/#other-properties","title":"Other properties","text":"

See dom game object, game object

"},{"location":"filechooser/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"

See dom-element's Interactive with other game objects

"},{"location":"filedropzone/","title":"File drop zone","text":""},{"location":"filedropzone/#introduction","title":"Introduction","text":"

Create a div element for dropping file(s).

  • Author: Rex
  • DOM Game object
"},{"location":"filedropzone/#live-demos","title":"Live demos","text":"
  • Drop text file
  • Drop image file
  • Interactve with other game objects
"},{"location":"filedropzone/#usage","title":"Usage","text":"

Sample code

"},{"location":"filedropzone/#install-plugin","title":"Install plugin","text":""},{"location":"filedropzone/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfiledropzoneplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfiledropzoneplugin.min.js', true);\n
  • Add file-drop-zone object
    var fileDropZone = scene.add.rexFileDropZone(config);\n
"},{"location":"filedropzone/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FileDropZonePlugin from 'phaser3-rex-plugins/plugins/filedropzone-plugin.js';\nvar config = {    parent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n}, // ...\nplugins: {\nglobal: [{\nkey: 'rexFileDropZone',\nplugin: FileDropZonePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add file-drop-zone object
    var fileDropZone = scene.add.rexFileDropZone(config);\n
"},{"location":"filedropzone/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import { FileDropZone } from 'phaser3-rex-plugins/plugins/filedropzone.js';\n
  • Add file-drop-zone object
    var fileDropZone = new FileDropZone(config);\nscene.add.existing(fileDropZone);\n
"},{"location":"filedropzone/#add-file-drop-zone-object","title":"Add file-drop-zone object","text":"
var fileDropZone = scene.add.rexFileDropZone({\n// style: { },\n\n// dropEnable: true,\n// filters: { filterType: (file, files) => boolean }\n});\n// var fileDropZone = scene.add.rexFileDropZone(x, y, width, height, config);\n
  • style : CSS style of div element.
  • dropEnable :
    • true : Fire drop events when dropping files. Default behavior.
    • false : Won't fire drop events.
  • filters : Filter methods, optional. For example, image files filter, will fire 'drop.image' event
    {\nimage: function(file, files) { return file.name.match(/\\.(jpg|jpeg|png|gif)$/i)\n}\n}\n
"},{"location":"filedropzone/#custom-class","title":"Custom class","text":"
  • Define class
    class MyFileDropZone extends FileDropZone {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config) {\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var fileDropZone = new MyFileDropZone(scene, x, y, width, height, config);\n
"},{"location":"filedropzone/#sync","title":"Sync","text":"

Sync position, size and origin to another game object.

fileDropZone.syncTo(gameObject);\n
"},{"location":"filedropzone/#dropped-files","title":"Dropped files","text":"
var files = fileDropZone.files;\n
  • files : Array of file object.
"},{"location":"filedropzone/#events","title":"Events","text":"
  • Drop files
    fileDropZone.on('drop', function(fileDropZone) {\nvar files = fileDropZone.files;\n})\n
  • Drop filtered files
    fileDropZone.on('drop.' + filterType, function(files) {\n})\n
  • Drag-enter/drag-leave/drag-over file(s)
    fileDropZone.on('dragenter', function(fileDropZone) {\n})\n
    fileDropZone.on('dragleave', function(fileDropZone) {\n})\n
    fileDropZone.on('dragover', function(fileDropZone) {\n})\n

Warning

Game objects under this file drop zone can't receive touch input events.

"},{"location":"filedropzone/#enable-drop-events","title":"Enable drop events","text":"
  • Enable
    fileDropZone.setDropEnable();\n// fileDropZone.setDropEnable(true);\n
  • Disable
    fileDropZone.setDropEnable(false);\n
  • Toggle
    fileDropZone.toggleDropEnable();\n
"},{"location":"filedropzone/#load-file-to-cache","title":"Load file to cache","text":"
fileDropZone.loadFile(file, loaderType, key);\n// fileDropZone.loadFile(file, loaderType, key, cahceType, onComplete);\n

or

fileDropZone.loadFilePromise(file, loaderType, key, cahceType)\n.then(function(content) {\n\n})\n
  • file : File object, see Events
  • loaderType : image, text, binary, ... See Loader
  • key : Unique string key.
  • cahceType :
    • undefined : Use default value.
  • onComplete : Callback invoked when file loaded to cache.
  • content : Content of file.
"},{"location":"filedropzone/#create-object-url","title":"Create object URL","text":"
  • Create object url
    var objectURL = URL.createObjectURL(file);\n
  • Release object url
    URL.revokeObjectURL(objectURL);\n
"},{"location":"filedropzone/#other-properties","title":"Other properties","text":"

See dom game object, game object

"},{"location":"filedropzone/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"

See dom-element's Interactive with other game objects

"},{"location":"firebase-auth/","title":"Authentication","text":""},{"location":"firebase-auth/#introduction","title":"Introduction","text":"

It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.

  • Author: Firebase
"},{"location":"firebase-auth/#usage","title":"Usage","text":"

Official document

Sample code

"},{"location":"firebase-auth/#setup","title":"Setup","text":"
  1. Import firestore
    import firebase from 'firebase/app';\nimport 'firebase/auth';\n
    Firebase has been included in package.json.
  2. Initialize
    var firebaseApp = firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n});\n
"},{"location":"firebase-auth/#on-sign-insign-out","title":"On sign-in/sign-out","text":"
firebaseApp.auth().onAuthStateChanged(function (user) {\nif (user) {\n// User is signed in.\nvar displayName = user.displayName;\nvar email = user.email;\nvar emailVerified = user.emailVerified;\nvar photoURL = user.photoURL;\nvar isAnonymous = user.isAnonymous;\nvar uid = user.uid;\nvar providerData = user.providerData;\n// ...\n} else {\n// User is signed out.\n// ...\n}\n});\n
"},{"location":"firebase-auth/#sign-in-with-facebook","title":"Sign-in with facebook","text":"
var provider = new firebase.auth.FacebookAuthProvider();\nfirebaseApp.auth().signInWithPopup(provider).then(function (result) {\n// This gives you a Facebook Access Token. You can use it to access the Facebook API.\nvar token = result.credential.accessToken;\n// The signed-in user info.\nvar user = result.user;\n// ...\n}).catch(function (error) {\n// Handle Errors here.\nvar errorCode = error.code;\nvar errorMessage = error.message;\n// The email of the user's account used.\nvar email = error.email;\n// The firebase.auth.AuthCredential type that was used.\nvar credential = error.credential;\n// ...\n});\n
"},{"location":"firebase-auth/#sign-in-with-google","title":"Sign-in with Google","text":"
var provider = new firebase.auth.GoogleAuthProvider();\nfirebaseApp.auth().signInWithPopup(provider).then(function (result) {\n// This gives you a Google Access Token. You can use it to access the Google API.\nvar token = result.credential.accessToken;\n// The signed-in user info.\nvar user = result.user;\n// ...\nconsole.log(user);\n}).catch(function (error) {\n// Handle Errors here.\nvar errorCode = error.code;\nvar errorMessage = error.message;\n// The email of the user's account used.\nvar email = error.email;\n// The firebase.auth.AuthCredential type that was used.\nvar credential = error.credential;\n// ...\n});\n
"},{"location":"firebase-auth/#sign-in-with-password","title":"Sign-in with password","text":"
  • Create new user
    firebaseApp.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {\n// Handle Errors here.\nvar errorCode = error.code;\nvar errorMessage = error.message;\n});\n
  • Sign-in
    firebase.auth().signInWithEmailAndPassword(email, password).catch(function (error) {\n// Handle Errors here.\nvar errorCode = error.code;\nvar errorMessage = error.message;\n});\n
"},{"location":"firebase-auth/#sign-out","title":"Sign-out","text":"
firebaseApp.auth().signOut();\n
"},{"location":"firebase-auth/#current-sign-in-user","title":"Current sign-in user","text":"
var user = firebaseApp.auth().currentUser;\nif (user != null) {\nvar name = user.displayName;\nvar email = user.email;\nvar photoUrl = user.photoURL;\nvar emailVerified = user.emailVerified;\nvar uid = user.uid;\n}\n
"},{"location":"firebase-auth/#update-email","title":"Update email","text":"
user.updateEmail('...').then(function() {\n// Update successful.\n}).catch(function(error) {\n// An error happened.\n});\n
"},{"location":"firebase-auth/#update-profile","title":"Update profile","text":"
user.updateProfile({\ndisplayName: '...',\nphotoURL: '...'\n}).then(function() {\n// Update successful.\n}).catch(function(error) {\n// An error happened.\n});\n
"},{"location":"firebase-auth/#send-a-verification-email","title":"Send a verification email","text":"
user.sendEmailVerification().then(function() {\n// Email sent.\n}).catch(function(error) {\n// An error happened.\n});\n
"},{"location":"firebase-broadcast/","title":"Broadcast","text":""},{"location":"firebase-broadcast/#introduction","title":"Introduction","text":"

Broadcast real-time messages, using firebase-database.

  • Author: Rex
"},{"location":"firebase-broadcast/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-broadcast/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-broadcast/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add messager object
    var messager = scene.plugins.get('rexfirebaseplugin').add.broadcast(config);\n
"},{"location":"firebase-broadcast/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add messager object
    var messager = scene.plugins.get('rexFirebase').add.broadcast(config);\n
"},{"location":"firebase-broadcast/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { Broadcast } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add messager object
    var messager = new Broadcast(config);\n
"},{"location":"firebase-broadcast/#create-instance","title":"Create instance","text":"
var messager = scene.plugins.get('rexFirebase').add.broadcast({\nroot: '',\n// senderID: '',\n// senderName: '',\n// receiverID: '',\n// history: 0\n});\n
  • root : Path of this messager.
  • senderID : ID of sender.
  • senderName : Name of sender.
  • receiverID : ID of receiver/channel.
  • history : Stored received (history) messages in client side.
    • 0, or false : No history message stored.
    • -1, or true : Infinity history message stored. i.e. store all messages from starting updating.
    • A number larger then 0 : Length of stored history message.
"},{"location":"firebase-broadcast/#send-message","title":"Send message","text":"
  1. Set sender in config, or setSender method.
    messager.setSender(userID, userName);\n
    or
    messager.setSender({\nuserID: userID,\nuserName: userName\n});\n
    • userID : User ID of sender.
    • userName : Display name of sender.
  2. Set receiver in config, or setReceiver method.
    messager.setReceiver(receiverID);\n
    • receiverID : ID of receiver/channel.
  3. Send message to receiverID.
    messager.send(message)\n// .then(function() { })\n// .catch(function() { })\n
    • message : A string message, or a JSON data.
"},{"location":"firebase-broadcast/#receive-messages","title":"Receive messages","text":"
  1. Register receive event
    messager.on('receive', function(data){\n// var senderID = data.senderID;\n// var senderName = data.senderName;\n// var message = data.message;\n})\n
  2. Set receiver in config, or setReceiver method
    messager.setReceiver(receiverID);\n
    • receiverID : ID of receiver/channel.
  3. Start receiving
    messager.startReceiving();\n
  4. Stop receive
    messager.stopReceiving();\n

Only receive messages after invoking startReceiving method. Previous messages won't be got anymore.

"},{"location":"firebase-broadcast/#received-messages","title":"Received messages","text":"

Received messages will be saved in client side.

  • Get received (history) messages.
    var messages = messager.getHistory();\n
  • Clear history messages.
    messager.clearHistory();\n
"},{"location":"firebase-files/","title":"Files","text":""},{"location":"firebase-files/#introduction","title":"Introduction","text":"

Save JSON data, using firebase-firestore.

Each owner has several files, each file contains header and content indexed by fileID.

  • Author: Rex
"},{"location":"firebase-files/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-files/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-files/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add file-manager object
    var fileManager = scene.plugins.get('rexfirebaseplugin').add.files(config);\n
"},{"location":"firebase-files/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add file-manager object
    var fileManager = scene.plugins.get('rexFirebase').add.files(config);\n
"},{"location":"firebase-files/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { Files } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add file-manager object
    var fileManager = new Files(config);\n
"},{"location":"firebase-files/#create-instance","title":"Create instance","text":"
var fileManager = scene.plugins.get('rexFirebase').add.files({\nroot: ''\n});\n
  • root : Collection name of these files.
"},{"location":"firebase-files/#save-file","title":"Save file","text":"
  1. Set file owner.
    fileManager.setOwner(userID);\n
    or
    fileManager.setOwner({\nuserID: userID\n});\n
    • userID : User ID of file owner.
  2. Save header and content data.
    • Overwrite
      fileManager.save(fileID, header, content);\n
      • fileID : Unique ID of this file.
      • header : Header data for indexing, a JSON object.
        • Reserve keys : userID, fileID, type, contentDocID. (i.e. don't use these keys)
      • content : Content/body, a JSON object.
        • Reserve keys : userID, fileID, type. (i.e. don't use these keys)
    • Update
      fileManager.save(fileID, header, content, true);\n
"},{"location":"firebase-files/#load-headers","title":"Load headers","text":"
  1. Set file owner.
    fileManager.setOwner(userID);\n
  2. Load all headers of this file owner.
    fileManager.loadHeaders()\n.then(function(result) { // var headers = result.headers;\n// var userID = result.userID;\n})\n.catch(function(result) {\n// var error = result.error;\n// var userID = result.userID;\n})\n
    • headers : Get header by headers[fileID], each header contains
      • header.fileID : Unique ID of this file.
      • header.userID : User ID of file owner.
"},{"location":"firebase-files/#load-file","title":"Load file","text":"
  1. Set file owner.
    fileManager.setOwner(userID);\n
  2. Load file.
    fileManager.load(fileID)\n.then(function(result) { // var header = result.header;\n// var content = result.content;\n// var fileID = result.fileID;\n// var userID = result.userID;\n})\n.catch(function(result) {\n// var error = result.error;\n// var fileID = result.fileID;\n// var userID = result.userID;\n})\n
    • header, content : Header/content of this file.
    • fileID : Unique ID of this file.
    • userID : User ID of file owner.
"},{"location":"firebase-firestore/","title":"Firestore","text":""},{"location":"firebase-firestore/#introduction","title":"Introduction","text":"

Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform.

  • Author: Firebase
"},{"location":"firebase-firestore/#usage","title":"Usage","text":"

Official document

Sample code

"},{"location":"firebase-firestore/#setup","title":"Setup","text":"
  1. Import firestore
    import firebase from 'firebase/app';\nimport 'firebase/firestore';\n
    Firebase has been included in package.json.
  2. Initialize
    var firebaseApp = firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n});\nvar db = firebaseApp.firestore();\ndb.settings({\ntimestampsInSnapshots: true\n})\n
"},{"location":"firebase-firestore/#references","title":"References","text":"
  • Reference of collection
    var collectionRef = db.collection(collectionName);\n
  • Reference of document
    var docRef = db.collection(collectionName).doc(docName);\n
"},{"location":"firebase-firestore/#save","title":"Save","text":"
  • Add document
    db.collection(collectionName).add(doc)      // doc: { ... }\n.then(function(doc) { /* ... */ })\n.catch(function(error) { /* ... */ });\n
    Maximum size for a document : 1 MiB (1,048,576 bytes)
  • Set document
    db.collection(collectionName).doc(docName).set(keyValues)  // keyValues: { ... }\n.then(function(doc) { /* ... */ })\n.catch(function(error) { /* ... */ });\n
    Overwrite document
  • Update data
    db.collection(collectionName).doc(docName).update(keyValues)  // keyValues: { ... }\n.then(function(doc) { /* ... */ })\n.catch(function(error) { /* ... */ });\n
  • Batched writes
    // Get a new write batch\nvar batch = db.batch();\n\nbatch.set(db.collection(collectionName).doc(docName), keyValues);\nbatch.update(db.collection(collectionName).doc(docName), keyValues);\nbatch.delete(db.collection(collectionName).doc(docName));\n// ...\n\n// Commit the batch\nbatch.commit()\n.then(function() { /* ... */ })\n.catch(function(error) { /* ... */ });\n
    Maximum document writting in a commit : 500
  • Delete a document
    db.collection(collectionName).doc(docName).delete()\n.then(function() { /* ... */ })\n.catch(function(error) { /* ... */ });\n
  • Delete a field
    db.collection(collectionName).doc(docName).update({\nkey: firebase.firestore.FieldValue.delete()\n})\n.then(function() { /* ... */ })\n.catch(function(error) { /* ... */ });\n
  • Transaction
    var docRef = db.collection(collectionName).doc(docName);\ndb.runTransaction(function(transaction) {\n// read-modify-write\n// This code may get re-run multiple times if there are conflicts.\nreturn transaction.get(docRef).then(function(doc) {\n// doc.exists\ntransaction.update(docRef, keyValues);\n});\n})\n.then(function() {\n//console.log(\"Transaction successfully committed!\");\n})\n.catch(function(error) {\n//console.log(\"Transaction failed: \", error);\n});\n

Limitation: Writes and transactions section

"},{"location":"firebase-firestore/#server-timestamp","title":"Server timestamp","text":"
firebase.firestore.FieldValue.serverTimestamp()\n
"},{"location":"firebase-firestore/#load","title":"Load","text":"
  • Get a document
    db.collection(collectionName).doc(docName).get()\n.then(function(doc) { /* ... */ })\n.catch(function(error) { /* ... */ });\n
    • doc
      • doc.id
      • doc.data()
  • Get all documents
    db.collection(collectionName).get()\n.then(function(querySnapshot) { /* ... */ })\n.catch(function(error){ /* ... */ });\n
    • querySnapshot
      • querySnapshot.docs
      • querySnapshot.forEach(callback, thisArg)
      • querySnapshot.empty
      • querySnapshot.size
  • Simple queries
    db.collection(collectionName).where(key, op, value).get()\n.then(function(querySnapshot) { /* ... */ })\n.catch(function(error){ /* ... */ });\n
    • op : '>', '==', '<', '>=', '<='
      • != : where(key,'>', value).where(key, '<', value)
  • Compound queries
    db.collection(collectionName).where(key0, op0, value0).where(key1, op1, value1).get()\n.then(function(querySnapshot) { /* ... */ })\n.catch(function(error){ /* ... */ });\n
    • Range filters (<, <=, >, >=) on only one field
"},{"location":"firebase-firestore/#paginate","title":"Paginate","text":"
  • Order, limit
    db.collection(collectionName).orderBy(key).limit(count)\n
    • Descending order : orderBy(key, 'desc')
    • Order by multiple fields : orderBy(key0).orderBy(key1)
  • Query, order, limit
    db.collection(collectionName).where(key, op, value).orderBy(key).limit(count)\n
    • Key of first order must be equal to range comparison (<, <=, >, >=)
  • Page
    1. Start at
      db.collection(collectionName).orderBy(key).startAt(value).limit(count).get()\n.then(function(querySnapshot) { /* ... */ })\n.catch(function(error){ /* ... */ });\n
      • endAt(value)
    2. Next page
      var lastDoc = querySnapshot.docs[querySnapshot.docs.length - 1];\ndb.collection(collectionName).orderBy(key).startAfter(lastDoc).limit(count).get()\n.then(function(querySnapshot) { /* ... */ })\n.catch(function(error){ /* ... */ });\n
      • endBefore(lastDoc)
"},{"location":"firebase-firestore/#get-realtime-updates","title":"Get realtime updates","text":"
  • Get updates of a document
    var unsubscribe = db.collection(collectionName).doc(docName)\n.onSnapshot(function(doc) { /* ... */ });\n
  • Get updates of documents
    var unsubscribe = db.collection(collectionName).where(key, op, value)\n.onSnapshot(function(querySnapshot) { /* ... */ });\n
    • Changes
      var changes = querySnapshot.docChanges();  // [change]\n
      • Change
        • change.type : 'added', 'modified', 'removed'
        • change.newIndex
        • change.oldIndex
  • Detach a listener
    unsubscribe();\n
  • Events for metadata changes
    var unsubscribe = db.collection(collectionName).doc(docName)\n.onSnapshot({\nincludeMetadataChanges: true    // Listen for document metadata changes\n},\nfunction(doc) { /* ... */ } );\n
"},{"location":"firebase-firestore/#indexing","title":"Indexing","text":"

Reference

"},{"location":"firebase-idalias/","title":"ID-alias","text":""},{"location":"firebase-idalias/#introduction","title":"Introduction","text":"

Map an unique ID to another unique ID (alias), using firebase-firestore.

Each owner has several files, each file contains header and content indexed by fileID.

  • Author: Rex
"},{"location":"firebase-idalias/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-idalias/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-idalias/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add id-alias object
    var idAlias = scene.plugins.get('rexfirebaseplugin').add.idAlias(config);\n
"},{"location":"firebase-idalias/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add id-alias object
    var idAlias = scene.plugins.get('rexFirebase').add.idAlias(config);\n
"},{"location":"firebase-idalias/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { IdAlias } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add id-alias object
    var idAlias = new IdAlias(config);\n
"},{"location":"firebase-idalias/#create-instance","title":"Create instance","text":"
var idAlias = scene.plugins.get('rexFirebase').add.idAlias({\nroot: ''\n});\n
  • root : Collection name of this id-alias.
"},{"location":"firebase-idalias/#random-alias","title":"Random alias","text":"

Get alias of an id, or register an alias from a random word.

idAlias.getRandomAlias(id, {\ndigits: 10,\ncandidates: '0123456789',\nretry: 1000\n})\n.then(function(result) { // var alias = result.alias;\n// var id = result.id;\n})\n.catch(function(error) { })\n
  • id : An unique ID.
  • digits : String length of alias.
  • candidates : Candidate characters.
  • retry : Max retry count.
"},{"location":"firebase-idalias/#specific-alias","title":"Specific alias","text":"
  • Add a specific alias
    idAlias.add(id, alias)\n.then(function(result) { // var alias = result.alias;\n// var id = result.id;\n})\n.catch(function(error) { })\n
    • id : An unique ID.
    • alias : Another unique ID.
  • Get ID from alias
    idAlias.getId(alias)\n.then(function(result) { // var alias = result.alias;\n// var id = result.id; // Return undefined if alias is not existed.\n})\n.catch(function(error) { })\n
  • Get alias from ID
    idAlias.getAlias(id)\n.then(function(result) { // var alias = result.alias; // Return undefined if id is not existed.\n// var id = result.id;\n})\n.catch(function(error) { })\n
"},{"location":"firebase-itemtable/","title":"Item table","text":""},{"location":"firebase-itemtable/#introduction","title":"Introduction","text":"

1d/2d/3d table, using firebase-database.

  • Author: Rex
"},{"location":"firebase-itemtable/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-itemtable/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-itemtable/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add table object
    var table = scene.plugins.get('rexfirebaseplugin').add.itemTable(config);\n
"},{"location":"firebase-itemtable/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add table object
    var table = scene.plugins.get('rexFirebase').add.itemTable(config);\n
"},{"location":"firebase-itemtable/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { ItemTable } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add table object
    var table = new ItemTable(config);\n
"},{"location":"firebase-itemtable/#create-instance","title":"Create instance","text":"
var table = scene.plugins.get('rexFirebase').add.itemTable({\nroot: '',\ntype: 3\n});\n
  • root : Path of this item table.
  • type : Table type.
    • 1, or '1d' : 1d table, indexing by (key0)
    • 2, or '2d' : 2d table, indexing by (key0, key1)
    • 3, or '3d' : 3d table, indexing by (key0, key1, key2)
"},{"location":"firebase-itemtable/#write","title":"Write","text":"
  • Set data
    table.setData(key0, value)\n// table.setData(key0, key1, value)\n// table.setData(key0, key1, key2, value)\n.then(function() { })\n.catch(function() { })\n
    • key0, key1, key2 : Any string.
    • value : Number, string, or JSON data.
  • Increase value
    table.incValue(key0, value)\n// table.incValue(key0, key1, value)\n// table.incValue(key0, key1, key2, value)\n.then(function() { })\n.catch(function() { })    
    • key0, key1, key2 : Any string.
    • value : Number.
  • Remove key
    table.removeData(key0)\n// table.removeData(key0, key1)\n// table.inremoveDatacValue(key0, key1, key2)\n.then(function() { })\n.catch(function() { })    
    • key0, key1, key2 : Any string.
  • Batch writing specific values at key pathes
    table.updateData({\n`${key0}` : value0,\n`${key0}/${key1}` : value1,\n`${key0}/${key1}/${key2}` : value2,\n...\n})\n.then(function() { })\n.catch(function() { })    
  • Transaction, write new value according to latest value
    table.transaction(key0, callback)\n// table.transaction(key0, key1, callback)\n// table.transaction(key0, key1, key2, callback)\n.then(function() { })\n.catch(function() { })    
    • key0, key1, key2 : Any string.
    • callback : Write new value according to latest value.
      function(preValue) { return newValue; }\n
  • Remove key when current user disconnect
    table.removeDataOnDisconnect(key0)\n// table.removeDataOnDisconnect(key0, key1)\n// table.removeDataOnDisconnect(key0, key1, key2)\n.then(function() { })\n.catch(function() { })        
  • Set value when current user disconnect
    table.setDataOnDisconnect(key0, value)\n// table.setDataOnDisconnect(key0, key1, value)\n// table.setDataOnDisconnect(key0, key1, key2, value)\n.then(function() { })\n.catch(function() { })        
"},{"location":"firebase-itemtable/#read","title":"Read","text":"
  • Start updating
    table.startUpdate();\n
    • Trigger 'init' event when all data read back.
    • table.initialFlag : Return true when all data read back.
  • Stop updating
    table.stopUpdate();\n
  • Read data stored in client
    var data = table.getData(key0);\n// var data = table.getData(key0, key1);\n// var data = table.getData(key0, key1, key2);\n
    • data : Number, string, or JSON data.
  • Read all data stored in client
    var data = table.getData();\n
    • data : JSON data.
  • Clone data stored in client
    var data = table.cloneData(key0);\n// var data = table.cloneData(key0, key1);\n// var data = table.cloneData(key0, key1, key2);    \n
  • Clone all data stored in client
    var data = table.cloneData();\n
"},{"location":"firebase-itemtable/#events","title":"Events","text":"
  • Initialize, read all data back after start updating
    table.on('init', function(data) { })\n
    • data : Table data.
    • table.initialFlag will be set to true.
  • Any value updated
    table.on('update', function(data) { })\n
    • data : Table data.
"},{"location":"firebase-itemtable/#1d-table","title":"1d table","text":"

1d table, indexing by (key0)

  • On add key0
    table.on('addkey0', function(key0, value) {  });\n
  • On remove key0
    table.on('removekey0', function(key0) {  });\n
  • On change key0
    table.on('changekey0', function(key0, value) {  });\n
"},{"location":"firebase-itemtable/#2d-table","title":"2d table","text":"

2d table, indexing by (key0, key1)

  • On add key0
    table.on('addkey0', function(key0, value) {  });\n
  • On remove key0
    table.on('removekey0', function(key0) {  });\n
  • On add key1
    table.on('addkey1', function(key0, key1, value) {  });\n
  • On remove key1
    table.on('removekey1', function(key0, key1) {  });\n
  • On change key1
    table.on('changekey1', function(key0, key1, value) {  });\n
"},{"location":"firebase-itemtable/#3d-table","title":"3d table","text":"

3d table, indexing by (key0, key1, key2)

  • On add key0
    table.on('addkey0', function(key0, value) {  });\n
  • On remove key0
    table.on('removekey0', function(key0) {  });\n
  • On add key1
    table.on('addkey1', function(key0, key1, value) {  });\n
  • On remove key1
    table.on('removekey1', function(key0, key1) {  });\n
  • On add key2
    table.on('addkey2', function(key0, key1, key2, value) {  });\n
  • On remove key2
    table.on('removekey2', function(key0, key1, key2) {  });\n
  • On change key2
    table.on('changekey2', function(key0, key1, key2, value) {  });\n
"},{"location":"firebase-leaderboard/","title":"Leaderboard","text":""},{"location":"firebase-leaderboard/#introduction","title":"Introduction","text":"

Descending sort scores, using firebase-firestore.

  • Author: Rex
"},{"location":"firebase-leaderboard/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-leaderboard/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-leaderboard/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add leader-board object
    var leaderBoard = scene.plugins.get('rexfirebaseplugin').add.leaderBoard(config);\n
"},{"location":"firebase-leaderboard/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add leader-board object
    var leaderBoard = scene.plugins.get('rexFirebase').add.leaderBoard(config);\n
"},{"location":"firebase-leaderboard/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { LeaderBoard } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add leader-board object
    var leaderBoard = new LeaderBoard(config);\n
"},{"location":"firebase-leaderboard/#create-instance","title":"Create instance","text":"
var leaderBoard = scene.plugins.get('rexFirebase').add.leaderBoard({\nroot: '',\n// timeFilters: false,\n// timeFilterType: 'year',\n// pageItemCount: 100,\n// userID: '',\n// userName: '',\n// boardID: undefined,\n// tag: undefined\n});\n
  • root : Collection name of this leaderboard.
  • timeFilters : Time filter of day/week/month/year.
    • false : Don't use any time filter.
    • true : Enable all time filters.
    • JSON object, enable some time filters.
      {\nday: true,\nweek: true,\nmonth: true,\nyear: true,\nall: true\n}\n
  • timeFilterType : Type of time filter.
    • 'day', or 'd' : Filter scores by current day.
    • 'week', or 'w' : Filter scores by current week.
    • 'month', 'm' : Filter scores by current month.
    • 'year', 'y' : Filter scores by current year. Default value.
    • 'all', 'a' : No time filter to track all scores.
  • pageItemCount : Item count of a page, default value is 100
  • userID : ID of user.
  • userName : Name of user.
  • boardID : Board ID, optional.
  • tag : Custom tag, optional.

Time filter enabled

Add indexes if time filter is enabled. - tagD(ascending), scoreD(descending), boardID(ascending), tag(ascending) - tagW(ascending), scoreW(descending), boardID(ascending), tag(ascending) - tagM(ascending), scoreM(descending), boardID(ascending), tag(ascending) - tagY(ascending), scoreY(descending), boardID(ascending), tag(ascending) - tagA(ascending), scoreA(descending), boardID(ascending), tag(ascending)

"},{"location":"firebase-leaderboard/#post-score","title":"Post score","text":"
  1. Set user.
    leaderBoard.setUser(userID, userName);\n
    or
    leaderBoard.setUser({\nuserID: userID,\nuserName: userName\n});\n
    • userID : User ID.
    • userName : Display name of user, optional.
  2. Set board property, optional.
    • Board ID
      leaderBoard.setBoardID(boardID);\n
    • Custom tag
      leaderBoard.setTag(tag);\n
  3. Post score
    leaderBoard.post(score)\n// leaderBoard.post(score, extraData)\n// leaderBoard.post(score, extraData, timestamp)\n.then(function(record) { })\n.catch(function(error) { })\n
    • score : A number, scores will be sorted descend.
    • extraData : Extra data in JSON format.
    • timestamp : Timestamp of posting.
      • undefined : Current time.
      • A number : For debug usage.
"},{"location":"firebase-leaderboard/#get-my-score","title":"Get my score","text":"
leaderBoard.getScore()\n// leaderBoard.getScore(userID)\n.then(function(score) { })\n.catch(function(error) { })\n
  • userID : User ID, optional.
    • undefined : Current user ID.
  • score : Score object.
    • Time filter enabled : {userID, scoreD, scoreW, scoreM, scoreY, tagD, tagW, tagM, tagY, tagA}
      • scoreD, scoreW, scoreM, scoreY, scoreA : Score of day/week/month/year/all-time.
      • tagD, tagW, tagM, tagY, tagA : Time tag of day/week/month/year/all-time.
    • Time filter disabled : {userID, score}
"},{"location":"firebase-leaderboard/#get-my-rank","title":"Get my rank","text":"
leaderBoard.getRank()\n// leaderBoard.getRank(userID)\n.then(function(rank) { })\n.catch(function(error) { })\n
  • userID : User ID, optional.
    • undefined : Current user ID.
  • rank : Rank object. {userID, rank}
"},{"location":"firebase-leaderboard/#get-scores","title":"Get scores","text":"
  1. Set board property, optional.
    • Board ID
      leaderBoard.setBoardID(boardID);\n
    • Custom tag
      leaderBoard.setTag(tag);\n
  2. Set time filter, optional.
    leaderBoard.setTimeFilterType(type);\n
    • type :
      • 'day', or 'd' : Filter scores by current day.
      • 'week', or 'w' : Filter scores by current week.
      • 'month', 'm' : Filter scores by current month.
      • 'year', 'y' : Filter scores by current year.
      • 'all', 'a' : No time filter to track all scores.
  3. Load scores page by page.
    • Load first page.
      leaderBoard.loadFirstPage()\n.then(function(scores) { })\n.catch(function(error) { })\n
      • scores : An array of score object. Each score object is {userID, userName, socre}
    • Load next page.
      leaderBoard.loadNextPage()\n.then(function(scores) { })\n.catch(function(error) { })\n
      • scores : An array of score object. Each score object is {userID, userName, socre}
    • Load previous page.
      leaderBoard.loadPreviousPage()\n.then(function(scores) { })\n.catch(function(error) { })\n
      • scores : An array of score object. Each score object is {userID, userName, socre}
    • Reload current page.
      leaderBoard.loadCurrentPage()\n.then(function(scores) { })\n.catch(function(error) { })\n
      • scores : An array of score object. Each score object is {userID, userName, socre}
"},{"location":"firebase-leaderboard/#page-index","title":"Page index","text":"
  • Current page index
    var pageIndex = leaderBoard.pageIndex;\n
  • Is first page
    var isFirstPage = leaderBoard.isFirstPage;\n
  • Is last page
    var isLastPage = leaderBoard.isLastPage;\n
"},{"location":"firebase-leaderboard/#delete","title":"Delete","text":"
  • Delete user
    leaderBoard.deleteUserScore(userID)\n.then(function(){ })\n.catch(function(){ })\n
  • Delete board
    leaderBoard.deleteBoard(boardID, tag)\n.then(function(){ })\n.catch(function(){ })\n
"},{"location":"firebase-messages/","title":"Messages","text":""},{"location":"firebase-messages/#introduction","title":"Introduction","text":"

Store messages in firebase-firestore.

  • Author: Rex
"},{"location":"firebase-messages/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-messages/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-messages/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add leader-board object
    var messages = scene.plugins.get('rexfirebaseplugin').add.messages(config);\n
"},{"location":"firebase-messages/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add leader-board object
    var messages = scene.plugins.get('rexFirebase').add.messages(config);\n
"},{"location":"firebase-messages/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { Messages } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add leader-board object
    var messages = new Messages(config);\n
"},{"location":"firebase-messages/#create-instance","title":"Create instance","text":"
var messages = scene.plugins.get('rexFirebase').add.messages({\nroot: '',\n// pageItemCount: 100,\n\n// senderID: '',\n// senderName: '',\n// receiverID: undefined,\n});\n
  • root : Collection name of this messages.
  • pageItemCount : Item count of a page, default value is 100
  • senderID : ID of sender.
  • senderName : Name of sender, optional.
  • receiverID : ID of receiver, optional.
"},{"location":"firebase-messages/#send-message","title":"Send message","text":"
  1. Set sender.
    messages.setSender(userID, userName);\n
    or
    messages.setSender({\nuserID: userID,\nuserName: userName\n});\n
    • userID : User ID.
    • userName : Display name of user, optional.
  2. Set receiver, optional.
    messages.setReceiver(userID);\n
    • userID : User ID.
  3. Send message
    messages.send(message)    .then(function() { })\n.catch(function(error) { })\n
    • message : String, number, or JSON object.
"},{"location":"firebase-messages/#receive-messages","title":"Receive messages","text":"
  1. Set receiverID, optional.
    messages.setReceiver(userID)\n
    • userID : User ID.
  2. Load previous messages, optional.
    messages.loadPreviousMessages()\n.then(function(messageObjs) { })\n.catch(function(error) { })    
    • messageObjs : Array of Received message objects
      • messageObj.senderID, messageObj.senderName : Sernder ID and name.
      • messageObj.receiverID : Receiver ID, optional.
      • messageObj.message : Sent message, a string, number, or JSON object.
      • messageObj.timestamp : Server-timestamp.
  3. Add 'receiver' event.
    messages.on('receive', function(messageObj) {\n// var senderID = messageObj.senderID;\n// var senderName = messageObj.senderName;\n// var receiverID = messageObj.receiverID;\n// var message = messageObj.message;\n// var timestamp = messageObj.timestamp;\n})\n
    • messageObj : Received message object.
  4. Start receiving
    messages.startReceiving();\n
  5. Stop receiving
    messages.stopReceiving();\n

Received messages will be stored in messages.cacheMessages

"},{"location":"firebase-onlineuserlist/","title":"Online user list","text":""},{"location":"firebase-onlineuserlist/#introduction","title":"Introduction","text":"

Online user list, using firebase-database.

  • Author: Rex
"},{"location":"firebase-onlineuserlist/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-onlineuserlist/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-onlineuserlist/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add online-user-list object
    var userList = scene.plugins.get('rexfirebaseplugin').add.onlineUserList(config);\n
"},{"location":"firebase-onlineuserlist/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add online-user-list object
    var userList = scene.plugins.get('rexFirebase').add.onlineUserList(config);\n
"},{"location":"firebase-onlineuserlist/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { OnlineUserList } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add online-user-list object
    var userList = new OnlineUserList(config);\n
"},{"location":"firebase-onlineuserlist/#create-instance","title":"Create instance","text":"
var userList = scene.plugins.get('rexFirebase').add.onlineUserList({\nroot: '',\n// maxUsers: 0,\n\n// userID: '',\n// userName: '',\n});\n
  • root : Path of this online user list.
  • maxUsers: Maximum users in this list. Set to 0 to have infinity users.
  • userID : ID of user.
  • userName : Name of user.
"},{"location":"firebase-onlineuserlist/#join","title":"Join","text":"
  1. Set userID and user name.
    userList.setUser(userID, userName);\n
    or
    userList.setUser({\nuserID: userID,\nuserName: userName\n});\n
    • userID : User ID.
    • userName : Display name.
  2. Join list.
    userList.join()\n// .then(function() { })\n// .catch(function() { })\n
"},{"location":"firebase-onlineuserlist/#leave","title":"Leave","text":"
userList.leave()\n// .then(function() { })\n// .catch(function() { })\n
"},{"location":"firebase-onlineuserlist/#kick-user","title":"Kick user","text":"
userList.leave(userID)\n// .then(function() { })\n// .catch(function() { })\n
"},{"location":"firebase-onlineuserlist/#change-user-name","title":"Change user name","text":"
userList.changeUserName(newUserName)\n// .then(function() { })\n// .catch(function() { })\n
"},{"location":"firebase-onlineuserlist/#user-list","title":"User list","text":"
  • Get users in user list
    var users = userList.getUsers();\n
    • users : Array of user {userID, userName}
  • Is first user in user list?
    var isFirstUser = userList.isFirstUser(userID);\n// var isFirstUser = userList.isFirstUser();  // Current user is first user\n
  • User list is full
    var isFull = userList.isFull();\n
  • Maximun users setting value
    var maxUsers = userList.maxUsers;\n
  • Current user is in list
    var isInList = userList.isInList;\n
"},{"location":"firebase-onlineuserlist/#events","title":"Events","text":"
  • Any user join
    userList.on('join', user);\n
    • user : {userID, userName}
  • Any user leave
    userList.on('leave', user);\n
    • user : {userID, userName}
  • User list updated, includes user join, user leave, and user name changed
    userList.on('update', users);\n
    • users : Array of user {userID, userName}
  • User name is changed
    userList.on('changename', userID, userName, prevUserName);\n
"},{"location":"firebase-overview/","title":"Overview","text":""},{"location":"firebase-overview/#introduction","title":"Introduction","text":"
  • Home page
  • Available libraries
"},{"location":"firebase-overview/#usage","title":"Usage","text":""},{"location":"firebase-overview/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-overview/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>        \n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Get firebase plugin
    var rexFireBase = scene.plugins.get('rexfirebaseplugin');\n
"},{"location":"firebase-overview/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Get firebase plugin
    var rexFireBase = scene.plugins.get('rexFirebase');\n
"},{"location":"firebase-singleroom/","title":"Single room","text":""},{"location":"firebase-singleroom/#introduction","title":"Introduction","text":"

Chat room, using firebase-database.

  • Author: Rex
"},{"location":"firebase-singleroom/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-singleroom/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-singleroom/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add single-room object
    var room = scene.plugins.get('rexfirebaseplugin').add.singleRoom(config);\n
"},{"location":"firebase-singleroom/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add single-room object
    var room = scene.plugins.get('rexFirebase').add.singleRoom(config);\n
"},{"location":"firebase-singleroom/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { SingleRoom } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add single-room object
    var room = new SingleRoom(config);\n
"},{"location":"firebase-singleroom/#create-instance","title":"Create instance","text":"
var room = scene.plugins.get('rexFirebase').add.singleRoom({\nroot: '',\n// maxUsers: 0,\n// userID: '',\n// userName: '',\n// broadcast: true,\n// tables: undefined,\n\n});\n
  • root : Path of this room.
  • maxUsers: Maximum users in this list. Set to 0 to have infinity users.
  • userID : ID of user.
  • userName : Name of user.
  • broadcast : Broadcast chat messages.
    • true : Enable broadcasting, without storing received (history) messages. Default behavior.
    • false : Disable broadcasting.
    • A JSON object :
      {\nhistory: 0\n}\n
      • history : Stored received (history) messages in client side.
        • 0, or false : No history message stored.
        • -1, or true : Infinity history message stored. i.e. store all messages from starting updating.
        • A number larger then 0 : Length of stored history message.
  • tables : Configuration of tables.
    • undefined : No table.
    • Array of table-config JSON object for each table.
      [\n{\nkey: tableKey,\ntype: '1d'\n},\n{\n...\n}\n]\n
      • key : Unique name of this table.
      • type : Table type.
        • 1, or '1d' : 1d table, indexing by (key0)
        • 2, or '2d' : 2d table, indexing by (key0, key1)
        • 3, or '3d' : 3d table, indexing by (key0, key1, key2)
"},{"location":"firebase-singleroom/#current-user-infomation","title":"Current user infomation","text":"
  • User name
    • Get
      var userName = room.userInfo.userName;\n
    • Set
      room.changeUserName(newUserName);\n
  • User ID
    • Get
      var userID = room.userInfo.userID;\n
"},{"location":"firebase-singleroom/#join-room","title":"Join room","text":"
  1. Set userID and user name.
    room.setUser(userID, userName);\n
    • userID : User ID.
    • userName : Display name.
  2. Join room.
    room.joinRoom();\n
"},{"location":"firebase-singleroom/#leave-room","title":"Leave room","text":"
room.leaveRoom();\n
"},{"location":"firebase-singleroom/#kick-user","title":"Kick user","text":"
room.kickUser(userID);\n
"},{"location":"firebase-singleroom/#user-list","title":"User list","text":"
  • Get users in room(user list)
    var users = room.getUsers();\n
    • users : Array of user {userID, userName}
  • Is first user in room(user list)?
    var isFirstUser = room.isFirstUser(userID);\n// var isFirstUser = room.isFirstUser();  // Current user is first user\n
  • Room(user list) is full
    var isFull = room.isFull();\n
  • Maximun users setting value
    var maxUsers = room.maxUsers;\n
  • Current user is in room(user list)
    var isInRoom = room.isInRoom();\n
"},{"location":"firebase-singleroom/#send-message","title":"Send message","text":"
room.broadcast.send(message);\n
  • message : A string message, or a JSON data.
"},{"location":"firebase-singleroom/#receive-messages","title":"Receive messages","text":"
  1. Register receive event
    room.on('broadcast.receive', function(data){\n// var senderID = data.senderID;\n// var senderName = data.senderName;\n// var message = data.message;\n})\n

Only receive messages after joined room. Previous messages won't be got anymore.

"},{"location":"firebase-singleroom/#received-messages","title":"Received messages","text":"

Received messages will be saved in client side.

  • Get received (history) messages.
    var messages = room.broadcast.getHistory();\n
  • Clear history messages.
    room.broadcast.clearHistory();\n
"},{"location":"firebase-singleroom/#tables","title":"Tables","text":"
  • Get table
    var table = room.getTable(key);\n
    • key : Unique name of this table.
"},{"location":"firebase-singleroom/#write","title":"Write","text":"

See here

"},{"location":"firebase-singleroom/#read","title":"Read","text":"

See here

"},{"location":"firebase-singleroom/#events","title":"Events","text":""},{"location":"firebase-singleroom/#user-list-events","title":"User list events","text":"
  • Any user join
    room.on('userlist.join', user);\n
    • user : {userID, userName}
  • Any user leave
    room.on('userlist.leave', user);\n
    • user : {userID, userName}
  • User list updated, includes user join, user leave, and user name changed
    room.on('userlist.update', users);\n
    • users : Array of user {userID, userName}
  • User name is changed
    room.on('userlist.changename', userID, userName, prevUserName);\n
"},{"location":"firebase-singleroom/#broadcast-events","title":"Broadcast events","text":"
  • Receive message
    room.on('broadcast.receive', function(data){\n// var senderID = data.senderID;\n// var senderName = data.senderName;\n// var message = data.message;\n})\n
"},{"location":"firebase-singleroom/#table-events","title":"Table events","text":"

Event names of each table indexed by key

  • init : tables.${key}.init
  • update : tables.${key}.update
  • addkey0 : tables.${key}.addkey0
  • removekey0 : tables.${key}.removekey0
  • changekey0 : tables.${key}.changekey0
  • addkey1 : tables.${key}.addkey1
  • removekey1 : tables.${key}.removekey1
  • changekey1 : tables.${key}.changekey1
  • addkey2 : tables.${key}.addkey2
  • removekey2 : tables.${key}.removekey2
  • changekey2 : tables.${key}.changekey2
"},{"location":"firebase-storage/","title":"Storage","text":""},{"location":"firebase-storage/#introduction","title":"Introduction","text":"

It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.

  • Author: Firebase
"},{"location":"firebase-storage/#usage","title":"Usage","text":"

Official document

Sample code

"},{"location":"firebase-storage/#setup","title":"Setup","text":"
  1. Import firestore
    import firebase from 'firebase/app';\nimport 'firebase/storage';\n
    Firebase has been included in package.json.
  2. Initialize
    var firebaseApp = firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n});\nvar storageRef = firebaseApp.storage().ref();\n
"},{"location":"firebase-storage/#upload-string","title":"Upload string","text":"
  • Upload string
    var fileRef = storageRef.child('path/to/filename');\nvar uploadTask = fileRef.putString(content)\n.then(function (snapshot) {})\n.catch(function (error) {});\n
  • Upload base64 formatted string
    var fileRef = storageRef.child('path/to/filename');\nvar uploadTask = fileRef.putString(content, 'base64')\n.then(function (snapshot) {})\n.catch(function (error) {});\n
  • Upload base64url formatted string
    var fileRef = storageRef.child('path/to/filename');\nvar uploadTask = fileRef.putString(content, 'base64url')\n.then(function (snapshot) {})\n.catch(function (error) {});\n
  • Upload data URL string
    var fileRef = storageRef.child('path/to/filename');\nvar uploadTask = fileRef.putString(content, 'data_url')\n.then(function (snapshot) {})\n.catch(function (error) {});\n
"},{"location":"firebase-storage/#upload-image","title":"Upload image","text":"
  1. Get image from image texture
    var image = scene.textures.get(key).getSourceImage();\n
  2. Copy image to canvas
    var canvas = CanvasPool.create(scene, image.width, image.height);\nvar ctx = canvas.getContext('2d');\nctx.drawImage(image, 0, 0, image.width, image.height);\n
  3. Get blob from canvas, then upload this blob.
    var uploadTask;\ncanvasToBlob(canvas)\n.then(function(blob) {\nvar metadata = {\ncontentType: 'image/jpeg',\n};        var fileRef = storageRef.child('path/to/filename');\nuploadTask = fileRef.put(blob, metadata);\nreturn uploadTask;\n})\n.then(function (snapshot) {})\n.catch(function (error) {});\n
    Reference: canvasToBlob
  4. Free canvas
    CanvasPool.remove(canvas);\n
"},{"location":"firebase-storage/#upload-task","title":"Upload task","text":"
  • Pause task
    uploadTask.pause();\n
  • Resume task
    uploadTask.resume();\n
  • Cancel task
    uploadTask.cancel();\n
  • Monitor progress
    uploadTask.on('state_changed', function(snapshot){\n// Observe state change events such as progress, pause, and resume\nvar progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;\nswitch (snapshot.state) {\ncase firebase.storage.TaskState.PAUSED: // or 'paused'\nconsole.log('Upload is paused');\nbreak;\ncase firebase.storage.TaskState.RUNNING: // or 'running'\nconsole.log('Upload is running');\nbreak;\n}\n},\nfunction(error) {\n// Handle unsuccessful uploads\n// https://firebase.google.com/docs/storage/web/handle-errors\nswitch (error.code) {\ncase 'storage/unauthorized':\n// User doesn't have permission to access the object\nbreak;\ncase 'storage/canceled':\n// User canceled the upload\nbreak;\ncase 'storage/unknown':\n// Unknown error occurred, inspect error.serverResponse\nbreak;\n}\n},\nfunction() {\n// Handle successful uploads on complete\n// Get download url\nuploadTask.snapshot.ref.getDownloadURL()\n.then(function(url) {\nconsole.log('File available at', url);\n})\n.catch(function (error) {});\n}\n);\n
"},{"location":"firebase-storage/#download-file","title":"Download file","text":"
  1. Get download url
    var fileRef = storageRef.child('path/to/filename');\nfileRef.getDownloadURL()\n.then(function(url) {})\n.catch(function (error) {});\n
  2. Download file by loader
"},{"location":"firebase-storage/#delete-file","title":"Delete file","text":"
var fileRef = storageRef.child('path/to/filename');\nfileRef.delete()\n.then(function() {})\n.catch(function(error) {});\n
"},{"location":"flash/","title":"Flash","text":""},{"location":"flash/#introduction","title":"Introduction","text":"

Flashing (set invisible then visible) game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"flash/#usage","title":"Usage","text":"

Sample code

"},{"location":"flash/#install-plugin","title":"Install plugin","text":""},{"location":"flash/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexflashplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexflashplugin.min.js', true);\n
  • Add flash behavior
    var flash = scene.plugins.get('rexflashplugin').add(gameObject, config);\n
"},{"location":"flash/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FlashPlugin from 'phaser3-rex-plugins/plugins/flash-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFlash',\nplugin: FlashPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add flash behavior
    var flash = scene.plugins.get('rexFlash').add(gameObject, config);\n
"},{"location":"flash/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Flash from 'phaser3-rex-plugins/plugins/flash.js';\n
  • Add flash behavior
    var flash = new Flash(gameObject, config);\n
"},{"location":"flash/#create-instance","title":"Create instance","text":"
var flash = scene.plugins.get('rexFlash').add(gameObject, {\n// duration: 500,\n// repeat: 2\n});\n
  • duration : Duration of invisible(50%) and visible(50%), in millisecond.
  • repeat : The number of times the flashing will repeat itself (a value of 1 means the flash will play twice, as it repeated once)
"},{"location":"flash/#start-flashing","title":"Start flashing","text":"
flash.flash();\n// flash.flash(duration, repeat);\n

or

flash.flash({\nduration: 500,\nrepeat: 2\n});\n
"},{"location":"flash/#stop-flashing","title":"Stop flashing","text":"
flash.stop();\n
"},{"location":"flash/#enable","title":"Enable","text":"
  • Enable/resume (default)
    flash.setEnable();\n
    or
    flash.enable = true;\n
  • Disable/pause
    flash.setEnable(false);\n
    or
    flash.enable = false;\n
"},{"location":"flash/#set-duration","title":"Set duration","text":"
flash.setDuration(duration);\n// flash.duration = duration;\n
"},{"location":"flash/#set-repeat","title":"Set repeat","text":"
flash.setRepeat(repeat);\n// flash.repeat = repeat;\n
"},{"location":"flash/#events","title":"Events","text":"
  • On reached target
    flash.on('complete', function(flash, gameObject){});\n
"},{"location":"flash/#status","title":"Status","text":"
  • Is flashing
    var isRunning = flash.isRunning;\n
"},{"location":"flip/","title":"Flip","text":""},{"location":"flip/#introduction","title":"Introduction","text":"

Flipping game object to another face by scaling width/height.

  • Author: Rex
  • Behavior of game object
"},{"location":"flip/#live-demos","title":"Live demos","text":"
  • Flip image
  • Flip ui
"},{"location":"flip/#usage","title":"Usage","text":"

Sample code, Sample code-2

"},{"location":"flip/#install-plugin","title":"Install plugin","text":""},{"location":"flip/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexflipplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexflipplugin.min.js', true);\n
  • Add flip behavior
    var flip = scene.plugins.get('rexflipplugin').add(gameObject, config);\n
"},{"location":"flip/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FlipPlugin from 'phaser3-rex-plugins/plugins/flip-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFlip',\nplugin: FlipPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add flip behavior
    var flip = scene.plugins.get('rexFlip').add(gameObject, config);\n
"},{"location":"flip/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Flip from 'phaser3-rex-plugins/plugins/flip.js';\n
  • Add flip behavior
    var flip = new Flip(gameObject, config);\n
"},{"location":"flip/#create-instance","title":"Create instance","text":"
var flip = scene.plugins.get('rexFlip').add(gameObject, {\nface: 'back',\nfront: { key, frame }, // key, or callback\nback: { key, frame },  // key, or callback\n\n// orientation: 0, // 0|'x'|1|'y'\n// duration: 500,\n// delay: 0,\n// ease: 'Sine',\n});\n
  • face : Initial face.
    • 0, 'front' : Front face.
    • 1, 'back' : Back face.
  • front, back : Texture of front/back face.
    • undefined : Use current texture key, or frame name
    • key : A string for texture key.
    • {key, frame}, or {frame} : A texture key and frame name
    • callback : Configure game object via callback.
      function(gameObject) {\n}\n
  • orientation : Flipping orientation.
    • 0, 'x', or 'horizontal' : Horizontal flipping.
    • 1, 'y', or 'vertical' : Vertical flipping.
  • duration : Duration of flipping, in millisecond.
  • delay : Initial delay
  • ease Ease function. Default value is 'Sine'.
"},{"location":"flip/#start-flipping","title":"Start flipping","text":"
flip.flip();\n// flip.flip(duration);\n
"},{"location":"flip/#stop-flipping","title":"Stop flipping","text":"
flip.stop();\n
"},{"location":"flip/#set-duration","title":"Set duration","text":"
flip.setDuration(duration);\n// flip.duration = duration;\n
"},{"location":"flip/#set-ease","title":"Set ease","text":"
flip.setEase(ease);\n// flip.ease = ease;\n
"},{"location":"flip/#faces","title":"Faces","text":""},{"location":"flip/#current-face","title":"Current face","text":"
  • Get
    var face = flip.face;\n
    • 0 : Front face
    • 1 : Back face
  • Set
    flip.setFace(face);\n// flip.face = face;\n
    • 0, 'front' : Front face.
    • 1, 'back' : Back face.
  • Toggle face
    flip.toggleFace();\n
"},{"location":"flip/#set-texture-of-face","title":"Set texture of face","text":"
  • Front face
    flip.setFrontFace(key, frame);\n
    or
    flip.setFrontFace(callback);\n
    • callback :
      function(gameObject) {\n// ...\n}\n
  • Back face
    flip.setBackFace(key, frame);\n
    or
    flip.setBackFace(callback);\n
    • callback :
      function(gameObject) {\n// ...\n}\n
"},{"location":"flip/#events","title":"Events","text":"
  • On flipping complete
    flip.on('complete', function(gameObject, flip){\n// ...\n});\n
"},{"location":"flip/#status","title":"Status","text":"
  • Is flipping
    var isRunning = flip.isRunning;\n
"},{"location":"format/","title":"Format","text":""},{"location":"format/#introduction","title":"Introduction","text":"

Format string with variables, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"format/#usage","title":"Usage","text":"

Replace %x from an array. x starts from 1.

// const Format = Phaser.Utils.String.Format;\nvar template = 'hello, %1';\nvar view = ['rex'];\nvar result = Format(template, view);\n
"},{"location":"framemanager/","title":"Frame manager","text":""},{"location":"framemanager/#introduction","title":"Introduction","text":"

Draw frames on canvas texture, or dynamic texture.

  • Author: Rex
  • Member of scene
"},{"location":"framemanager/#live-demos","title":"Live demos","text":"
  • Paste text
"},{"location":"framemanager/#usage","title":"Usage","text":"

Sample code

"},{"location":"framemanager/#install-plugin","title":"Install plugin","text":""},{"location":"framemanager/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexframemanagerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexframemanagerplugin.min.js', true);\n
  • Add frame-manager object
    var frameManager = scene.plugins.get('rexframemanagerplugin').add(scene, config);\n
"},{"location":"framemanager/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FrameManagerPlugin from 'phaser3-rex-plugins/plugins/framemanager-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFrameManager',\nplugin: FrameManagerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add frame-manager object
    var frameManager = scene.plugins.get('rexFrameManager').add(scene, config);\n
"},{"location":"framemanager/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import FrameManager from 'phaser3-rex-plugins/plugins/framemanager.js';\n
  • Add frame-manager object
    var frameManager = new FrameManager(scene, config);\n
"},{"location":"framemanager/#create-instance","title":"Create instance","text":"
var frameManager = scene.plugins.get('rexFrameManager').add(scene, {\nkey: '',\nwidth: 4096,\nheight: 4096,\ncellWidth: 64,\ncellHeight: 64,\ncellPadding: 0,\ncolumns: undefined,\nrows: undefined,\nfillColor: undefined,\nuseDynamicTexture: false,\n});\n
  • key : Texture key in texture manager
  • width, height : Size of canvas.
    • Calculate width/height by columns/rows and cellWidth/cellHeight, if columns, rows parameters are given.
  • columns, rows :
    • undefined : Calculate columns/rows by width/height and cellWidth/cellHeight.
  • cellWidth, cellHeight : Maximum frame size.
  • cellPadding : Extra space around frame. Default value is 0.
    • Total cell width will be cellWidth + (cellPadding * 2)
    • Total cell height will be cellHeight + (cellPadding * 2)
  • fillColor : Fill an initial color, in css color string (for canvas-texture), or number (for dynamic-texture)
    • undefined : Don't fill color.
  • useDynamicTexture
    • false : Use canvas-texture. Default behavior.
    • true : Use dynamic-texture.

or

var frameManager = scene.plugins.get('rexFrameManager').add(scene, key, width, height, cellWidth, cellHeight, fillColor, useDynamicTexture);\n

Steps of generating bitmapfont :

  1. Add frames :
    frameManager.paste(frameName, gameObject);\n
  2. Update texture
    frameManager.updateTexture();\n
  3. Export frame data to bitmapfont
    frameManager.addToBitmapFont();\n
"},{"location":"framemanager/#add-frame","title":"Add frame","text":""},{"location":"framemanager/#from-game-object","title":"From game object","text":"

After rendering content on text, bbcode text, canvas

frameManager.paste(frameName, gameObject);\n
  • frameName : Frame name.
  • gameObject :
    • Canvas-texture mode :
      • Game objects which has canvas, for example, text, bbcode text, or canvas.
    • Dynamic-texture mode :
      • Any render-able game object except :
        • Graphics can't paste directly, because that Graphics game object does not have size.
          • Draw Graphics to RenderTexture, then paste this RenderTexture to frameMamager.
"},{"location":"framemanager/#custom-drawing","title":"Custom drawing","text":"

frameManager.draw(frameName, callback, scope)\n
- frameName : Frame name. - callback : - Canvas-texture mode :
function(canvas, context, frameSize) {\n// The maximum frame size\nvar cellWidth = frameSize.width;\nvar cellHeight = frameSize.height;\n\n// Draw content in area of (0, 0) - (cellWidth, cellHeight)\n\n// Update frame size\n// frameSize.width = ...\n// frameSize.height = ...\n}\n
- Dynamic-texture mode :
function(texture, frameSize) {\n// The maximum frame size\nvar cellWidth = frameSize.width;\nvar cellHeight = frameSize.height;\n\n// Draw content in area of (0, 0) - (cellWidth, cellHeight)\n\n// Update frame size\n// frameSize.width = ...\n// frameSize.height = ...\n}\n

"},{"location":"framemanager/#empty-frame","title":"Empty frame","text":"
frameManager.addEmptyFrame(frameName);\n// frameManager.addEmptyFrame(frameName, width, height);\n
  • frameName : Frame name.
  • width : Frame width, default value is cellWidth
  • height : Frame height, default value is cellHeight
"},{"location":"framemanager/#update-texture","title":"Update texture","text":"

Update texture after adding frames, for Canvas-texture mode.

frameManager.updateTexture();\n

Do nothing in Dynamic-texture mode.

"},{"location":"framemanager/#remove-frame","title":"Remove frame","text":"
  • Remove a frame
    frameManager.remove(frameName);\n
    • frameName : Frame name.
  • Remove all frames
    frameManager.clear();\n

Remove frame data but won't clear texture image.

"},{"location":"framemanager/#export-to-bitmapfont","title":"Export to bitmapfont","text":"
frameManager.addToBitmapFont();\n
"},{"location":"framemanager/#destroy-instance","title":"Destroy instance","text":"
frameManager.destroy();\n
"},{"location":"fsm/","title":"FSM","text":""},{"location":"fsm/#introduction","title":"Introduction","text":"

Finite state machine.

  • Author: Rex
  • Object
"},{"location":"fsm/#usage","title":"Usage","text":"

Sample code

"},{"location":"fsm/#install-plugin","title":"Install plugin","text":""},{"location":"fsm/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfsmplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfsmplugin.min.js', true);\n
  • Add FSM object
    var states = scene.plugins.get('rexfsmplugin').add(config);\n
"},{"location":"fsm/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FSMPlugin from 'phaser3-rex-plugins/plugins/fsm-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFSM',\nplugin: FSMPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add FSM object
    var states = scene.plugins.get('rexFSM').add(config);\n
"},{"location":"fsm/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import FSM from 'phaser3-rex-plugins/plugins/fsm.js';\n
  • Add FSM object
    var states = new FSM(config);\n
"},{"location":"fsm/#create-instance","title":"Create instance","text":""},{"location":"fsm/#create-by-config","title":"Create by config","text":"
var states = scene.plugins.get('rexFSM').add({\nstart: 'A',   // default: undefined\nstates: {\nA: {\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},                 // this: this fsm instance\nexit: function() {},                  // this: this fsm instance\nupdate: function(time, delta) {},     // this: this fsm instance\npreupdate: function(time, delta) {},  // this: this fsm instance\npostupdate: function(time, delta) {}, // this: this fsm instance\n},\n// ...\n},\ninit: function() {},   // this: this fsm instance\nextend: {\ni: 0,        // Add member `i` into this fsm instance\nname: 'abc'\n// ...\n},\nenable: true,\nscene: undefined,\neventEmitter: undefined\n});\n
  • start: Initial state.
  • states: Define states.
    • stateName
      • next: String of next state, or a callback to get next state.
      • enter: Callback when enter state.
        function() {\n// this : this fsm instance\n}\n
      • exit: Callback when exit state. javascript function() { // this : this fsm instance }
      • update, preupdate, postupdate : Callback invoked by scene's 'update', 'preupdate', 'postupdate' events.
        function(time, delta) {\n// this : this fsm instance\n}\n
  • init: Initial callback when creating instance.
    function() {\n// this : this fsm instance\n}\n
  • extend: Inject key-value pairs into this fsm instance.
  • enable: Set false to block any state changing.
  • scene : Scene object for startUpdate, startPreUpdate, startPostUpdate method. Optional.
  • eventEmitter
    • undefined : Create a private event emitter, default value.
    • false : Don't add any event emitter, i.e. no event will be fired.
    • Event emitter object : Fire event through this event emitter.
"},{"location":"fsm/#inheritance","title":"Inheritance","text":"
  1. Create new class
    class State extends FSM {\nconstructor() {\nsuper();\n}\n\nnext_A() { return 'B' }\n\nenter_A() { }\n\nexit_A() { }\n\nupdate_A(time, delta) { }\npreupdate_A(time, delta) { }\npostupdate_A(time, delta) { }\n}\n
    Members: - next_ + stateName : Callback to get next state. - enter_ + stateName : Callback when enter state. - exit_ + stateName : Callback when exit state. - update_ + stateName, preupdate_ + stateName, postupdate_ + stateName : Callback invoked by scene's 'update', 'preupdate', 'postupdate' events.
  2. Create instance
    var states = new State();\n
"},{"location":"fsm/#read-state","title":"Read state","text":"
  • Current state
    var curState = states.state;\n
  • Previous state
    var preState = states.prevState;\n
"},{"location":"fsm/#start-at-state","title":"Start at state","text":"
states.start(newState);\n

Note

Set new state without triggering any state-changing callbacks or events.

"},{"location":"fsm/#next-state","title":"Next state","text":"
graph TB\n\nnext[\"states.next()\"] --> next_A[\"states.next_A()<br>return 'B'\"]\n\nnext_A --> eventStateChange[\"states.emit('statechange', states)<br>states.prevState -> states.state\"]\n\nsubgraph State changing\n\neventStateChange --> exit_A[\"states.exit_A()\"]\nexit_A --> eventExitA[\"states.emit('exit_A', states)\"]\n\neventExitA --> enter_B[\"states.enter_B()\"]\nenter_B --> eventEnterB[\"states.emit('enter_B', states)\"]\n\nsubgraph Exit\nexit_A\neventExitA\nend\n\nsubgraph Enter\nenter_B\neventEnterB\nend\n\nend\n\ngoto[\"states.goto('B')\"] --> eventStateChange\n\nsubgraph Request\n\nsubgraph Next\nnext\nnext_A\nend\n\nsubgraph Goto\ngoto\nend\n\nend
"},{"location":"fsm/#request","title":"Request","text":"
  • Get next state by callback
    states.next();    // nextState = states.next_A()    \n
  • Goto state
    states.goto(nextState);\n// states.state = nextState;\n
"},{"location":"fsm/#state-changing","title":"State-changing","text":"

These callbacks or events will be triggered if state is changing.

For example, state is changing from 'A' to 'B'.

  1. event statechange
    states.on('statechange', function(states) {\nconsole.log( states.prevState + '->' + states.state );\n});\n
  2. callback states.exit_A
  3. event exit_A
    states.on('exit_A', function(states) {\n/*...*/\n});\n
  4. callback states.enter_B
  5. event enter_B
    states.on('enter_B', function(states) {\n/*...*/\n});\n
"},{"location":"fsm/#enable","title":"Enable","text":"
states.setEnable();\n// states.setEnable(false); // disable\n

or

states.toggleEnable();\n

states.next() and states.goto() will be ignored if disabled.

"},{"location":"fsm/#update","title":"Update","text":"
  • Start
    states.startUpdate();\nstates.startPreUpdate();\nstates.startPostUpdate();\n// Assume that `scene` is assigned in config of constructor\n
    or
    states.startUpdate(scene);\nstates.startPreUpdate(scene);\nstates.startPostUpdate(scene);\n
    • scene : Scene object
  • Stop
    states.stopUpdate();\nstates.stopPreUpdate();\nstates.stopPostUpdate();\n
"},{"location":"fsm/#add-new-state","title":"Add new state","text":"

states.addState(name, {\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {},\nupdate: function(time, delta) {},\npreupdate: function(time, delta) {},\npostupdate: function(time, delta) {},\n})\n
states.addState({\nname: 'A',\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {},\nupdate: function(time, delta) {},\npreupdate: function(time, delta) {},\npostupdate: function(time, delta) {},\n})\n

or

states.addStates({\n'A' : {\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {},\nupdate: function(time, delta) {},\npreupdate: function(time, delta) {},\npostupdate: function(time, delta) {},\n},\n// ...\n})\n
states.addStates([\n{\nname: 'A',\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {},\nupdate: function(time, delta) {},\npreupdate: function(time, delta) {},\npostupdate: function(time, delta) {},\n},\n// ...\n]);\n

"},{"location":"fullscreen/","title":"Full screen","text":""},{"location":"fullscreen/#introduction","title":"Introduction","text":"

Enable or disable full screen mode, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"fullscreen/#usage","title":"Usage","text":""},{"location":"fullscreen/#enabledisable","title":"Enable/disable","text":"

Under any input event (touch or keyboard)

gameObject.setInteractive().on('pointerdown', function() {\nif (scene.scale.isFullscreen) {\nscene.scale.stopFullscreen();\n// On stop fulll screen\n} else {\nscene.scale.startFullscreen();\n// On start fulll screen\n}\n});\n

Fire one of these events

  • 'fullscreenunsupported' : Tried to enter fullscreen mode, but it is unsupported by the browser.
  • 'enterfullscreen' : Entered fullscreen mode successfully.
  • 'fullscreenfailed' : Tried to enter fullscreen mode but failed.
"},{"location":"fullscreen/#toggle","title":"Toggle","text":"

Under any input event (touch or keyboard)

gameObject.setInteractive().on('pointerdown', function() {\nscene.scale.toggleFullscreen();\nif (scene.scale.isFullscreen) {\n// On start fulll screen\n} else {\n// On stop fulll screen\n}\n});\n
  • Fire 'fullscreenunsupported' or 'enterfullscreen' event.
"},{"location":"fullscreen/#state","title":"State","text":"
  • Is in full screen mode
    var isFullScreen = scene.scale.isFullscreen;\n
  • Support full screen
    var supported = Phaser.Device.Fullscreen.available;\n
"},{"location":"fullscreen/#events","title":"Events","text":"
  • Full screen mode unsupported
    scene.scale.on('fullscreenunsupported', function() {});\n
  • Enter full screen mode
    scene.scale.on('enterfullscreen', function() {});\n
"},{"location":"fullscreen/#with-dom-game-object","title":"With DOM game object","text":"

Set gameConfig.fullscreenTarget to parent id.

var config = {\nparent: parentDivID,\nfullscreenTarget: parentDivID\n};\n\nvar game = new Phaser.Game(config);\n
"},{"location":"fuzzy/","title":"Fuzzy","text":""},{"location":"fuzzy/#introduction","title":"Introduction","text":"

A wrap of fuzzy logic (MIT license).

  • Author of wrap : Rex , Core API : Michael Herzog
  • Member of scene, or game object
"},{"location":"fuzzy/#live-demos","title":"Live demos","text":"
  • Fuzzy
"},{"location":"fuzzy/#usage","title":"Usage","text":"

Sample code

"},{"location":"fuzzy/#install-plugin","title":"Install plugin","text":""},{"location":"fuzzy/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfuzzyplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfuzzyplugin.min.js', true);\n
  • Add fuzzy module object
    var fuzzyModule = scene.plugins.get('rexfuzzyplugin').add(config);\n
"},{"location":"fuzzy/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GashaponPlugin from 'phaser3-rex-plugins/plugins/fuzzy-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGashapon',\nplugin: GashaponPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add fuzzy module object
    var fuzzyModule = scene.plugins.get('rexFuzzy').add(config);\n
"},{"location":"fuzzy/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import BuildFuzzyModule from 'phaser3-rex-plugins/plugins/fuzzy.js';\n
  • Add fuzzy module object
    var fuzzyModule = BuildFuzzyModule(config);\n
"},{"location":"fuzzy/#create-instance","title":"Create instance","text":"
var fuzzyModule = scene.plugins.get('rexFuzzy').add(`\n// Declare fuzzy sets\nFuzzySetName : left, middle, right, setType\nFuzzySetName : left, middle, right\nFuzzySetName : left, right\n\n// Declare rules\nFuzzySetNameA => FuzzySetNameT\nFuzzySetNameA and FuzzySetNameB => FuzzySetNameT\nFuzzySetNameA or FuzzySetNameB => FuzzySetNameT\nFuzzySetNameA or (FuzzySetNameA and FuzzySetNameB) => FuzzySetNameT\n\n// More comment lines...\n`);\n
  • config can be a multiple lines string, or a plain object
    • A multiple lines string contains
      • FuzzySetName : left, middle, right, setType : A line with ':', declare a fuzzy set.
        • FuzzySetName : Fuzzy set name in one of these format
          • Variable name with postfix '+', or '-'. For example, HP-, HP, HP+, HP--, HP++, the variable name is HP.
          • variableName.setName. For example, DIST.near, DIST.middle, DIST.far, the variable name is DIST.
            • Variable name and set name are composed of number(0-9) or English characters (A-Za-z).
        • left, middle, right : Left, middle, right point of fuzzy set, in numbers.
          • left, right : Two numbers for left and right point, middle point is the average of (left + right).
        • setType :
          • Can be one of these string, or none.
            • Left part : leftShoulder, leftSCurve.
              • Default value is leftShoulder for first fuzzy set of a variable.
            • Right part : rightShoulder, rightSCurve.
              • Default value is rightShoulder for last fuzzy set of a variable.
            • Middle parts : triangular, singleton, normal.
              • Default value is triangular for other fuzzy sets of a variable.
      • FuzzySetNameA and FuzzySetNameB => FuzzySetNameT : A line with '=>', declare a fuzzy rule.
      • // ... : Comment lines
    • A plain object
      {\nvariables: {\nVariableName: [\n{\nname: leftSetName, setType: undefined,\nparameters: [left, middle, right]\n},\n{\nname: middleSetName, setType: undefined,\nparameters: [left, middle, right]\n},\n{\nname: rightSetName, setType: undefined,\nparameters: [left, middle, right]\n},\n],\n// ....\n},\n\nrules: [\n'FuzzySetNameA => FuzzySetNameT',\n'FuzzySetNameA and FuzzySetNameB => FuzzySetNameT',\n'FuzzySetNameA or FuzzySetNameB => FuzzySetNameT',\n// ...\n]\n\n}\n
"},{"location":"fuzzy/#set-input","title":"Set input","text":"
fuzzyModule.fuzzify(variableName, value);\n
  • variableName : An antecedent variable name string.
  • value : A number.

or

fuzzyModule.fuzzify({\nvarName: value,\n});\n
"},{"location":"fuzzy/#get-result","title":"Get result","text":"
var result = fuzzyModule.defuzzify(variableName);\n
  • variableName : A consequence variable name string.

or

var result = fuzzyModule.defuzzify([varName0, varName1, ...]);\n
  • result : {varName0: value0, varName1, value1, ...}

or

var result = fuzzyModule.defuzzify();\n
  • result : {varName0: value0, varName1, value1, ...}
    • Grab variable names from all consequence of rules.
"},{"location":"game/","title":"Game","text":""},{"location":"game/#boot","title":"Boot","text":"
var config = {\ntype: Phaser.AUTO,\nparent: null,\nwidth: 1024,\nheight: 768,\nscale: {\nmode: Phaser.Scale.FIT,\nautoCenter: Phaser.Scale.CENTER_BOTH\n},\n\nscene: null\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"game/#configuration","title":"Configuration","text":"

Reference

{\ntype: Phaser.AUTO,\nparent: 'phaser-example',\nwidth: 800,\nheight: 600,\nscale: {\nmode: Phaser.Scale.FIT,\nautoCenter: Phaser.Scale.CENTER_BOTH\n},\ndom: {\ncreateContainer: false,\n},\nscene: null,\nbackgroundColor: 0x333333\n}\n

or

{\ntype: Phaser.AUTO,\nparent: null,\nwidth: 800,\nheight: 600,\n\nscale: {\nmode: Phaser.Scale.NONE,\nautoCenter: Phaser.Scale.NO_CENTER,\nresizeInterval: 500,\n// width:\n// height:\n// zoom:\n// parent:\nexpandParent: true.\n// min: {width: 0, height: 0},\n// max: {width: 0, height: 0},\n// snap: {width: 0, height: 0},\n// autoRound: false,\nfullscreenTarget: null,\n},\n\nautoRound: false,\ncanvas: null,\ncanvasStyle: null,\n\nscene: null,\n\ncallbacks: {\npreBoot: NOOP,\npostBoot: NOOP\n},\n\nseed: [ (Date.now() * Math.random()).toString() ],\n\ntitle: '',\nurl: 'https://phaser.io',\nversion: '',\n\nautoFocus: true,\ninput: {\nkeyboard: {\ntarget: window\n},\nmouse: {\ntarget: null,\ncapture: true\n},\nactivePointers: 1,\ntouch: {\ntarget: null,\ncapture: true\n},\nsmoothFactor: 0,\ngamepad: false,\nwindowEvents: true,\n},\ndisableContextMenu: false,\n\nbackgroundColor: 0,\n\nrender: {\nantialias: true,\nantialiasGL: true,\ndesynchronized: false,\npixelArt: false,\nroundPixels: false,\ntransparent: false,\nclearBeforeRender: true,\npreserveDrawingBuffer: false,\npremultipliedAlpha: true,\nfailIfMajorPerformanceCaveat: false,\npowerPreference: 'default', // 'high-performance', 'low-power' or 'default'\nbatchSize: 4096,\nmaxLights: 10,\nmaxTextures: -1,\nmipmapFilter: 'LINEAR', // 'NEAREST', 'LINEAR', 'NEAREST_MIPMAP_NEAREST', 'LINEAR_MIPMAP_NEAREST', 'NEAREST_MIPMAP_LINEAR', 'LINEAR_MIPMAP_LINEAR'\nautoMobilePipeline: true,\ndefaultPipeline: 'MultiPipeline',\npipeline:[]\n},\ndisablePreFX: false,\ndisablePostFX: false,\n\nphysics: {\ndefault: false,  // 'arcade', or 'matter'\narcade: {...},   // See arcade-world#Configuration\nmatter: {...},   // See matterjs-world#Configuration\n},\n\nloader:{\nbaseURL: '',\npath: '',\nmaxParallelDownloads: 4,\ncrossOrigin: undefined,\nresponseType: '',\nasync: true,\nuser: '',\npassword: '',\ntimeout: 0,\nmaxRetries: 2,\nwithCredentials: false,\nimageLoadType: 'XHR',    // 'HTMLImageElement' \nlocalScheme: [ 'file://', 'capacitor://' ]\n},\n\nimages: {\ndefault: 'data:image/png;base64....',\nmissing: 'data:image/png;base64....',\nwhite: 'data:image/png;base64....',\n},\n\naudio: {\ndisableWebAudio: false,\ncontext:\nnoAudio: false,\n},\n\ndom: {\ncreateContainer: false,\nbehindCanvas: false,\npointerEvents: 'none'\n},\n\nplugins: {\nglobal: [\n//{key, plugin, start}\n],\nscene: [\n// ...\n]\n},\n\npipeline: { key:PipelineClass },\n\nfps: {\nmin: 10,\ntarget: 60,\nlimit: 0,\nforceSetTimeOut: false,\ndeltaHistory: 10,\npanicMax: 120,\nsmoothStep: true,\n},\n\nbanner: {\nhidePhaser: false,\ntext: '#ffffff',\nbackground: [\n'#ff0000',\n'#ffff00',\n'#00ff00',\n'#00ffff',\n'#000000'\n]\n},\n// banner: false,\n\nstableSort: -1\n}\n
"},{"location":"game/#destroy","title":"Destroy","text":"
game.destroy();\n// game.destroy(removeCanvas, noReturn);\n
  • removeCanvas : Set to true if you would like the parent canvas element removed from the DOM, or false to leave it in place.
  • noReturn : If true all the core Phaser plugins are destroyed. You cannot create another instance of Phaser on the same web page if you do this.
"},{"location":"game/#global-members","title":"Global members","text":""},{"location":"game/#scene-manager","title":"Scene manager","text":"

Global scene manager in game.scene, or scene.scene in each scene.

"},{"location":"game/#global-data","title":"Global data","text":"

Instance of data manager in game.registry, or scene.registry in each scene.

  • Get
    var value = scene.registry.get(key);\n// var value = game.registry.get(key);\n
  • Set
    scene.registry.set(key, value);\n// game.registry.set(key, value);\n
  • Event
    • Set data event
      scene.registry.events.on('setdata', function(parent, key, value){ /* ... */ });\n// game.registry.events.on('setdata', function(parent, key, value){ /* ... */ })\n
    • Change data event
      scene.registry.events.on('changedata', function(parent, key, value, previousValue){ /* ... */ });\n// game.registry.events.on('changedata', function(parent, key, value, previousValue){ /* ... */ })\n
      scene.registry.events.on('changedata-' + key, function(parent, value, previousValue){ /* ... */ });\n// game.registry.events.on('changedata-' + key, function(parent, value, previousValue){ /* ... */ });\n
"},{"location":"game/#game-time","title":"Game time","text":"
  • The time that the current game step started at.
    var time = game.getTime();\n// var time = scene.game.getTime();\n
  • The current game frame.
    var frameCount = game.getFrame();\n// var frameCount = scene.game.getFrame();\n
  • The delta time, since the last game step. This is a clamped and smoothed average value.
    var delta = game.loop.delta;\n// var delta = scene.game.loop.delta;\n
"},{"location":"game/#game-config","title":"Game config","text":"
var config = game.config;\n// var config = scene.game.config;\n
"},{"location":"game/#window-size","title":"Window size","text":"
  • Width
    var width = game.config.width;\n// var width = scene.game.config.width;\n
  • Height
    var height = game.config.height;\n// var height = scene.game.config.height;\n
"},{"location":"game/#pause-resume","title":"Pause / Resume","text":"
  • Pause the entire game and emit a PAUSE event.
    game.pause();\n
  • Resume the entire game and emit a RESUME event.
    game.resume();\n
  • Get pause duration
    var time = game.pauseDuration;\n
  • Is paused
    var isPaused = game.isPaused;\n
"},{"location":"game/#events","title":"Events","text":"
  • Pause(window is invisible)/Resume(window is visible)
    game.events.on('pause', function() {});\n
    game.events.on('resume', function() {});\n
  • Destroy event, triggered by game.destroy()
    game.events.on('destroy', function() {})\n
  • On window focused/blurred
    game.events.on('focus', function() {})\n
    game.events.on('blur', function(){ })\n
"},{"location":"gameobject/","title":"Game object","text":""},{"location":"gameobject/#introduction","title":"Introduction","text":"

Base class of all game object in phaser.

  • Author: Richard Davey
"},{"location":"gameobject/#usage","title":"Usage","text":""},{"location":"gameobject/#destroy","title":"Destroy","text":"
  • Destroy game object
    gameObject.destroy();\n
  • Game object will be destroyed automatically when scene destroyed, if it is in display list, or update list.
  • Event
    gameObject.once('destroy', function(gameObject, fromScene) {\n\n}, scope);\n
    • fromScene : true if game object is destroyed during scene is shutdown. When scene is shutdown, all game objects will be destroyed.
"},{"location":"gameobject/#position","title":"Position","text":"
  • Get
    var x = gameObject.x;\nvar y = gameObject.y;\n
  • Set
    gameObject.x = 0;\ngameObject.y = 0;\ngameObject.setPosition(x,y);\ngameObject.setX(x);\ngameObject.setY(y);\n
    • Set random
      gameObject.setRandomPosition(x, y, width, height);\n// gameObject.setRandomPosition(); // x=0, y=0, width=game.width, height=game.height\n
"},{"location":"gameobject/#local-point","title":"Local point","text":"

Transfer world point to local point

var point = gameObject.getLocalPoint(x, y);  // point : {x, y}\n// var out = gameObject.getLocalPoint(x, y, out);\n
or
var out = gameObject.getLocalPoint(x, y, out, camera);\n

"},{"location":"gameobject/#angle","title":"Angle","text":"
  • Get
    var angle = gameObject.angle;\nvar radians = gameObject.rotation;  // angle in radians\n
  • Set
    gameObject.angle = degrees;\ngameObject.rotation = radians;\ngameObject.setAngle(degrees);\ngameObject.setRotation(radians);\n
"},{"location":"gameobject/#visible","title":"Visible","text":"
  • Get
    var visible = gameObject.visible; // visible: true/false\n
  • Set
    gameObject.visible = visible;\ngameObject.setVisible(visible);\n
"},{"location":"gameobject/#alpha","title":"Alpha","text":"
  • Get
    var alpha = gameObject.alpha;  // 0~1\n
  • Set
    gameObject.setAlpha(alpha);\n// gameObject.alpha = alpha;\n
    or
    gameObject.setAlpha(topLeft, topRight, bottomLeft, bottomRight);\n// gameObject.alphaTopLeft = alpha;\n// gameObject.alphaTopRight = alpha;\n// gameObject.alphaBottomLeft = alpha;\n// gameObject.alphaBottomRight = alpha;\n
  • Clear (set to 1)
    gameObject.clearAlpha();\n
"},{"location":"gameobject/#flipx-flipy","title":"FlipX, FlipY","text":"
  • Get
    var flip = gameObject.flipX;  // flip: true/false\nvar flip = gameObject.flipY;  // flip: true/false\n
  • Set
    gameObject.flipX = flip;\ngameObject.flipY = flip;\ngameObject.setFlipX(flip);\ngameObject.setFlipY(flip);\ngameObject.setFlip(flipX, flipY);\ngameObject.toggleFlipX();\ngameObject.toggleFlipY();\ngameObject.resetFlip();  // equal to gameObject.setFlip(false, false);\n
"},{"location":"gameobject/#order-of-rendering","title":"Order of rendering","text":""},{"location":"gameobject/#depth-z-index","title":"Depth (z-index)","text":"

The depth starts from zero (the default value) and increases from that point. A game object with a higher depth value will always render in front of one with a lower value.

  • Get
    var depth = gameObject.depth;\n
  • Set
    gameObject.depth = value;\ngameObject.setDepth(value);\n
"},{"location":"gameobject/#display-list","title":"Display list","text":"
  • Get displayList
    var displayList = gameObject.getDisplayList();\n
  • Move the game Object to the top of the display list
    gameObject.setToTop()\n
    var displayList = gameObject.getDisplayList();\ndisplayList.bringToTop(child);\n
  • Move the game Object to the bottom of the display list
    gameObject.setToBack()\n
    var displayList = gameObject.getDisplayList();\ndisplayList.sendToBack(child);\n
  • Move the Game Object to appear above a given Game Object
    gameObject.setAbove(givenGameObject)\n
    var displayList = gameObject.getDisplayList();\ndisplayList.moveAbove(gameObject, givenGameObject);\n
  • Move the Game Object to appear below a given Game Object
    gameObject.setBelow(givenGameObject)\n
    var displayList = gameObject.getDisplayList();\ndisplayList.moveBelow(gameObject, givenGameObject);\n
  • Move the game object by index
    var displayList = gameObject.getDisplayList();\ndisplayList.moveTo(gameObject, index);\n
  • Swap two game objects
    var displayList = gameObject.getDisplayList();\ndisplayList.swap(gameObject, givenGameObject);\n
  • Move up or down
    var displayList = gameObject.getDisplayList();\ndisplayList.moveUp(gameObject);\ndisplayList.moveDown(gameObject);\n
"},{"location":"gameobject/#layer-game-object","title":"Layer game object","text":"

Place game object into Layer game object

"},{"location":"gameobject/#scroll-factor","title":"Scroll factor","text":"
  • Get
    var scrollFactorX = gameObject.scrollFactorX;\nvar scrollFactorY = gameObject.scrollFactorY;\n
  • Set
    gameObject.setScrollFactor(scrollFactor);\ngameObject.setScrollFactor(scrollFactorX, scrollFactorY);\n

Scroll factor: 0~1

  • 0= fixed to camera
  • 0.25= quarter the speed of the camera
  • 0.5= half the speed of the camera
"},{"location":"gameobject/#bounds","title":"Bounds","text":"
var output = gameObject.getTopLeft(output);     // output: {x, y}\nvar output = gameObject.getTopCenter(output);     // output: {x, y}\nvar output = gameObject.getTopRight(output);    // output: {x, y}\nvar output = gameObject.getLeftCenter(output);    // output: {x, y}\nvar output = gameObject.getRightCenter(output);    // output: {x, y}\nvar output = gameObject.getBottomLeft(output);  // output: {x, y}\nvar output = gameObject.getBottomCenter(output);     // output: {x, y}\nvar output = gameObject.getBottomRight(output); // output: {x, y}\nvar output = gameObject.getCenter(output);      // output: {x, y}\nvar output = gameObject.getBounds(output);      // output: {x, y, width, height}\n
"},{"location":"gameobject/#origin","title":"Origin","text":"
  • Get
    var originX = gameObject.originX;\nvar originY = gameObject.originY;\n
  • Set
    gameObject.setOrigin(x, y);\n// gameObject.setOrigin(x); // y = x\n
    • Set to top-left
      gameObject.setOrigin(0);\n
    • Set to center
      gameObject.setOrigin(0.5);\n
    • Set to bottom-right
      gameObject.setOrigin(1);\n
"},{"location":"gameobject/#tint","title":"Tint","text":"
  • Get
    var color = gameObject.tintTopLeft;     // color: 0xRRGGBB\nvar color = gameObject.tintTopRight;\nvar color = gameObject.tintBottomLeft;\nvar color = gameObject.tintBottomRight;\nvar isTinted = gameObject.isTinted;\n
  • Set
    gameObject.tint = color;\ngameObject.setTint(color);  // multiply color value\ngameObject.setTint(colorTopLeft, colorTopRight, colorBottomLeft, colorBottomRight);\ngameObject.setTintFill(color);  // replace color value\ngameObject.setTintFill(colorTopLeft, colorTopRight, colorBottomLeft, colorBottomRight);    gameObject.clearTint();     // equal to `gameObject.setTint(0xffffff)`\n

Note

gameObject.tint is a write-only property

"},{"location":"gameobject/#blend-mode","title":"Blend mode","text":"
  • Get
    var blendMode = gameObject.blendMode;\n
  • Set
    gameObject.blendMode = blendMode;\ngameObject.setBlendMode(blendMode);\n
    • blendMode : Blend mode
"},{"location":"gameobject/#mask","title":"Mask","text":"

See Mask.

"},{"location":"gameobject/#built-in-shader-effects","title":"Built-in shader effects","text":"

See built-in shader effects

"},{"location":"gameobject/#post-fx-pipeline","title":"Post-fx pipeline","text":""},{"location":"gameobject/#register-post-fx-pipeline","title":"Register post-fx pipeline","text":"
  • Register post-fx pipeline in game config
    import PostFxClass from 'path';\nvar config = {\n// ...\npipeline: [PostFxClass]\n// ...\n};\nvar game = new Phaser.Game(config);\n

Some post-fx pipelines:

  • Barrel: Barrel post processing filter.
  • Color replace: Replace color post processing filter.
  • Cross-stitching: Cross-stitching post processing filter.
  • Dissolve: Dissolve transition post processing filter.
  • Fish eye: Fish-eye post processing filter.
  • Glow-filter: Glow post processing filter.
  • Glow-filter: Glow post processing filter, ported from pixi.
  • Gray-scale: Gray scale post processing filter.
  • Hsl-adjust: Adjust color in HSL domain, post processing filter.
  • Horri-fi: 6-in-1 post processing filter.
  • Inverse: Inverse color post processing filter.
  • Kawase-blur: Kawase-blur post processing filter.
  • Pixelation: Pixelation post processing filter.
  • Toonify: Draw outlines and quantize color in HSV domain, post processing filter.
  • Shockwave: Shockwave post processing filter.
  • Split: Split image into 4 parts.
  • Swirl: Swirl post processing filter.
  • Warp: Warp post processing filter.
"},{"location":"gameobject/#add-post-fx-pipeline","title":"Add post-fx pipeline","text":"
gameObject.setPostPipeline(PostFxClass);\n
  • PostFxClass : Class of post-fx pipeline.
"},{"location":"gameobject/#remove-post-fx-pipeline","title":"Remove post-fx pipeline","text":"
  • Remove a post-fx pipeline
    gameObject.removePostPipeline(PostFxClass);\n
  • Remove all post-fx pipelines
    gameObject.resetPipeline(true);\n
    or
    gameObject.postPipelines = [];\ngameObject.hasPostPipeline = false;\n
"},{"location":"gameobject/#get-post-fx-pipeline","title":"Get post-fx pipeline","text":"
var pipelineInstance = gameObject.getPostPipeline(PostFxClass);\n
"},{"location":"gameobject/#size","title":"Size","text":"
  • Native (un-scaled) size
    • Get
      var width = gameObject.width;\nvar height = gameObject.height;\n
    • Set
      gameObject.setSize(width, height);\n
      or
      gameObject.width = width;\ngameObject.height = height;\n
  • Display size
    • Get
      var displayWidth = gameObject.displayWidth;\nvar displayHeight = gameObject.displayHeight;\n
    • Set
      gameObject.setDisplaySize(displayWidth, displayHeight);\n
      or
      gameObject.displayWidth = displayWidth;\ngameObject.displayHeight = displayHeight;\n
  • Scale
    • Get
      var scaleX = gameObject.scaleX;\nvar scaleY = gameObject.scaleY;\n
      or
      var scale = gameObject.scale;  // Return (scaleX + scaleY)/2\n
    • Set
      gameObject.setScale(scaleX, scaleY);\n
      or
      gameObject.scaleX = scaleX;\ngameObject.scaleY = scaleY;\n
      or
      gameObject.scale = scale;  // Set scaleX, scaleY to scale\n
"},{"location":"gameobject/#click","title":"Click","text":"
gameObject.setInteractive().on('pointerdown', function(pointer, localX, localY, event){\n// ...\n});\n

See touch event

"},{"location":"gameobject/#state","title":"State","text":"
  • Get
    var state = gameObject.state;\n
  • Set
    gameObject.setState(state);\n
"},{"location":"gameobject/#data","title":"Data","text":"
  • Get
    var value = gameObject.getData(key);\nvar values = gameObject.getData(keys); // keys: an array of keys\nvar value = gameObject.data.values[key];\n
  • Set
    gameObject.setData(key, value);\ngameObject.incData(key, value);    gameObject.setData(obj); // obj: {key0:value0, key1:value1, ...}\ngameObject.data.values[key] = value;\ngameObject.data.values[key] += inc;\n
    or
    gameObject.toggleData(key);\n
  • Enable
    gameObject.setDataEnabled();\n
  • Events :
    • Set data evant
      gameObject.on('setdata', function(gameObject, key, value){ /* ... */ });\n
    • Change data event
      gameObject.on('changedata', function(gameObject, key, value, previousValue){ /* ... */ });\n
      gameObject.on('changedata-' + key, function(gameObject, value, previousValue){ /* ... */ });\n

See data manager

Note

Ensure data manager is created before binding any data-changed events.

"},{"location":"gameobject/#texture","title":"Texture","text":"
  • Set texture via key string
    gameObject.setTexture(key);\n// gameObject.setTexture(key, frame);\n// gameObject.setTexture(key, frame, updateSize, updateOrigin);\n
  • Set texture via texture object
    gameObject.setTexture(texture);\n// gameObject.setTexture(texture, frame);\n
    • texture : Texture object, or canvas texture object
  • Set frame
    gameObject.setFrame(frame);\n// gameObject.setFrame(frame, updateSize, updateOrigin);\n
    • frame :\u3000The name or index of the frame within the Texture.
    • updateSize : Should this call adjust the size of the Game Object?
    • updateOrigin : Should this call adjust the origin of the Game Object?
  • Set frame by frame object
    gameObject.setFrame(frameObject);\n// gameObject.setFrame(frameObject, updateSize, updateOrigin);\n
  • Applies a crop to a texture
    gameObject.setCrop(x, y, width, height);\n
    The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left.
    • Reset crop
      gameObject.setCrop();\n// gameObject.isCropped = false;\n
  • Get texture, frame.
    var texture = gameObject.texture;\nvar frame = gameObject.frame;\n
  • Get texture key, frame name.
    var textureKey = gameObject.texture.key;\nvar frameName = gameObject.frame.name;\n
"},{"location":"gameobject/#name","title":"Name","text":"
  • Get
    var name = gameObject.name;\n
  • Set
    gameObject.setName(name);\ngameObject.name = name;\n
"},{"location":"gameobject/#will-render","title":"Will render","text":"
  • Test render flag and camera filter.
    var willRennder = gameObject.willRender(camera);\n
  • Test render flag only
    var willRender = (gameObject.renderFlags === Phaser.GameObjects.GameObject.RENDER_MASK);\n
    • Phaser.GameObjects.GameObject.RENDER_MASK : 15 (Visible, Alpha, Transform and Texture)
"},{"location":"gameobject/#add-to-scenecontainer","title":"Add to scene/container","text":""},{"location":"gameobject/#add","title":"Add","text":"

Trigger 'addedtoscene' event, which invoke gameObject.addedToScene()

  • Register 'addedtoscene' event
    gameObject.on('addedtoscene', function(gameObject, scene){});\n
  • Or, override addedToScene method
    class MyClass extends BaseClass {\n// ...\naddedtoscene() {\nsuper.addedtoscene();\n// ...\n}\n}\n
"},{"location":"gameobject/#remove","title":"Remove","text":"

Trigger 'removedfromscene' event, which invoke gameObject.removedFromScene()

  • Register 'removedfromscene' event
    gameObject.on('removedfromscene', function(gameObject, scene){});\n
  • Or, override removedFromScene method
    class MyClass extends BaseClass {\n// ...\nremovedFromScene() {\nsuper.removedFromScene();\n// ...\n}\n}\n
"},{"location":"gameobject/#custom-class","title":"Custom class","text":"
  • Define class
    class MyClass extends BaseClass {\nconstructor(scene, x, y) {\nsuper(scene, x, y);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     if (super.preUpdate) {\n//         super.preUpdate(time, delta);\n//     }\n// }\n\n// destroy(fromScene) {\n//     //  This Game Object has already been destroyed\n//     if (!this.scene) {\n//         return;\n//     }\n//     super.destroy(fromScene);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
        • Some kinds of game object like Sprite, Dom-element has preUpdate method already.
  • Create instance
    var image = new MyClass(scene, x, y, key);\n
"},{"location":"gamepad/","title":"Gamepad","text":""},{"location":"gamepad/#introduction","title":"Introduction","text":"

Gamepad's state of buttons, or axis.

  • Author: Richard Davey
"},{"location":"gamepad/#usage","title":"Usage","text":""},{"location":"gamepad/#enable-gamepad-manager","title":"Enable gamepad manager","text":"
var config = {\n// ...\ninput: {\ngamepad: true\n},\n// ...\n}\nvar game = new Phaser.Game(config);\n
"},{"location":"gamepad/#get-gamepad","title":"Get gamepad","text":"
  • Get all currently connected Gamepads.
    var gamepads = scene.input.gamepad.getAll();\n
  • Get gamepad by index
    var gamepad = scene.input.gamepad.getPad(0);\n// var gamepad = scene.input.gamepad.getPad(index);\n
  • Get gamepad when button-down.
    scene.input.gamepad.once('down', function (gamepad, button, value) {\n}\n
    • gamepad : A reference to the Gamepad on which the button was released. See Properties of gamepad
    • button : A reference to the Button which was released.
    • value : The value of the button at the time it was released. Between 0 and 1. Some Gamepads have pressure-sensitive buttons.
"},{"location":"gamepad/#events","title":"Events","text":"
  • Button down
    scene.input.gamepad.on('down', function (gamepad, button, value) {\n})\n
    or
    gamepad.on('down', function(buttonIndex, value, button) {\n})\n
  • Button up
    scene.input.gamepad.on('up', function (gamepad, button, value) {\n}\n
    or
    gamepad.on('up', function(buttonIndex, value, button) {\n})\n
  • Gamepad connected
    scene.input.gamepad.on('connected', function (gamepad, event) {\n}\n
  • Gamepad disconnected
    scene.input.gamepad.on('disconnected', function (gamepad, event) {\n}\n
"},{"location":"gamepad/#gamepad","title":"Gamepad","text":""},{"location":"gamepad/#buttons","title":"Buttons","text":"
  • Cursor buttons
    var isLeftDown = gamepad.left;\nvar isRightftDown = gamepad.right;\nvar isUpDown = gamepad.up;\nvar isDownDown = gamepad.down;\n
  • Right buttons cluster
    var isADown = gamepad.A;  // Dual Shock controller: X button\nvar isYDown = gamepad.Y;  // Dual Shock controller: Triangle button\nvar isXDown = gamepad.X;  // Dual Shock controller: Square button.\nvar isBDown = gamepad.B;  // Dual Shock controller: Circle button\n
  • Shoulder buttons
    var isL1Down = gamepad.L1; // XBox controller: LB button\nvar isL2Down = gamepad.L2; // XBox controller: LT button\nvar isR1Down = gamepad.R1; // XBox controller: RB button\nvar isR2Down = gamepad.R2; // XBox controller: RT button\n
"},{"location":"gamepad/#axis-sticks","title":"Axis sticks","text":"
  • Left sticks, right sticks
    var leftStick = gamepad.leftStick;\nvar rightStick = gamepad.rightStick;\n
    • leftStick, rightStick : Read only vector2.
      • Angle : leftStick.angle()
      • Length : leftStick.length()
      • x, y : leftStick.x , leftStick.y
"},{"location":"gamepad/#properties","title":"Properties","text":"
  • gamepad.index : An integer that is unique for each Gamepad currently connected to the system. This can be used to distinguish multiple controllers. Note that disconnecting a device and then connecting a new device may reuse the previous index.
  • gamepad.id : A string containing some information about the controller.
  • gamepad.buttons : An array of Gamepad Button objects, corresponding to the different buttons available on the Gamepad.
  • gamepad.axes : An array of Gamepad Axis objects, corresponding to the different axes available on the Gamepad, if any.
"},{"location":"gashapon/","title":"Gashapon","text":""},{"location":"gashapon/#introduction","title":"Introduction","text":"

Pick random item from box.

  • Author: Rex
  • Member of scene, or game object
"},{"location":"gashapon/#usage","title":"Usage","text":"

Sample code

"},{"location":"gashapon/#install-plugin","title":"Install plugin","text":""},{"location":"gashapon/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexgashaponplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgashaponplugin.min.js', true);\n
  • Add gashapon object
    var gashapon = scene.plugins.get('rexgashaponplugin').add(config);\n
"},{"location":"gashapon/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GashaponPlugin from 'phaser3-rex-plugins/plugins/gashapon-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGashapon',\nplugin: GashaponPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add gashapon object
    var gashapon = scene.plugins.get('rexGashapon').add(config);\n
"},{"location":"gashapon/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Gashapon from 'phaser3-rex-plugins/plugins/gashapon.js';\n
  • Add gashapon object
    var gashapon = new Gashapon(config);\n
"},{"location":"gashapon/#create-instance","title":"Create instance","text":"
var gashapon = scene.plugins.get('rexGashapon').add({\nmode: 'shuffle',  // 0|'shuffle'|1|'random\nitems: {  // name:count\na:1, b:2, c:3 },\nreload: true,     // true|false\nrnd: undefined,\n});\n
  • mode :
    • 'shuffle', or 0 : pick item from box without put it back.
    • 'random', or 1 : pick item from box then put it back.
  • reload : set true to reload items when box is empty for shuffle mode.
  • items : initial items { name:count } in box.
  • rnd : Use random data generator to generate result.
    • undefined : Use Math.random() to generate result.
    • Phaser.Math.RND : Use pre-defined random data generator.
"},{"location":"gashapon/#pick-item","title":"Pick item","text":"
  • Pick a random item
    var item = gashapon.next();\n
    • return null if pick nothing
  • Pick specific item
    var item = gashapon.next(name);\n
    • return null if pick nothing
  • Last picked item
    var item = gashapon.result;\n
"},{"location":"gashapon/#set-item","title":"Set item","text":"
  • Set item
    gashapon.setItem(name, count);\n
  • Add item
    gashapon.addItem(name, count);\n
  • Put item back
    gashapon.putItemBack(name, count);\n
"},{"location":"gashapon/#remove-item","title":"Remove item","text":"
  • Remove item
    gashapon.removeItem(name);\n
  • Remove all items
    gashapon.removeAllItems();\n
"},{"location":"gashapon/#current-status","title":"Current status","text":"
  • Get current status
    var status = gashapon.toJSON();\n
  • Clone object
    var state = gashapon.toJSON();\nvar gashapon2 = new Gashapon(state);\n
  • Overwrite current status
    var status = gashapon.toJSON();\n// gashapon.next()...\ngashapon.resetFromJSON(status);\n
"},{"location":"gashapon/#get-items","title":"Get items","text":"
  • Get initial items
    var items = gashapon.getItems();\n
  • Get remainder items
    var items = gashapon.getRemain();\n
  • Get initial item count
    var count = gashapon.getItemCount(name);\n
  • Get remainder item count
    var count = gashapon.getRemainCount(name);\n
  • For each initial item
    gashapon.forEachItem(function(name, count) {\n\n}, scope);\n
  • For each remainder item
    gashapon.forEachRemain(function(name, count) {\n\n}, scope);\n
"},{"location":"gashapon/#set-random-generator","title":"Set random generator","text":"
gashapon.setRND(rnd);\n
  • rnd : Use random data generator to generate result.
    • undefined, or null : Use Math.random() to generate result.
    • Phaser.Math.RND : Use pre-defined random data generator.
"},{"location":"geom-circle/","title":"Circle","text":""},{"location":"geom-circle/#introduction","title":"Introduction","text":"

Circle shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-circle/#usage","title":"Usage","text":""},{"location":"geom-circle/#create-shape","title":"Create shape","text":"
var circle = new Phaser.Geom.Circle(x, y, radius);\n
"},{"location":"geom-circle/#clone-shape","title":"Clone shape","text":"
var circle1 = Phaser.Geom.Circle.Clone(circle0);\n
"},{"location":"geom-circle/#draw-on-graphics","title":"Draw on graphics","text":"
  • Fill shape
    // graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\ngraphics.fillCircleShape(circle);\n
  • Stroke shape
    // graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\ngraphics.strokeCircleShape(circle);\n

Note

Negative radius will be treated as positive radius. i.e. Math.abs(radius)

"},{"location":"geom-circle/#set-properties","title":"Set properties","text":"
  • All properties
    circle.setTo(x, y, radius);\n
    or
    Phaser.Geom.Circle.CopyFrom(source, dest);\n
  • Position
    circle.setPosition(x, y);\n
    or
    circle.x = 0;\ncircle.y = 0;\n
    or
    circle.left = 0;       // circle.x\ncircle.top = 0;        // circle.y\n// circle.right = 0;   // circle.x\n// circle.bottom = 0;  // circle.y\n
    or
    Phaser.Geom.Circle.Offset(circle, dx, dy); // circle.x += dx, circle.y += dy\n
    or
    Phaser.Geom.Circle.OffsetPoint(circle, point); // circle.x += point.x, circle.y += point.y\n
  • Radius
    circle.radius = radius;\n
    or
    circle.diameter = diameter;  // diameter = 2 * radius\n
"},{"location":"geom-circle/#get-properties","title":"Get properties","text":"
  • Position
    var x = circle.x;\nvar y = circle.y;\nvar top = circle.top;\nvar left = circle.left;\nvar right = circle.right;\nvar bottom = circle.bottom;\n
  • Radius
    var radius = circle.radius;\n// var diameter = circle.diameter;\n
  • Bound
    var bound = Phaser.Geom.Circle.GetBounds(circle);\n// var bound = Phaser.Geom.Circle.GetBounds(circle, bound);  // push bound\n
    • bound : A Rectangle shape object
  • Area
    var area = Phaser.Geom.Circle.Area(circle);\n
  • Circumference
    var circumference = Phaser.Geom.Circle.Circumference(circle);\n
  • Type:
    var type = circle.type; // 0\n
"},{"location":"geom-circle/#points-shape","title":"Point(s) & shape","text":"
  • Get point at shape's edge
    var point = circle.getPoint(t);  // t : 0 ~ 1 (angle/360)\n// var point = circle.getPoint(t, point);  // modify point\n
    or
    var point = Phaser.Geom.Circle.CircumferencePoint(circle, angle);  // angle in degrees\n// var point = Phaser.Geom.Circle.CircumferencePoint(circle, angle, point);  // modify point\n
  • Get a random point inside shape
    var point = circle.getRandomPoint();\n// var point = circle.getRandomPoint(point);  // modify point\n
  • Get points around shape's edge
    var points = circle.getPoints(quantity);\n// var points = circle.getPoints(quantity, null, points);  // push points\n
    or calculate quantity from steps
    var points = circle.getPoints(false, step);\n// var points = circle.getPoints(false, step, points);  // push points\n
    • points : an array of point
  • Point is inside shape
    var isInside = circle.contains(x, y);\n
    or
    var isInside = Phaser.Geom.Circle.ContainsPoint(circle, point);\n
  • Rectangle is inside shape
    var isInside = Phaser.Geom.Circle.ContainsRect(circle, rect);  // rect : 4 points\n
"},{"location":"geom-circle/#empty","title":"Empty","text":"
  • Set empty
    circle.setEmpty();     // circle.radius = 0\n
  • Is empty
    var isEmpty = circle.isEmpty();   // circle.radius <= 0\n
"},{"location":"geom-circle/#equal","title":"Equal","text":"
var isEqual = Phaser.Geom.Circle.Equals(circle0, circle1);\n

Position and radius are equal.

"},{"location":"geom-circle/#intersection","title":"Intersection","text":""},{"location":"geom-circle/#circle-to-circle","title":"Circle to circle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.CircleToCircle(circleA, circleB);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetCircleToCircle(circleA, circleB);\n// var out = Phaser.Geom.Intersects.GetCircleToCircle(circleA, circleB, out);\n
"},{"location":"geom-circle/#circle-to-rectangle","title":"Circle to rectangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.CircleToRectangle(circle, rect);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetCircleToRectangle(circle, rect);\n// var out = Phaser.Geom.Intersects.GetCircleToRectangle(circle, rect, out);\n
"},{"location":"geom-circle/#circle-to-triangle","title":"Circle to triangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.TriangleToCircle(triangle, circle);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetTriangleToCircle(triangle, circle);\n// var out = Phaser.Geom.Intersects.GetTriangleToCircle(triangle, circle, out);\n
"},{"location":"geom-circle/#circle-to-line","title":"Circle to line","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.LineToCircle(line, circle);\n// var result = Phaser.Geom.Intersects.LineToCircle(line, circle, nearest);\n
    • nearest : Nearest point on line.
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetLineToCircle(line, circle);\n// var out = Phaser.Geom.Intersects.GetLineToCircle(line, circle, out);\n
"},{"location":"geom-ellipse/","title":"Ellipse","text":""},{"location":"geom-ellipse/#introduction","title":"Introduction","text":"

Ellipse shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-ellipse/#usage","title":"Usage","text":""},{"location":"geom-ellipse/#create-shape","title":"Create shape","text":"
var ellipse = new Phaser.Geom.Ellipse(x, y, width, height);\n
"},{"location":"geom-ellipse/#clone-shape","title":"Clone shape","text":"
var ellipse1 = Phaser.Geom.Ellipse.Clone(ellipse0);\n
"},{"location":"geom-ellipse/#draw-on-graphics","title":"Draw on graphics","text":"
  • Fill shape
    // graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\ngraphics.fillEllipseShape(ellipse);\n
  • Stroke shape
    // graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\ngraphics.strokeEllipseShape(ellipse);\n

Note

Negative width, height will be treated as positive width, height. i.e. Math.abs(width), Math.abs(height)

"},{"location":"geom-ellipse/#set-properties","title":"Set properties","text":"
  • All properties
    ellipse.setTo(x, y, width, height);\n
    or
    Phaser.Geom.Ellipse.CopyFrom(source, dest);\n
  • Position
    ellipse.setPosition(x, y);\n
    or
    ellipse.x = 0;\nellipse.y = 0;\n
    or
    ellipse.left = 0;       // ellipse.x\nellipse.top = 0;        // ellipse.y\n// ellipse.right = 0;   // ellipse.x\n// ellipse.bottom = 0;  // ellipse.y\n
    or
    Phaser.Geom.Ellipse.Offset(ellipse, dx, dy); // ellipse.x += dx, ellipse.y += dy\n
    or
    Phaser.Geom.Ellipse.OffsetPoint(ellipse, point); // ellipse.x += point.x, ellipse.y += point.y\n
  • Width, height
    ellipse.width = width;\nellipse.height = height;\n
"},{"location":"geom-ellipse/#get-properties","title":"Get properties","text":"
  • Position
    var x = ellipse.x;\nvar y = ellipse.y;\nvar top = ellipse.top;\nvar left = ellipse.left;\nvar right = ellipse.right;\nvar bottom = ellipse.bottom;\n
  • Width, height
    var width = ellipse.width;\nvar height = ellipse.height;\n
  • Bound
    var bound = Phaser.Geom.Ellipse.GetBounds(ellipse);\n// var bound = Phaser.Geom.Ellipse.GetBounds(ellipse, bound);  // push bound\n
    • bound : A Rectangle shape object
  • Area
    var area = Phaser.Geom.Ellipse.Area(ellipse);\n
  • Circumference
    var circumference = Phaser.Geom.Ellipse.Circumference(ellipse);\n
  • Type:
    var type = ellipse.type; // 1\n
"},{"location":"geom-ellipse/#points-shape","title":"Point(s) & shape","text":"
  • Get point at shape's edge
    var point = ellipse.getPoint(t);  // t : 0 ~ 1 (angle/360)\n// var point = ellipse.getPoint(t, point);  // modify point\n
    or
    var point = Phaser.Geom.Ellipse.CircumferencePoint(ellipse, angle);  // angle in degrees\n// var point = Phaser.Geom.Ellipse.CircumferencePoint(ellipse, angle, point);  // modify point\n
  • Get a random point inside shape
    var point = ellipse.getRandomPoint();\n// var point = ellipse.getRandomPoint(point);  // modify point\n
  • Get points around shape's edge
    var points = ellipse.getPoints(quantity);\n// var points = ellipse.getPoints(quantity, null, points);  // push points\n
    or calculate quantity from steps
    var points = ellipse.getPoints(false, step);\n// var points = ellipse.getPoints(false, step, points);  // push points\n
    • points : an array of point
  • Point is inside shape
    var isInside = ellipse.contains(x, y);\n
    or
    var isInside = Phaser.Geom.Ellipse.ContainsPoint(ellipse, point);\n
  • Rectangle is inside shape
    var isInside = Phaser.Geom.Ellipse.ContainsRect(ellipse, rect);  // rect : 4 points\n
"},{"location":"geom-ellipse/#empty","title":"Empty","text":"
  • Set empty
    ellipse.setEmpty();     // ellipse.width = 0, ellipse.height = 0\n
  • Is empty
    var isEmpty = ellipse.isEmpty();   // ellipse.width <= 0 || ellipse.height <= 0\n
"},{"location":"geom-ellipse/#equal","title":"Equal","text":"
var isEqual = Phaser.Geom.Ellipse.Equals(ellipse0, ellipse1);\n

Position and width, height are equal.

"},{"location":"geom-hexagon/","title":"Hexagon","text":""},{"location":"geom-hexagon/#introduction","title":"Introduction","text":"

Hexagon shape and methods, extends from Polygon geometry object.

  • Author: Rex
  • Geometry object
"},{"location":"geom-hexagon/#usage","title":"Usage","text":"

Sample code

"},{"location":"geom-hexagon/#install-plugin","title":"Install plugin","text":""},{"location":"geom-hexagon/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexhexagonplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexhexagonplugin.min.js', true);\n
  • Add hexagon geometry object
    var hexagon = scene.plugins.get('rexhexagonplugin').add(x, y, size, orientationType);\n
"},{"location":"geom-hexagon/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import HexagonPlugin from 'phaser3-rex-plugins/plugins/hexagon-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexHexagon',\nplugin: HexagonPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add hexagon geometry object
    var hexagon = scene.plugins.get('rexHexagon').add(x, y, size, orientationType);\n
"},{"location":"geom-hexagon/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Hexagon from 'phaser3-rex-plugins/plugins/hexagon.js';\n
  • Add hexagon geometry object
    var hexagon = new Hexagon(x, y, size, orientationType);\n
"},{"location":"geom-hexagon/#create-shape","title":"Create shape","text":"

var hexagon = scene.plugins.get('rexHexagon').add(x, y, size, orientationType);\n
or
var hexagon = scene.plugins.get('rexHexagon').add({\nx: 0,\ny: 0,\nsize: 20,\norientationType: 0     // 0|'flat'|'vertical'|1|'pointy'|'horizontal'\n});\n
or
var hexagon = new Phaser.Geom.rexHexagon(x, y, size, orientationType);\n

  • x : Center X.
  • y : Center Y.
  • size : Distance between center to each corner.
  • orientationType : See here
    • 0, 'flat', or 'y'
    • 1, 'pointy' or ,'x'
"},{"location":"geom-hexagon/#draw-on-graphics","title":"Draw on graphics","text":"

See Polygon shape.

"},{"location":"geom-hexagon/#set-properties","title":"Set properties","text":"
  • All properties
    hexagon.setTo(x, y, size, orientationType);\n
  • Position
    hexagon.setPosition(x, y);\n
    or
    hexagon.x = 0;\nhexagon.y = 0;\n
    or
    hexagon.centerX = 0;  // equal to hexagon.x\nhexagon.centerY = 0;  // equal to hexagon.y\n
    or
    hexagon.left = 0;       // hexagon.x\nhexagon.top = 0;        // hexagon.y\nhexagon.right = 0;      // hexagon.x\nhexagon.bottom = 0;     // hexagon.y\n
  • Size
    hexagon.setSize(size);\n
    or
    hexagon.size = size;\n
  • Orientation type
    hexagon.setType(orientationType);\n
    or
    hexagon.orientationType = orientationType;\n
    • orientationType : See here
      • 0, 'flat', or 'y'
      • 1, 'pointy' or ,'x'
"},{"location":"geom-hexagon/#get-properties","title":"Get properties","text":"

See Polygon shape.

  • Position
    • Center
      var centerX = hexagon.centerX;\nvar centerY = hexagon.centerY;\n
      or
      var centerX = hexagon.x;\nvar centerY = hexagon.y;\n
    • Bound
      var top = hexagon.top;\nvar left = hexagon.left;\nvar right = hexagon.right;\nvar bottom = hexagon.bottom;\n
  • Width
    var width = hexagon.width;\n
  • Height
    var width = hexagon.height;\n
  • Lines around hexagon
    var edge01 = hexagon.getLineA();\nvar edge12 = hexagon.getLineB();\nvar edge23 = hexagon.getLineC();\nvar edge34 = hexagon.getLineD();\nvar edge45 = hexagon.getLineE();\nvar edge50 = hexagon.getLineF();\n// var out = hexagon.getLineF(out);\n
    or
    var edge = hexagon.getEdge(edgeIdx);\n// var out = hexagon.getEdge(edgeIdx, out);\n
"},{"location":"geom-hexagon/#points-shape","title":"Point(s) & shape","text":"

See Polygon shape.

"},{"location":"geom-line/","title":"Line","text":""},{"location":"geom-line/#introduction","title":"Introduction","text":"

Line shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-line/#usage","title":"Usage","text":""},{"location":"geom-line/#create-shape","title":"Create shape","text":"
var line = new Phaser.Geom.Line(x1, y1, x2, y2);\n
"},{"location":"geom-line/#clone-shape","title":"Clone shape","text":"
var line1 = Phaser.Geom.Line.Clone(line0);\n
"},{"location":"geom-line/#draw-on-graphics","title":"Draw on graphics","text":"
// graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\ngraphics.strokeLineShape(line);\n
"},{"location":"geom-line/#set-properties","title":"Set properties","text":"
  • All properties
    line.setTo(x1, y1, x2, y2);\n
    or
    Phaser.Geom.Line.CopyFrom(source, dest);\n
  • Position
    line.x1 = 0;\nline.y1 = 0;\nline.x2 = 0;\nline.y2 = 0;\n
    or
    line.left = 0;    // min(x1, x2)\nline.top = 0;     // min(y1, y2)\nline.right = 0;   // max(x1, x2)\nline.bottom = 0;  // max(y1, y2)\n
    • Offset start, end
      var line = Phaser.Geom.Line.Offset(line, dx, dy); // line.x1 += dx, line.y1 += dy, line.x2 += dx, line.y2 += dy\n
    • Set center position
      var line = Phaser.Geom.Line.CenterOn(line, x, y);\n
  • Start point, angle, length
    var line = Phaser.Geom.Line.SetToAngle(line, x, y, angle, length);\n
    • line : The line to set
    • x , y : start point
    • angle : The angle of the line in radians
      var rad = Phaser.Math.DegToRad(deg);\n
    • length :\u3000The length of the line
  • Rotate
    • Rotate around midpoint
      var line = Phaser.Geom.Line.Rotate(line, angle)\n
      • line : The line to set
      • angle : The angle of the line in radians
        var rad = Phaser.Math.DegToRad(deg);\n
    • Rotate around point
      var line = Phaser.Geom.Line.RotateAroundPoint(line, point, angle);\n
      or
      var line = Phaser.Geom.Line.RotateAroundXY(line, x, y, angle);\n
      • line : The line to set
      • angle : The angle of the line in radians
        var rad = Phaser.Math.DegToRad(deg);\n
  • Extend
    var line = Phaser.Geom.Line.Extend(line, left, right);\n
"},{"location":"geom-line/#get-properties","title":"Get properties","text":"
  • Position
    var x1 = line.x1;\nvar y1 = line.y1;\nvar x2 = line.x2;\nvar y2 = line.y2;\nvar top = line.top;       // min(x1, x2)\nvar left = line.left;     // min(y1, y2)\nvar right = line.right;   // max(x1, x2)\nvar bottom = line.bottom; // max(y1, y2)\n
    • Start point
      var start = line.getPointA();  // start: {x, y}\nvar start = line.getPointA(start);  // push start\n
    • End point
      var end = line.getPointB();  // end: {x, y}\nvar end = line.getPointB(end);  // push end\n
    • Middle point
      var middle = Phaser.Geom.Line.GetMidPoint(line);  // middle: {x, y}\n// var middle = Phaser.Geom.Line.GetMidPoint(line, middle);\n
  • Length
    var length = Phaser.Geom.Line.Length(line);\n
    • Width : Abs(x1 - x2)
      var width = Phaser.Geom.Line.Width(line);\n
    • Height : Abs(y1 - y2)
      var width = Phaser.Geom.Line.Height(line);\n
  • Slope
    • Slope : (y2 - y1) / (x2 - x1)
      var slope = Phaser.Geom.Line.Slope(line);\n
    • Perpendicular slope : -((x2 - x1) / (y2 - y1))
      var perpSlope = Phaser.Geom.Line.PerpSlope(line);\n
  • Angle
    • Angle
      var angle = Phaser.Geom.Line.Angle(line);\n
      • angle : The angle of the line in radians
        var deg = Phaser.Math.RadToDeg(rad);  // deg : -180 ~ 180\n
    • Normal angle (angle - 90 degrees)
      • Normal angle
        var normalAngle = Phaser.Geom.Line.NormalAngle(line);\n
      • Normal vector
        var normal = Phaser.Geom.Line.GetNormal(line);  // normal: {x, y}\n// var normal = Phaser.Geom.Line.GetNormal(line, normal);  // push normal\n
        or
        var normalX = Phaser.Geom.Line.NormalX(line);\nvar normalY = Phaser.Geom.Line.NormalY(line);\n
    • Reflect angle
      var reflectAngle = Phaser.Geom.Line.ReflectAngle(aimLine, reflectingLine);\n
  • Type:
    var type = line.type; // 2\n
"},{"location":"geom-line/#points-shape","title":"Point(s) & shape","text":"
  • Get point at shape's edge
    var point = line.getPoint(t);  // t : 0 ~ 1. 0=start, 0.5=middle, 1=end\n// var point = line.getPoint(t, point);  // modify point\n
  • Get a random point inside shape
    var point = line.getRandomPoint();\n// var point = line.getRandomPoint(point);  // modify point\n
  • Get points around shape's edge
    var points = line.getPoints(quantity);\n// var points = line.getPoints(quantity, null, points);  // push points\n
    or calculate quantity from steps
    var points = line.getPoints(false, step);\n// var points = line.getPoints(false, step, points);  // push points\n
    • points : an array of point
  • Get points using Bresenham's line algorithm
    var points = Phaser.Geom.Line.BresenhamPoints(line, step);\n// var points = Phaser.Geom.Line.BresenhamPoints(line, step, points);  // push points\n
  • Get points using easing function
    var points = Phaser.Geom.Line.GetEasedPoints(line, ease, quantity);\n// var points = Phaser.Geom.Line.GetEasedPoints(line, ease, quantity, collinearThreshold, easeParams);\n
    • ease : String of ease function, or a custom function (function (t) { return value}).
    • quantity : The number of points to return.
    • collinearThreshold : Each point is spaced out at least this distance apart. This helps reduce clustering in noisey eases.
    • easeParams : Array of ease parameters to go with the ease.
  • Get the nearest point on a line perpendicular to the given point.
    var point = Phaser.Geom.Line.GetNearestPoint(line, pointIn);\n// var point = Phaser.Geom.Line.GetNearestPoint(line, pointIn, point);\n
  • Get the shortest distance from a Line to the given Point.
    var distance = Phaser.Geom.Line.GetShortestDistance(line, point);\n
"},{"location":"geom-line/#equal","title":"Equal","text":"
var isEqual = Phaser.Geom.Line.Equals(line0, line1);\n

x1, y2, x2, y2 are equal.

"},{"location":"geom-line/#intersection","title":"Intersection","text":""},{"location":"geom-line/#line-to-circle","title":"Line to circle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.LineToCircle(line, circle);\n// var result = Phaser.Geom.Intersects.LineToCircle(line, circle, nearest);\n
    • nearest : Nearest point on line.
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetLineToCircle(line, circle);\n// var out = Phaser.Geom.Intersects.GetLineToCircle(line, circle, out);\n
"},{"location":"geom-line/#line-to-rectangle","title":"Line to rectangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.LineToRectangle(line, rect);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetLineToRectangle(line, rect);\n// var out = Phaser.Geom.Intersects.GetLineToRectangle(line, rect, out);\n
"},{"location":"geom-line/#line-to-triangle","title":"Line to triangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.TriangleToLine(triangle, line);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetTriangleToLine(triangle, line);\n// var out = Phaser.Geom.Intersects.GetTriangleToLine(triangle, line, out);\n
"},{"location":"geom-line/#line-to-line","title":"Line to line","text":"
  • Is intersection
    var isIntersection = Phaser.Geom.Intersects.LineToLine(line1, line2);\n
    • isIntersection : Return true if line1 and line2 are intersectioned
  • Get intersection point
    var isIntersection = Phaser.Geom.Intersects.LineToLine(line1, line2, out);\n
    • isIntersection : Return true if line1 and line2 are intersectioned
    • out : intersected point
"},{"location":"geom-point/","title":"Point","text":""},{"location":"geom-point/#introduction","title":"Introduction","text":"

Warning

The Geom.Point class and all related functions will be removed. All functionality for this can be found in the existing Vector2 math classes. All Geometry classes that currently create and return Point objects will be updated to return Vector2 objects instead.

Point shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-point/#usage","title":"Usage","text":""},{"location":"geom-point/#create-shape","title":"Create shape","text":"
var point = new Phaser.Geom.Point(x, y);\n
"},{"location":"geom-point/#clone-shape","title":"Clone shape","text":"
var point1 = Phaser.Geom.Point.Clone(point0);\n
"},{"location":"geom-point/#draw-on-graphics","title":"Draw on graphics","text":"
// graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\ngraphics.fillPointShape(point, size);\n
"},{"location":"geom-point/#set-properties","title":"Set properties","text":"
  • All properties
    point.setTo(x, y);\n
    or
    Phaser.Geom.Point.CopyFrom(source, dest);\n
  • Position
    point.x = 0;\npoint.y = 0;\n
  • Round
    • Ceil : Apply Math.ceil() to each coordinate of the given Point
      var point = Phaser.Geom.Point.Ceil(point)\n
    • Floor : Apply Math.floor() to each coordinate of the given Point.
      var point = Phaser.Geom.Point.Floor(point)\n
"},{"location":"geom-point/#symmetry","title":"Symmetry","text":"
  • Invert : x = y, y = x
    var point = Phaser.Geom.Point.Invert(point);\n
  • Negative : x = -x, y = -y
    var out = Phaser.Geom.Point.Negative(point);\n// var out = Phaser.Geom.Point.Negative(point, out);  // modify out\n
"},{"location":"geom-point/#get-properties","title":"Get properties","text":"
  • Position
    var x = point.x;\nvar y = point.y;\n
  • Type:
    var type = point.type; // 3\n
"},{"location":"geom-point/#equal","title":"Equal","text":"
var isEqual = Phaser.Geom.Point.Equals(point0, point1);\n

x, y are equal.

"},{"location":"geom-point/#points","title":"Points","text":"
  • Centroid : center-point over some points
    var out = Phaser.Geom.Point.GetCentroid(points);\n// var out = Phaser.Geom.Point.GetCentroid(points, out);  // modify out\n
  • Calculates the Axis Aligned Bounding Box (or aabb) from an array of points (rectangle)
    var rect = Phaser.Geom.Point.GetRectangleFromPoints(points);\n// var rect = Phaser.Geom.Point.GetRectangleFromPoints(points, rect);  // modify rect\n
  • Interpolate
    var out = Phaser.Geom.Point.Interpolate(pointA, pointB, t);  // out : point\n// var out = Phaser.Geom.Point.Interpolate(pointA, pointB, t, out);  // modify out\n
"},{"location":"geom-point/#intersection","title":"Intersection","text":"
  • Point to line
    var result = Phaser.Geom.Intersects.PointToLine(point, line);\n// var result = Phaser.Geom.Intersects.PointToLine(point, line, lineThickness);\n
    var result = Phaser.Geom.Intersects.PointToLineSegment(point, line);\n
"},{"location":"geom-point/#point-as-vector","title":"Point as Vector","text":"

Vector starting at (0,0)

  • Magnitude : sqrt( (x * x) + (y * y) )
    var magnitude = Phaser.Geom.Point.GetMagnitude(point);\n
    or
    var magnitudeSq = Phaser.Geom.Point.GetMagnitudeSq(point);\n
  • Project
    var out = Phaser.Geom.Point.Project(from, to);\n// var out = Phaser.Geom.Point.Project(from, to, out);  // modify out\n
    or
    var out = Phaser.Geom.Point.ProjectUnit(from, to);  // vector `from` and `to` are unit vector (length = 1)\n// var out = Phaser.Geom.Point.ProjectUnit(from, to, out);  // modify out\n
"},{"location":"geom-polygon/","title":"Polygon","text":""},{"location":"geom-polygon/#introduction","title":"Introduction","text":"

Polygon shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-polygon/#usage","title":"Usage","text":""},{"location":"geom-polygon/#create-shape","title":"Create shape","text":"
var polygon = new Phaser.Geom.Polygon(points);\n
  • points :
    • An array of number : [x0, y0, x1, y1, ...]
    • An array of points : [{x:x0, y:y0}, {x:x1, y:y1}, ...]
    • A string : 'x0 y0 x1 y1 ...'
"},{"location":"geom-polygon/#clone-shape","title":"Clone shape","text":"
var polygon1 = Phaser.Geom.Polygon.Clone(polygon0);\n
"},{"location":"geom-polygon/#draw-on-graphics","title":"Draw on graphics","text":"
  • Fill shape
    // graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\ngraphics.fillPoints(polygon.points, true);\n
  • Stroke shape
    // graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\ngraphics.strokePoints(polygon.points, true);\n
"},{"location":"geom-polygon/#set-properties","title":"Set properties","text":"
polygon.setTo(points);\n// points = [x0, y0, x1, y1, x2, y2, ...] , or [{x,y}, {x,y}, {x,y}, ...]\n
"},{"location":"geom-polygon/#get-properties","title":"Get properties","text":"
  • Points
    var points = polygon.points;    // array of points {x,y}\n
  • Area
    var area = polygon.area;\n
  • Number array
    var out = Phaser.Geom.Polygon.GetNumberArray(polygon);\n// var out = Phaser.Geom.Polygon.GetNumberArray(polygon, out);  // modify out\n
    • arr : [x0, y0, x1, y1, x2, y2, ...]
  • AABB (A minimum rectangle to cover this polygon)
    var out = Phaser.Geom.Polygon.GetAABB(polygon);\n// var out = Phaser.Geom.Polygon.GetAABB(polygon, out);\n
    • out : A rectangle object
  • Type:
    var type = polygon.type; // 4\n
"},{"location":"geom-polygon/#points-shape","title":"Point(s) & shape","text":"
  • Point is inside shape
    var isInside = polygon.contains(x, y);\n
    or
    var isInside = Phaser.Geom.Polygon.ContainsPoint(polygon, point);\n
  • Translate : Shift points.
    Phaser.Geom.Polygon.Translate(polygon, x, y);\n
  • Reverse the order of points.
    var polygon = Phaser.Geom.Polygon.Reverse(polygon);\n
  • Smooth : Takes a Polygon object and applies Chaikin's smoothing algorithm on its points.
    Phaser.Geom.Polygon.Smooth(polygon)\n
  • Simplify : Simplifies the points by running them through a combination of Douglas-Peucker and Radial Distance algorithms. Simplification dramatically reduces the number of points in a polygon while retaining its shape, giving a huge performance boost when processing it and also reducing visual noise.
    var polygon = Phaser.Geom.Polygon.Simplify(polygon);\n// var polygon = Phaser.Geom.Polygon.Simplify(polygon, tolerance, highestQuality);\n
"},{"location":"geom-polygon/#vector-to-polygon","title":"Vector to polygon","text":"
  • Get closest point of intersection between a vector and an array of polygons
    var result = Phaser.Geom.Intersects.GetLineToPolygon(line, polygons);\n// var out = Phaser.Geom.Intersects.GetLineToPolygon(line, polygons, isRay, out);\n
    • line : Vector of line object
    • polygons : A single polygon, or array of polygons
    • isRay : Is line a ray or a line segment?
    • out :
      • out.x, out.y : Intersection point
      • out.z : Closest intersection distance
      • out.w : Index of the polygon
  • Projects rays out from the given point to each line segment of the polygons.
    var out = Phaser.Geom.Intersects.GetRaysFromPointToPolygon(x, y, polygons);\n
    • x, y : The point to project the rays from.
    • polygons : A single polygon, or array of polygons
    • out : An array containing all intersections
      • out[i].x, out[i].y : Intersection point
      • out[i].z : Angle of intersection
      • out[i].w : Index of the polygon
"},{"location":"geom-rectangle/","title":"Rectangle","text":""},{"location":"geom-rectangle/#introduction","title":"Introduction","text":"

Rectangle shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-rectangle/#usage","title":"Usage","text":""},{"location":"geom-rectangle/#create-shape","title":"Create shape","text":"
var rect = new Phaser.Geom.Rectangle(x, y, width, height);\n
"},{"location":"geom-rectangle/#create-from-points","title":"Create from points","text":"

All of the given points are on or within its bounds.

var rect = Phaser.Geom.Rectangle.FromPoints(points);\n// var rect = Phaser.Geom.Rectangle.FromPoints(points, rect);  // push rect\n
  • points : an array with 4 points. [x, y], or {x:0, y:0}

or

var rect = Phaser.Geom.Rectangle.FromXY(x1, y1, x2, y2);\n// var rect = Phaser.Geom.Rectangle.FromXY(x1, y1, x2, y2, rect);  // push rect\n
"},{"location":"geom-rectangle/#clone-shape","title":"Clone shape","text":"
var rect1 = Phaser.Geom.Rectangle.Clone(rect0);\n
"},{"location":"geom-rectangle/#draw-on-graphics","title":"Draw on graphics","text":"
  • Fill shape
    // graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\ngraphics.fillRectShape(rect);\n
  • Stroke shape
    // graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\ngraphics.strokeRectShape(rect);\n

Note

x with positive/negative width is left/right bound y with positive/negative height is top/bottom bound

"},{"location":"geom-rectangle/#set-properties","title":"Set properties","text":"
  • All properties
    rect.setTo(x, y, width, height);\n
    or
    Phaser.Geom.Rectangle.CopyFrom(source, dest);\n
  • Position
    rect.setPosition(x, y);\n
    or
    rect.x = 0;\nrect.y = 0;\n
    or
    rect.left = 0;       // rect.x, rect.width\nrect.top = 0;        // rect.y, rect.height\n// rect.right = 0;   // rect.x, rect.width\n// rect.bottom = 0;  // rect.y, rect.height\nrect.centerX = 0;    // rect.x\nrect.centerY = 0;    // rect.y\n
    or
    Phaser.Geom.Rectangle.Offset(rect, dx, dy); // rect.x += dx, rect.y += dy\n
    or
    Phaser.Geom.Rectangle.OffsetPoint(rect, point); // rect.x += point.x, rect.y += point.y\n
    or
    Phaser.Geom.Rectangle.CenterOn(rect, x, y);  // rect.x = x - (rect.width / 2), rect.y = y - (rect.height / 2)\n
  • Size
    rect.setSize(width, height);\n// rect.setSize(width);   // height = width\n
    or
    rect.width = 0;\nrect.height = 0;\n
    • Scale
      Phaser.Geom.Rectangle.Scale(rect, x, y); // rect.width *= x, rect.height *= y;\n// Phaser.Geom.Rectangle.Scale(rect, x);   // y = x\n
    • Extend size to include points
      Phaser.Geom.Rectangle.MergePoints(rect, points);\n
      • points : an array of points. [x, y], or {x:0, y:0}
    • Extend size to include another rectangle
      Phaser.Geom.Rectangle.MergeRect(target, source);\n
  • Inflate
    Phaser.Geom.Rectangle.Inflate(rect, x, y);\n
    1. change size to width += x*2, height += y*2
    2. center on previous position
  • Fits the target rectangle into the source rectangle
    Phaser.Geom.Rectangle.FitInside(target, source);\n
    Preserves aspect ratio, scales and centers the target rectangle to the source rectangle
  • Fits the target rectangle around the source rectangle
    Phaser.Geom.Rectangle.FitOutside(target, source);\n
    Preserves aspect ratio, scales and centers the target rectangle to the source rectangle
  • Ceil
    Phaser.Geom.Rectangle.Ceil(rect);  // ceil x, y\n
    Phaser.Geom.Rectangle.CeilAll(rect);  // ceil x, y, width, height\n
  • Floor
    Phaser.Geom.Rectangle.Floor(rect);  // floor x, y\n
    Phaser.Geom.Rectangle.FloorAll(rect);  // floor x, y, width, height\n
"},{"location":"geom-rectangle/#get-properties","title":"Get properties","text":"
  • Position
    var x = rect.x;\nvar y = rect.y;\n
    • Bound
      var top = rect.top;\nvar left = rect.left;\nvar right = rect.right;\nvar bottom = rect.bottom;\n
      or
      var points = Phaser.Geom.Rectangle.Decompose(rect);\n// var points = Phaser.Geom.Rectangle.Decompose(rect, points); // push result points\n
      • points : top-left, top-right, bottom-right, bottom-left
    • Center
      var centerX = rect.centerX;\nvar centerY = rect.centerY;\n
      or
      var point = Phaser.Geom.Rectangle.GetCenter(rect);\n// var point = Phaser.Geom.Rectangle.GetCenter(rect, point);\n
  • Size
    var width = rect.width;\nvar height = rect.height;\n
    or
    var point = Phaser.Geom.Rectangle.GetSize(rect); // {x: rect.width, y: rect.height}\n
  • Area
    var area = Phaser.Geom.Rectangle.Area(rect);\n
  • Perimeter
    var perimeter = Phaser.Geom.Rectangle.Perimeter(rect);  // 2 * (rect.width + rect.height)\n
  • Aspect ratio
    var aspectRatio = Phaser.Geom.Rectangle.GetAspectRatio(rect);  // rect.width / rect.height\n
  • Lines around rectangle
    var topLine = rect.getLineA();  // top line of this rectangle\nvar rightLine = rect.getLineB();  // right line of this rectangle\nvar bottomLine = rect.getLineC();  // bottom line of this rectangle\nvar leftLine = rect.getLineD();  // left line of this rectangle\n// var out = rect.getLineA(out);  // top line of this rectangle\n
  • Type:
    var type = rect.type; // 5\n
"},{"location":"geom-rectangle/#points-shape","title":"Point(s) & shape","text":"
  • Get point at shape's edge
    var point = rect.getPoint(t);  // t : 0 ~ 1 (0= top-left, 0.5= bottom-right, 1= top-left)\n// var point = rect.getPoint(t, point);  // modify point\n
    or
    var point = Phaser.Geom.Rectangle.PerimeterPoint(rect, angle);  // angle in degrees\n// var point = Phaser.Geom.Rectangle.PerimeterPoint(rect, angle, point);  // push point\n
  • Get points around shape's edge
    var points = rect.getPoints(quantity);\n// var points = rect.getPoints(quantity, null, points);  // push points\n
    or calculate quantity from steps
    var points = rect.getPoints(false, step);\n// var points = rect.getPoints(false, step, points);  // push points\n
    • step : width of each step, in pixels. quantity = Perimeter(rectangle) / step;
    • points : an array of point
  • Point is inside shape
    var isInside = rect.contains(x, y);\n
    or
    var isInside = Phaser.Geom.Rectangle.ContainsPoint(rect, point);\n
  • Get a random point inside shape
    var point = rect.getRandomPoint();\n// var point = rect.getRandomPoint(point);  // modify point\n
  • Get a random point outside shape
    var point = Phaser.Geom.Rectangle.RandomOutside(outer, inner);\n// var point = Phaser.Geom.Rectangle.RandomOutside(outer, inner, point); // modify point\n
  • Rectangle is inside shape
    var isInside = Phaser.Geom.Rectangle.ContainsRect(rectA, rectB);  // rectB is inside rectA\n
"},{"location":"geom-rectangle/#rectangles","title":"Rectangles","text":"
  • Is overlapping
    var isOverlapping = Phaser.Geom.Rectangle.Overlaps(rectA, rectB);\n
  • Get intersection rectangle
    var rect = Phaser.Geom.Rectangle.Intersection(rectA, rectB);\nvar rect = Phaser.Geom.Rectangle.Intersection(rectA, rectB, rect);  // push rect\n
  • Get union rectangle
    var rect = Phaser.Geom.Rectangle.Union(rectA, rectB);\nvar rect = Phaser.Geom.Rectangle.Union(rectA, rectB, rect);  // push rect\n
"},{"location":"geom-rectangle/#empty","title":"Empty","text":"
  • Set empty
    rect.setEmpty();     // rect.x = 0, rect.y = 0, rect.width = 0, rect.height = 0\n
  • Is empty
    var isEmpty = rect.isEmpty();   // rect.radius <= 0;\n
"},{"location":"geom-rectangle/#equal","title":"Equal","text":"
  • Position, width, and height are the same
    var isEqual = Phaser.Geom.Rectangle.Equals(rect0, rect1);\n
  • Width and height are the same
    var isEqual = Phaser.Geom.Rectangle.SameDimensions(rect0, rect1);\n
"},{"location":"geom-rectangle/#intersection","title":"Intersection","text":""},{"location":"geom-rectangle/#rectangle-to-circle","title":"Rectangle to circle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.CircleToRectangle(circle, rect);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetCircleToRectangle(circle, rect);\n// var out = Phaser.Geom.Intersects.GetCircleToRectangle(circle, rect, out);\n
"},{"location":"geom-rectangle/#rectangle-to-rectangle","title":"Rectangle to rectangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.RectangleToRectangle(rectA, rectB);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetRectangleToRectangle(rectA, rectB);\n// var out = Phaser.Geom.Intersects.GetRectangleToRectangle(rectA, rectB, out);\n
"},{"location":"geom-rectangle/#rectangle-to-triangle","title":"Rectangle to triangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.RectangleToTriangle(rect, triangle);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetRectangleToTriangle(rect, triangle);\n// var out = Phaser.Geom.Intersects.GetRectangleToTriangle(rect, triangle, out);\n
"},{"location":"geom-rectangle/#rectangle-to-line","title":"Rectangle to line","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.LineToRectangle(line, rect);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetLineToRectangle(line, rect);\n// var out = Phaser.Geom.Intersects.GetLineToRectangle(line, rect, out);\n
"},{"location":"geom-rhombus/","title":"Rhombus","text":""},{"location":"geom-rhombus/#introduction","title":"Introduction","text":"

Rhombus shape and methods, extends from Polygon geometry object.

  • Author: Rex
  • Geometry object
"},{"location":"geom-rhombus/#usage","title":"Usage","text":"

Sample code

"},{"location":"geom-rhombus/#install-plugin","title":"Install plugin","text":""},{"location":"geom-rhombus/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrhombusplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrhombusplugin.min.js', true);\n
  • Add rhombus geometry object
    var rhombus = scene.plugins.get('rexrhombusplugin').add(x, y, width, height);\n
"},{"location":"geom-rhombus/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RhombusPlugin from 'phaser3-rex-plugins/plugins/rhombus-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRhombus',\nplugin: RhombusPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add rhombus geometry object
    var rhombus = scene.plugins.get('rexRhombus').add(x, y, width, height);\n
"},{"location":"geom-rhombus/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Rhombus from 'phaser3-rex-plugins/plugins/rhombus.js';\n
  • Add rhombus geometry object
    var rhombus = new Rhombus(x, y, width, height);\n
"},{"location":"geom-rhombus/#create-shape","title":"Create shape","text":"

var rhombus = scene.plugins.get('rexRhombus').add(x, y, width, height);\n
or
var rhombus = scene.plugins.get('rexRhombus').add({\nx: 0,\ny: 0,\nwidth: 40,\nheight: 20\n});\n
or
var rhombus = new rexRhombus(x, y, width, height);\n// var rhombus = new Phaser.Geom.rexRhombus(x, y, width, height);\n

  • x : Top X.
  • y : Left Y.
"},{"location":"geom-rhombus/#draw-on-graphics","title":"Draw on graphics","text":"

See Polygon shape.

"},{"location":"geom-rhombus/#set-properties","title":"Set properties","text":"
  • All properties
    rhombus.setTo(x, y, width, height);\n
  • Position
    rhombus.setPosition(x, y);\n
    or
    rhombus.x = 0;\nrhombus.y = 0;\n
    or
    rhombus.left = 0;       // rhombus.x\nrhombus.top = 0;        // rhombus.y\nrhombus.right = 0;      // rhombus.x\nrhombus.bottom = 0;     // rhombus.y\n
  • Size
    rhombus.setSize(width, height);\n
    or
    rhombus.width = width;\nrhombus.height = height;\n
"},{"location":"geom-rhombus/#get-properties","title":"Get properties","text":"

See Polygon shape.

  • Position
    • Center
      var centerX = rhombus.centerX;\nvar centerY = rhombus.centerY;\n
    • Bound
      var top = rhombus.top;\nvar left = rhombus.left;\nvar right = rhombus.right;\nvar bottom = rhombus.bottom;\n
  • Width
    var width = rhombus.width;\n
  • Height
    var width = rhombus.height;\n
  • Lines around rhombus
    var edge01 = rhombus.getLineA();\nvar edge12 = rhombus.getLineB();\nvar edge23 = rhombus.getLineC();\nvar edge34 = rhombus.getLineD();\n
    or
    var edge = rhombus.getEdge(edgeIdx);\n// var out = rhombus.getEdge(edgeIdx, out);\n
"},{"location":"geom-rhombus/#points-shape","title":"Point(s) & shape","text":"

See Polygon shape.

"},{"location":"geom-triangle/","title":"Triangle","text":""},{"location":"geom-triangle/#introduction","title":"Introduction","text":"

Triangle shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-triangle/#usage","title":"Usage","text":""},{"location":"geom-triangle/#create-shape","title":"Create shape","text":"
var triangle = new Phaser.Geom.Triangle(x1, y1, x2, y2, x3, y3);\n
"},{"location":"geom-triangle/#clone-shape","title":"Clone shape","text":"
var triangle1 = Phaser.Geom.Triangle.Clone(triangle0);\n
"},{"location":"geom-triangle/#equilateral-triangle","title":"Equilateral triangle","text":"
var triangle = Phaser.Geom.Triangle.BuildEquilateral(x1, y1, length);\n
"},{"location":"geom-triangle/#right-triangle","title":"Right triangle","text":"
var triangle = Phaser.Geom.Triangle.BuildRight(x1, y1, width, height);\n
"},{"location":"geom-triangle/#polygon-to-triangles","title":"Polygon to triangles","text":"
var out = Phaser.Geom.Triangle.BuildFromPolygon(data);\n// var out = Phaser.Geom.Triangle.BuildFromPolygon(data, holes, scaleX, scaleY);\n// out = Phaser.Geom.Triangle.BuildFromPolygon(data, holes, scaleX, scaleY, out);\n
  • data : A flat array of vertice coordinates like [x0,y0, x1,y1, x2,y2, ...]
  • out : Array of triangles
"},{"location":"geom-triangle/#draw-on-graphics","title":"Draw on graphics","text":"
  • Fill shape
    // graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\ngraphics.fillTriangleShape(triangle);\n
  • Stroke shape
    // graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\ngraphics.strokeTriangleShape(triangle);\n
"},{"location":"geom-triangle/#set-properties","title":"Set properties","text":"
  • All properties
    triangle.setTo(x1, y1, x2, y2, x3, y3);\n
    or
    Phaser.Geom.Triangle.CopyFrom(source, dest);\n
  • Position
    triangle.x1 = 0;\ntriangle.y1 = 0;\ntriangle.x2 = 0;\ntriangle.y2 = 0;\ntriangle.x3 = 0;\ntriangle.y3 = 0;\n
    or
    triangle.left = 0;       // triangle.x1, triangle.x2, triangle.x3\ntriangle.top = 0;        // triangle.y1, triangle.y2, triangle.y3\n// triangle.right = 0;   // triangle.x1, triangle.x2, triangle.x3\n// triangle.bottom = 0;  // triangle.y1, triangle.y2, triangle.y3\n
    or
    Phaser.Geom.Triangle.Offset(triangle, dx, dy); // triangle.x += dx, triangle.y += dy\n
    or
    Phaser.Geom.Triangle.CenterOn(triangle, x, y);\n
  • Rotate
    • Rotate around center (incenter)
      var triangle = Phaser.Geom.Triangle.Rotate(triangle, angle);\n
      • angle : Radian
    • Rotate around point
      var triangle = Phaser.Geom.Triangle.RotateAroundPoint(triangle, point, angle);\n
      • point : {x, y}
      • angle : Radian
    • Rotate around (x,y)
      var triangle = Phaser.Geom.Triangle.RotateAroundXY(triangle, x, y, angle);\n
      • angle : Radian
"},{"location":"geom-triangle/#get-properties","title":"Get properties","text":"
  • Position
    var x1 = triangle.x1;\nvar y1 = triangle.y1;\nvar x2 = triangle.x2;\nvar y2 = triangle.y2;\nvar x3 = triangle.x3;\nvar y3 = triangle.y3;\nvar top = triangle.top;\nvar left = triangle.left;\nvar right = triangle.right;\nvar bottom = triangle.bottom;\n
    or
    var out = Phaser.Geom.Triangle.Decompose(triangle);  // out: [{x1,y1}, {x2,y2}, {x3,y3}]\n// var out = Phaser.Geom.Triangle.Decompose(triangle, out);\n
  • Perimeter
    var perimeter = Phaser.Geom.Triangle.Perimeter(triangle);\n
  • Area
    var area = Phaser.Geom.Triangle.Area(triangle);\n
  • Lines around triangle
    var line12 = rect.getLineA();     // line from (x1, y1) to (x2, y2)\nvar line23 = rect.getLineB();     // line from (x2, y2) to (x3, y3)\nvar line31 = rect.getLineC();     // line from (x3, y3) to (x1, y1)\n
  • Centroid
    var out = Phaser.Geom.Triangle.Centroid(triangle);  // out: {x,y}\n
  • Incenter
    var out = Phaser.Geom.Triangle.InCenter(triangle);  // out: {x,y}\n// var out = Phaser.Geom.Triangle.InCenter(triangle, out);\n
  • Circumcenter
    var out = Phaser.Geom.Triangle.CircumCenter(triangle);  // out: {x,y}\n// var out = Phaser.Geom.Triangle.CircumCenter(triangle, out);\n
  • Circumcircle
    var out = Phaser.Geom.Triangle.CircumCircle(triangle);  // out: a circle object\n// var out = Phaser.Geom.Triangle.CircumCircle(triangle, out);\n
  • Type:
    var type = triangle.type; // 6\n
"},{"location":"geom-triangle/#points-shape","title":"Point(s) & shape","text":"
  • Get point at shape's edge
    var point = triangle.getPoint(t);  // t : 0 ~ 1 (angle/360)\n// var point = triangle.getPoint(t, point);  // modify point\n
  • Get a random point inside shape
    var point = triangle.getRandomPoint();\n// var point = triangle.getRandomPoint(point);  // modify point\n
  • Get points around shape's edge
    var points = triangle.getPoints(quantity);\n// var points = triangle.getPoints(quantity, null, points);  // push points\n
    or calculate quantity from steps
    var points = triangle.getPoints(false, step);\n// var points = triangle.getPoints(false, step, points);  // push points\n
    • points : an array of point
  • Point is inside shape
    var isInside = triangle.contains(x, y);\n
    or
    var isInside = Phaser.Geom.Triangle.ContainsPoint(triangle, point);\n
    • Points inside shape
      var out = Phaser.Geom.Triangle.ContainsArray(triangle, points, returnFirst);\n// var out = Phaser.Geom.Triangle.ContainsArray(triangle, points, returnFirst, out);\n
      • out : Points inside triangle
      • returnFirst : True to get fist matched point
"},{"location":"geom-triangle/#equal","title":"Equal","text":"
var isEqual = Phaser.Geom.Triangle.Equals(triangle0, triangle1);\n

Position and radius are equal.

"},{"location":"geom-triangle/#intersection","title":"Intersection","text":""},{"location":"geom-triangle/#triangle-to-circle","title":"Triangle to circle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.TriangleToCircle(triangle, circle);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetTriangleToCircle(triangle, circle);\n// var out = Phaser.Geom.Intersects.GetTriangleToCircle(triangle, circle, out);\n
"},{"location":"geom-triangle/#triangle-to-rectangle","title":"Triangle to rectangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.RectangleToTriangle(rect, triangle);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetRectangleToTriangle(rect, triangle);\n// var out = Phaser.Geom.Intersects.GetRectangleToTriangle(rect, triangle, out);\n
"},{"location":"geom-triangle/#triangle-to-triangle","title":"Triangle to triangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.TriangleToTriangle(triangleA, triangleB);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetTriangleToTriangle(triangleA, triangleB);\n// var out = Phaser.Geom.Intersects.GetTriangleToTriangle(triangleA, triangleB, out);\n
"},{"location":"geom-triangle/#triangle-to-line","title":"Triangle to line","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.TriangleToLine(triangle, line);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetTriangleToLine(triangle, line);\n// var out = Phaser.Geom.Intersects.GetTriangleToLine(triangle, line, out);\n
"},{"location":"gesture-overview/","title":"Overview","text":""},{"location":"gesture-overview/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-overview/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Object factories : scene.rexGestures.add.xxx(config)
"},{"location":"gesture-overview/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Object factories : scene.rexGestures.add.xxx(config)
"},{"location":"gesture-overview/#list-of-gesture-plugins","title":"List of gesture plugins","text":""},{"location":"gesture-overview/#one-pointer-gesture","title":"One pointer gesture","text":"
  • Tap
  • Press
  • Swipe
  • Pan
"},{"location":"gesture-overview/#two-pointers-gesture","title":"Two pointers gesture","text":"
  • Pinch
  • Rotate
"},{"location":"gesture-pan/","title":"Pan","text":""},{"location":"gesture-pan/#introduction","title":"Introduction","text":"

Get pan events of a game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"gesture-pan/#live-demos","title":"Live demos","text":"
  • Camera scroll
  • Pan & rotate
"},{"location":"gesture-pan/#usage","title":"Usage","text":"

Sample code

"},{"location":"gesture-pan/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-pan/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Add pan input
    var pan = scene.rexGestures.add.pan(config);\n// var pan = scene.rexGestures.add.pan(gameObject, config);\n
"},{"location":"gesture-pan/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add pan input
    var pan = scene.rexGestures.add.pan(config);\n// var pan = scene.rexGestures.add.pan(gameObject, config);\n
"},{"location":"gesture-pan/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Pan } from 'phaser3-rex-plugins/plugins/gestures.js';\n
  • Add pan input
    var pan = new Pan(scene, config);\n// var pan = new Pan(gameObject, config);\n
"},{"location":"gesture-pan/#create-instance","title":"Create instance","text":"
  • Pan input
    var pan = scene.rexGestures.add.pan({\n// enable: true,\n// bounds: undefined,\n\n// threshold: 10,\n});\n
    • enable : Set false to disable input events.
    • bounds : Touch detecting area rectangle, if game obect is not given.
      • undefined : Ignore this feature, default behavior.
    • threshold : Minimal movement when pointer is down.
  • Pan behavior of game object
    var pan = scene.rexGestures.add.pan(gameObject, {\n// enable: true,\n\n// threshold: 10,\n});\n
"},{"location":"gesture-pan/#enable","title":"Enable","text":"
  • Get
    var enable = pan.enable;  // enable: true, or false\n
  • Set
    pan.setEnable(enable);  // enable: true, or false\n// pan.enable = enable;\n
  • Toggle
    pan.toggleEnable();\n
"},{"location":"gesture-pan/#events","title":"Events","text":""},{"location":"gesture-pan/#pan","title":"Pan","text":"
pan.on('pan', function(pan, gameObject, lastPointer){\n}, scope);\n
  • pan.dx, pan.dy : Vector from previous pointer to current pointer.
  • pan.dWorldX, pan.dWorld : Vector from previous pointer to current pointer, in world position. i.e, including camera-zoom.
  • pan.worldX, pan.worldY : World position of current pointer.
  • pan.x, pan.y : Scene position of current pointer.
  • gameObject, pan.gameObject : Parent gameobject of this pan behavior.
  • lastPointer : Last touch pointer.
"},{"location":"gesture-pan/#pan-start","title":"Pan start","text":"
pan.on('panstart', function(pan, gameObject, lastPointer){\n}, scope);\n
  • pan.startWorldX, pan.startWorldY : World position of pan-start pointer.
  • pan.startX, pan.startY : Scene position of pan-start pointer.
  • gameObject, pan.gameObject : Parent gameobject of this pan behavior.
  • lastPointer : Last touch pointer.
"},{"location":"gesture-pan/#pan-end","title":"Pan end","text":"
pan.on('panend', function(pan, gameObject, lastPointer){\n}, scope);\n
  • pan.endWorldX, pan.endWorldY : World position of pan-end pointer.
  • pan.endX, pan.endY : Scene position of pan-end pointer.
  • gameObject, pan.gameObject : Parent gameobject of this pan behavior.
  • lastPointer : Last touch pointer.
"},{"location":"gesture-pan/#is-panned","title":"Is panned","text":"
var isPanned = pan.isPanned;\n

Return true if panned.

"},{"location":"gesture-pan/#is-pointer-inside-another-game-object","title":"Is pointer inside another game object","text":"

Under any pan event,

pan.on('panend', function(pan){\nvar isPointerInsideGameObject = pan.isPointerInGameObject(anotherGameObject);\n});\n
"},{"location":"gesture-pan/#other-properties","title":"Other properties","text":"
  • Drag threshold
    • Get
      var dragThreshold = pan.dragThreshold;\n
    • Set
      pan.setDragThreshold(dragThreshold);\n// pan.dragThreshold = dragThreshold;\n
  • Detect bounds
    • Get
      var bounds = pan.bounds;\n
    • Set
      pan.setDetectBounds(bounds);\n// pan.bounds = bounds;\n
"},{"location":"gesture-pinch/","title":"Pinch","text":""},{"location":"gesture-pinch/#introduction","title":"Introduction","text":"

Get scale factor from 2 dragging touch pointers.

  • Author: Rex
  • Member of scene
"},{"location":"gesture-pinch/#live-demos","title":"Live demos","text":"

Pinch-zoom

"},{"location":"gesture-pinch/#usage","title":"Usage","text":"

Sample code

"},{"location":"gesture-pinch/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-pinch/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Add pinch input
    var pinch = scene.rexGestures.add.pinch(config);\n// var pinch = scene.rexGestures.add.pinch(gameObject, config);\n
"},{"location":"gesture-pinch/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add pinch input
    var pinch = scene.rexGestures.add.pinch(config);\n// var pinch = scene.rexGestures.add.pinch(gameObject, config);\n
"},{"location":"gesture-pinch/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Pinch } from 'phaser3-rex-plugins/plugins/gestures.js';\n
  • Add pinch input
    var pinch = new Pinch(scene, config);\n// var pinch = new Pinch(gameObject, config);\n
"},{"location":"gesture-pinch/#create-instance","title":"Create instance","text":"
  • Pinch input
    var pinch = scene.rexGestures.add.pinch({\n// enable: true,\n// bounds: undefined,\n\n// threshold: 0,\n});\n
    • enable : Set false to disable input events.
    • bounds : A rectangle object or undefined (to use game window as rectangle object), for detecting the position of cursor.
    • threshold : Fire pinch events after dragging distances of catched pointers are larger than this threshold.
  • Pinch behavior of game object
    var pan = scene.rexGestures.add.pinch(gameObject, {\n// enable: true,\n// bounds: undefined,\n\n// threshold: 0,\n});\n
    • Start pinching when pointer-down on this game object.
"},{"location":"gesture-pinch/#enable","title":"Enable","text":"
  • Get
    var enable = pinch.enable;  // enable: true, or false\n
  • Set
    pinch.setEnable(enable);  // enable: true, or false\n// pinch.enable = enable;\n
  • Toggle
    pinch.toggleEnable();\n
"},{"location":"gesture-pinch/#events","title":"Events","text":""},{"location":"gesture-pinch/#on-dragging","title":"On dragging","text":"
  • On dragging 1st touch pointer, fired when 1st touch pointer is moving
    pinch.on('drag1', function(pinch) {\n// var drag1Vector = pinch.drag1Vector; // drag1Vector: {x, y}\n}, scope);\n
    • pinch.drag1Vector : Drag vector from prevoius touch position to current touch position of 1st catched touch pointer.
  • On dragging 2 touch pointers, fired when any catched touch pointer moved.
    pinch.on('pinch', function(pinch) {\n// var scaleFactor = pinch.scaleFactor;\n// gameObject.scaleX *= scaleFactor;\n// gameObject.scaleY *= scaleFactor;\n}, scope);\n
    • pinch.scaleFactor : Rate of distance change between 2 catched touch pointers.
"},{"location":"gesture-pinch/#on-drag-start-on-drag-end","title":"On drag start, on drag end","text":"
  • On drag 1 touch pointer start, fired when catching 1st touch pointer.
    pinch.on('drag1start', function(pinch) {\n\n}, scope);\n
  • On drag 1 touch pointer end, fired when releasing the last one catched touch pointer.
    pinch.on('drag1end', function(pinch) {\n\n}, scope);\n
  • On drag 2 touch pointers start, fired when catching 2 touch pointers.
    pinch.on('pinchstart', function(pinch) {\n\n}, scope);\n
  • On drag 2 touch pointers end, fired when releasing any catched touch pointer.
    pinch.on('pinchend', function(pinch) {\n\n}, scope);\n
"},{"location":"gesture-pinch/#scale-factor","title":"Scale factor","text":"
var scaleFactor = pinch.scaleFactor;\n

Rate of distance change between 2 catched touch pointers. (i.e current distance between 2 catched touch pointers / previous distance ).

"},{"location":"gesture-pinch/#drag-vector-of-1st-touch-pointer","title":"Drag vector of 1st touch pointer","text":"
var drag1Vector = pinch.drag1Vector; // {x, y}\n
"},{"location":"gesture-pinch/#catched-touch-pointers","title":"Catched touch pointers","text":"
  • Pointer 0, available when state is 1
    var pointer0 = pinch.pointers[0];\n
    • Position of pointer
      var x = pointer0.x;\nvar y = pointer0.y;\nvar worldX = pointer0.worldX;\nvar worldY = pointer0.worldY;\n
  • Pointer 1, available when state is 2
    var pointer1 = pinch.pointers[1];\n
"},{"location":"gesture-pinch/#is-pinched","title":"Is pinched","text":"
var isPinched = pinch.isPinched;\n

Return true if pinched.

"},{"location":"gesture-pinch/#is-pointer-inside-another-game-object","title":"Is pointer inside another game object","text":"

Under any pinch event,

pinch.on('pinch', function(pinch) {\nvar isPointer0InsideGameObject = pinch.isPointer0InGameObject(anotherGameObject);\nvar isPointer1InsideGameObject = pinch.isPointer1InGameObject(anotherGameObject);\n});\n
"},{"location":"gesture-pinch/#other-properties","title":"Other properties","text":"
  • Drag threshold
    • Get
      var dragThreshold = pinch.dragThreshold;\n
    • Set
      pinch.setDragThreshold(dragThreshold);\n// pinch.dragThreshold = dragThreshold;\n
  • Detect bounds
    • Get
      var bounds = pinch.bounds;\n
    • Set
      pinch.setDetectBounds(bounds);\n// pinch.bounds = bounds;\n
"},{"location":"gesture-press/","title":"Press","text":""},{"location":"gesture-press/#introduction","title":"Introduction","text":"

Get press events of a game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"gesture-press/#live-demos","title":"Live demos","text":"
  • Press object
"},{"location":"gesture-press/#usage","title":"Usage","text":"

Sample code

"},{"location":"gesture-press/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-press/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Add press input
    var press = scene.rexGestures.add.press(config);\n// var press = scene.rexGestures.add.press(gameObject, config);\n
"},{"location":"gesture-press/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add press input
    var press = scene.rexGestures.add.press(config);\n// var press = scene.rexGestures.add.press(gameObject, config);\n
"},{"location":"gesture-press/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Press } from 'phaser3-rex-plugins/plugins/gestures.js';\n
  • Add press input
    var press = new Press(scene, config);\n// var press = new Press(gameObject, config);\n
"},{"location":"gesture-press/#create-instance","title":"Create instance","text":"
  • Press input
    var press = scene.rexGestures.add.press({\n// enable: true,\n// bounds: undefined,\n\n// time: 251,\n// threshold: 9,\n});\n
    • enable : Set false to disable input events.
    • bounds : Touch detecting area rectangle, if game obect is not given.
      • undefined : Ignore this feature, default behavior.
    • time : Minimal time of the pointer to be pressed.
    • threshold : Minimal movement when pointer is down.
  • Press behavior of game object
    var press = scene.rexGestures.add.press(gameObject, {\n// enable: true,\n\n// time: 251,\n// threshold: 9,\n});\n
"},{"location":"gesture-press/#enable","title":"Enable","text":"
  • Get
    var enable = press.enable;  // enable: true, or false\n
  • Set
    press.setEnable(enable);  // enable: true, or false\n// press.enable = enable;\n
  • Toggle
    press.toggleEnable();\n
"},{"location":"gesture-press/#events","title":"Events","text":""},{"location":"gesture-press/#pressing-start","title":"Pressing start","text":"
press.on('pressstart', function(press, gameObject, lastPointer){\n}, scope);\n
  • press.gameObject : Parent gameobject of this press behavior.
  • press.worldX, press.worldY : World position of pressing start.
  • press.x, press.y : Scene position of pressing start.
  • gameObject, press.gameObject : Parent gameobject of this press behavior.
  • lastPointer : Last touch pointer.
"},{"location":"gesture-press/#pressing-end","title":"Pressing end","text":"
press.on('pressend', function(press, gameObject, lastPointer){\n}, scope);\n
"},{"location":"gesture-press/#is-pressed","title":"Is pressed","text":"
var isPressed = press.isPressed;\n

Return true if pressed.

"},{"location":"gesture-press/#is-pointer-inside-another-game-object","title":"Is pointer inside another game object","text":"

Under any press event,

press.on('pressstart', function(press){\nvar isPointerInsideGameObject = press.isPointerInGameObject(anotherGameObject);\n});\n
"},{"location":"gesture-press/#other-properties","title":"Other properties","text":"
  • Hold time
    • Get
      var holdTime = press.holdTime;\n
    • Set
      press.setHoldTime(holdTime);\n// press.holdTime = holdTime;\n
  • Drag threshold
    • Get
      var dragThreshold = press.dragThreshold;\n
    • Set
      press.setDragThreshold(dragThreshold);\n// press.dragThreshold = dragThreshold;\n
  • Detect bounds
    • Get
      var bounds = press.bounds;\n
    • Set
      press.setDetectBounds(bounds);\n// press.bounds = bounds;\n
"},{"location":"gesture-rotate/","title":"Rotate","text":""},{"location":"gesture-rotate/#introduction","title":"Introduction","text":"

Get spin angle from 2 dragging touch pointers.

  • Author: Rex
  • Member of scene
"},{"location":"gesture-rotate/#live-demos","title":"Live demos","text":"
  • Rotate & rotate
"},{"location":"gesture-rotate/#usage","title":"Usage","text":"

Sample code

"},{"location":"gesture-rotate/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-rotate/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Add rotate input
    var rotate = scene.rexGestures.add.rotate(config);\n// var rotate = scene.rexGestures.add.rotate(gameObject, config);\n
"},{"location":"gesture-rotate/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add rotate input
    var rotate = scene.rexGestures.add.rotate(config);\n// var rotate = scene.rexGestures.add.rotate(gameObject, config);\n
"},{"location":"gesture-rotate/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Rotate } from 'phaser3-rex-plugins/plugins/gestures.js';\n
  • Add rotate input
    var rotate = new Rotate(scene, config);\n// var rotate = new Rotate(gameObject, config);\n
"},{"location":"gesture-rotate/#create-instance","title":"Create instance","text":"
  • Rotate input
    var rotate = scene.rexGestures.add.rotate({\n// enable: true,\n// bounds: undefined,\n\n// threshold: 0,\n});\n
    • enable : Set false to disable input events.
    • bounds : A rectangle object or undefined (to use game window as rectangle object), for detecting the position of cursor.
    • threshold : Fire rotate events after dragging distances of catched pointers are larger than this threshold.
  • Rotate behavior of game object
    var rotate = scene.rexGestures.add.rotate(gameObject, {\n// enable: true,\n// bounds: undefined,\n\n// threshold: 0,\n});\n
    • Start rotation when pointer-down on this game object.
"},{"location":"gesture-rotate/#enable","title":"Enable","text":"
  • Get
    var enable = rotate.enable;  // enable: true, or false\n
  • Set
    rotate.setEnable(enable);  // enable: true, or false\n// rotate.enable = enable;\n
  • Toggle
    rotate.toggleEnable();\n
"},{"location":"gesture-rotate/#events","title":"Events","text":""},{"location":"gesture-rotate/#on-dragging","title":"On dragging","text":"
  • On dragging 1st touch pointer, fired when 1st touch pointer is moving
    rotate.on('drag1', function(rotate) {\n// var drag1Vector = rotate.drag1Vector; // drag1Vector: {x, y}\n}, scope);\n
    • rotate.drag1Vector : Drag vector from prevoius touch position to current touch position of 1st catched touch pointer.
  • On dragging 2 touch pointers, fired when any catched touch pointer moved.
    rotate.on('rotate', function(rotate) {\n// rotate.spinObject(gameObejects);\n// var angle = rotate.rotation;\n}, scope);\n
    • rotate.spinObject(gameObejects) : Drag and spin an array of game object, or a game object around current center of 2 dragging pointers.
    • rotate.rotation : Return spin angle of 2 dragging pointers, in radius.
"},{"location":"gesture-rotate/#on-drag-start-on-drag-end","title":"On drag start, on drag end","text":"
  • On drag 1 touch pointer start, fired when catching 1st touch pointer.
    rotate.on('drag1start', function(rotate) {\n\n}, scope);\n
  • On drag 1 touch pointer end, fired when releasing the last one catched touch pointer.
    rotate.on('drag1end', function(rotate) {\n\n}, scope);\n
  • On drag 2 touch pointers start, fired when catching 2 touch pointers.
    rotate.on('rotatestart', function(rotate) {\n\n}, scope);\n
  • On drag 2 touch pointers end, fired when releasing any catched touch pointer.
    rotate.on('rotateend', function(rotate) {\n\n}, scope);\n
"},{"location":"gesture-rotate/#spin-game-object","title":"Spin game object","text":"
rotate.spinObject(gameObejects);\n

Drag and spin game objects around current center of 2 dragging pointers. Uses this function under 'rotate' event.

  • gameObejects : An array of game object, or a game object.
"},{"location":"gesture-rotate/#spin-angle","title":"Spin angle","text":"
var angle = rotate.rotation;\n

Spin angle of 2 dragging pointers, in radius.

"},{"location":"gesture-rotate/#drag-vector-of-1st-touch-pointer","title":"Drag vector of 1st touch pointer","text":"
var drag1Vector = rotate.drag1Vector; // {x, y}\n
"},{"location":"gesture-rotate/#catched-touch-pointers","title":"Catched touch pointers","text":"
  • Pointer 0, available when state is 1
    var pointer0 = rotate.pointers[0];\n
    • Position of pointer
      var x = pointer0.x;\nvar y = pointer0.y;\nvar worldX = pointer0.worldX;\nvar worldY = pointer0.worldY;\n
  • Pointer 1, available when state is 2
    var pointer0 = rotate.pointers[1];\n
"},{"location":"gesture-rotate/#is-rotated","title":"Is rotated","text":"
var isRotated = rotate.isRotated;\n

Return true if pinched.

"},{"location":"gesture-rotate/#is-pointer-inside-another-game-object","title":"Is pointer inside another game object","text":"

Under any rotate event,

rotate.on('rotate', function(rotate) {\nvar isPointer0InsideGameObject = rotate.isPointer0InGameObject(anotherGameObject);\nvar isPointer1InsideGameObject = rotate.isPointer1InGameObject(anotherGameObject);\n});\n
"},{"location":"gesture-rotate/#other-properties","title":"Other properties","text":"
  • Drag threshold
    • Get
      var dragThreshold = rotate.dragThreshold;\n
    • Set
      rotate.setDragThreshold(dragThreshold);\n// rotate.dragThreshold = dragThreshold;\n
  • Detect bounds
    • Get
      var bounds = rotate.bounds;\n
    • Set
      rotate.setDetectBounds(bounds);\n// rotate.bounds = bounds;\n
"},{"location":"gesture-swipe/","title":"Swipe","text":""},{"location":"gesture-swipe/#introduction","title":"Introduction","text":"

Get swipe events of a game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"gesture-swipe/#live-demos","title":"Live demos","text":"
  • Swipe
"},{"location":"gesture-swipe/#usage","title":"Usage","text":"

Sample code

"},{"location":"gesture-swipe/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-swipe/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Add swipe input
    var swipe = scene.rexGestures.add.swipe(config);\n// var swipe = scene.rexGestures.add.swipe(gameObject, config);\n
"},{"location":"gesture-swipe/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add swipe input
    var swipe = scene.rexGestures.add.swipe(config);\n// var swipe = scene.rexGestures.add.swipe(gameObject, config);\n
"},{"location":"gesture-swipe/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Swipe } from 'phaser3-rex-plugins/plugins/gestures.js';\n
  • Add swipe input
    var swipe = new Swipe(scene, config);\n// var swipe = new Swipe(gameObject, config);\n
"},{"location":"gesture-swipe/#create-instance","title":"Create instance","text":"
  • Swipe input
    var swipe = scene.rexGestures.add.swipe({\n// enable: true,\n// bounds: undefined,\n\n// threshold: 10,\n// velocityThreshold: 1000,\n// dir: '8dir',\n});\n
    • enable : Set false to disable input events.
    • bounds : Touch detecting area rectangle, if game obect is not given.
      • undefined : Ignore this feature, default behavior.
    • time : Max time of the pointer to be down.
    • threshold : Minimal movement when pointer is down.
    • velocityThreshold : Minimal dragging speed.
    • dir :
      • 'up&down', or 0 : Get up or down state only.
      • 'left&right', or 1 : Get left or right state only.
      • '4dir', or 2 : Get up, down, left or right state.
      • '8dir', or 3 : Get up, up/left, up/right, down, down/left, down/right, left, or right state.
  • Swipe behavior of game object
    var swipe = scene.rexGestures.add.swipe(gameObject, {\n// enable: true,\n\n// threshold: 10,\n// velocityThreshold: 1000,\n// direction: '8dir',\n});\n
"},{"location":"gesture-swipe/#enable","title":"Enable","text":"
  • Get
    var enable = swipe.enable;  // enable: true, or false\n
  • Set
    swipe.setEnable(enable);  // enable: true, or false\n// swipe.enable = enable;\n
  • Toggle
    swipe.toggleEnable();\n
"},{"location":"gesture-swipe/#events","title":"Events","text":""},{"location":"gesture-swipe/#swipe","title":"Swipe","text":"
swipe.on('swipe', function(swipe, gameObject, lastPointer){\n}, scope);\n
  • swipe.left, swipe.right, swipe.up, swipe.down : Swipe direction states.
  • swipe.worldX, swipe.worldY : World position of swiping start.
  • swipe.x, swipe.y : Scene position of swiping start.
  • swipe.dragVelocity : Velocity of dragging.
  • gameObject, swipe.gameObject : Parent gameobject of this pan behavior.
  • lastPointer : Last touch pointer.
"},{"location":"gesture-swipe/#is-swiped","title":"Is swiped","text":"
var isSwiped = swipe.isSwiped;\n

Return true if panning.

"},{"location":"gesture-swipe/#is-pointer-inside-another-game-object","title":"Is pointer inside another game object","text":"

Under any swipe event,

swipe.on('swipe', function(swipe){\nvar isPointerInsideGameObject = swipe.isPointerInGameObject(anotherGameObject);\n});\n
"},{"location":"gesture-swipe/#other-properties","title":"Other properties","text":"
  • Drag threshold
    • Get
      var dragThreshold = swipe.dragThreshold;\n
    • Set
      swipe.setDragThreshold(dragThreshold);\n// swipe.dragThreshold = dragThreshold;\n
  • Velocity threshold
    • Get
      var velocityThreshold = swipe.velocityThreshold;\n
    • Set
      swipe.setVelocityThreshold(velocityThreshold);\n// swipe.velocityThreshold = velocityThreshold;\n
  • Direction mode
    • Get
      var dirMode = swipe.dirMode;  // 0,1,2,3\n
    • Set
      swipe.setDirectionMode(dirMode);  // 0,1,2,3,'up&down','left&right','4dir','8dir'\n// swipe.dirMode = dirMode;  // 0,1,2,3\n
  • Detect bounds
    • Get
      var bounds = swipe.bounds;\n
    • Set
      swipe.setDetectBounds(bounds);\n// swipe.bounds = bounds;\n
"},{"location":"gesture-tap/","title":"Tap","text":""},{"location":"gesture-tap/#introduction","title":"Introduction","text":"

Get tap/multi-taps events of a game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"gesture-tap/#live-demos","title":"Live demos","text":"
  • Tap object
"},{"location":"gesture-tap/#usage","title":"Usage","text":"

Sample code

"},{"location":"gesture-tap/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-tap/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Add tap input
    var tap = scene.rexGestures.add.tap(config);\n// var tap = scene.rexGestures.add.tap(gameObject, config);\n
"},{"location":"gesture-tap/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add tap input
    var tap = scene.rexGestures.add.tap(config);\n// var tap = scene.rexGestures.add.tap(gameObject, config);\n
"},{"location":"gesture-tap/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Tap } from 'phaser3-rex-plugins/plugins/gestures.js';\n
  • Add tap input
    var tap = new Tap(scene, config);\n// var tap = new Tap(gameObject, config);\n
"},{"location":"gesture-tap/#create-instance","title":"Create instance","text":"
  • Tap input
    var tap = scene.rexGestures.add.tap({\n// enable: true,\n// bounds: undefined,\n\n// time: 250,\n// tapInterval: 200,\n// threshold: 9,\n// tapOffset: 10,\n\n// taps: undefined,\n// minTaps: undefined,\n// maxTaps: undefined,\n});\n
    • enable : Set false to disable input events.
    • bounds : Touch detecting area rectangle, if game obect is not given.
      • undefined : Ignore this feature, default behavior.
    • time : Max time of the pointer to be down.
    • tapInterval : Max time between the multi-tap taps.
    • threshold : Minimal movement when pointer is down.
    • tapOffset : A multi-tap can be a bit off the initial position.
    • taps : Fire tap event only when taps count reaches this value.
      • undefined : Fire tap event only when tapped end. i.e pointer-up time exceeds tapInterval.
    • minTaps : Fire tap event only when taps count is larger than this value.
      • undefined : Don't check taps count.
    • maxTaps : Fire tap event only when taps count is less than this value.
      • undefined : Don't check taps count.
  • Tap behavior of game object
    var tap = scene.rexGestures.add.tap(gameObject, {\n// enable: true,\n\n// time: 250,\n// tapInterval: 200,\n// threshold: 9,\n// tapOffset: 10,\n\n// taps: undefined,\n// minTaps: undefined,\n// maxTaps: undefined,\n});\n
"},{"location":"gesture-tap/#enable","title":"Enable","text":"
  • Get
    var enable = tap.enable;  // enable: true, or false\n
  • Set
    tap.setEnable(enable);  // enable: true, or false\n// tap.enable = enable;\n
  • Toggle
    tap.toggleEnable();\n
"},{"location":"gesture-tap/#events","title":"Events","text":""},{"location":"gesture-tap/#tap","title":"Tap","text":"
tap.on('tap', function(tap, gameObject, lastPointer){\n}, scope);\n
  • tap.tapsCount : Taps count.
  • gameObject, tap.gameObject : Parent gameobject of this tap behavior.
  • tap.worldX, tap.worldY : World position of first tapping.
  • tap.x, tap.y : Scene position of first tapping.
  • lastPointer : Last touch pointer.
tap.on(tapsCount + 'tap', function(tap, gameObject, lastPointer){\n}, scope);\n
  • tapsCount + 'tap' : 1tap, 2tap, 3tap, etc ...
"},{"location":"gesture-tap/#tapping-start","title":"Tapping start","text":"

Each pointer-down will increase taps count and fire tappingstart event.

tap.on('tappingstart', function(tap, gameObject, lastPointer){\n}, scope);\n
"},{"location":"gesture-tap/#is-tapped","title":"Is tapped","text":"
var isTapped = tap.isTapped;\n

Return true if tapped end.

"},{"location":"gesture-tap/#is-pointer-inside-another-game-object","title":"Is pointer inside another game object","text":"

Under any tap event,

tap.on('tap', function(tap){\nvar isPointerInsideGameObject = tap.isPointerInGameObject(anotherGameObject);\n});\n
"},{"location":"gesture-tap/#other-properties","title":"Other properties","text":"
  • Hold time
    • Get
      var holdTime = tap.holdTime;\n
    • Set
      tap.setHoldTime(holdTime);\n// tap.holdTime = holdTime;\n
  • Tap interval
    • Get
      var tapInterval = tap.tapInterval;\n
    • Set
      tap.setTapInterval(tapInterval);\n// tap.tapInterval = tapInterval;\n
  • Drag threshold
    • Get
      var dragThreshold = tap.dragThreshold;\n
    • Set
      tap.setDragThreshold(dragThreshold);\n// tap.dragThreshold = dragThreshold;\n
  • Tap offset
    • Get
      var tapOffset = tap.tapOffset;\n
    • Set
      tap.setTapOffset(tapOffset);\n// tap.tapOffset = tapOffset;\n
  • Max taps
    • Get
      var maxTaps = tap.maxTaps;\n
    • Set
      tap.setMaxTaps(maxTaps);\n// tap.maxTaps = maxTaps;\n
  • Min taps
    • Get
      var minTaps = tap.minTaps;\n
    • Set
      tap.setMinTaps(minTaps);\n// tap.minTaps = minTaps;\n
  • Taps
    taps.setTaps(taps);\n// taps.setTaps(minTaps, maxTaps);\n
  • Detect bounds
    • Get
      var bounds = taps.bounds;\n
    • Set
      taps.setDetectBounds(bounds);\n// taps.bounds = bounds;\n
"},{"location":"graphics/","title":"Graphics","text":""},{"location":"graphics/#introduction","title":"Introduction","text":"

Drawing on webgl or canvas, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"graphics/#usage","title":"Usage","text":""},{"location":"graphics/#add-graphics-object","title":"Add graphics object","text":"
var graphics = scene.add.graphics();\n

or

var graphics = scene.add.graphics({\nx: 0,\ny: 0,\n\n// lineStyle: {\n//     width: 1,\n//     color: 0xffffff,\n//     alpha: 1\n// },\n// fillStyle: {\n//     color: 0xffffff,\n//     alpha: 1\n// },\n\nadd: true\n});\n
"},{"location":"graphics/#custom-class","title":"Custom class","text":"
  • Define class
    class MyGraphics extends Phaser.GameObjects.Graphics {\nconstructor(scene, options) {\nsuper(scene, options);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var graphics = new MyGraphics(scene, options);\n
"},{"location":"graphics/#drawing-commands","title":"Drawing commands","text":""},{"location":"graphics/#set-style","title":"Set style","text":"
  • Set default line style and fill style
    graphics.setDefaultStyles({\nlineStyle: {\nwidth: 1,\ncolor: 0xffffff,\nalpha: 1\n},\nfillStyle: {\ncolor: 0xffffff,\nalpha: 1\n}\n});\n
  • Set line style
    graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\n
  • Set fill style
    • Fill color
      graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\n
    • Fill gradient color (WebGL only)
      graphics.fillGradientStyle(topLeft, topRight, bottomLeft, bottomRight, alpha);  // alpha= 1\n// graphics.fillGradientStyle(topLeft, topRight, bottomLeft, bottomRight, alphaTopLeft, alphaTopRight, alphaBottomLeft, alphaBottomRight);\n
      • topLeft : The tint being applied to the top-left of the Game Object.
      • topRight : The tint being applied to the top-right of the Game Object.
      • bottomLeft : The tint being applied to the bottom-left of the Game Object.
      • bottomRight : The tint being applied to the bottom-right of the Game Object.
      • alphaTopLeft : The top left alpha value.
      • alphaTopRight : The top right alpha value.
      • alphaBottomLeft : The bottom left alpha value.
      • alphaBottomRight : The bottom right alpha value.
"},{"location":"graphics/#clear","title":"Clear","text":"
graphics.clear();\n
"},{"location":"graphics/#path","title":"Path","text":"
graphics.beginPath();\ngraphics.closePath();\ngraphics.fillPath(); // = graphics.fill()\ngraphics.strokePath(); // = graphics.stroke()\n
"},{"location":"graphics/#rectangle","title":"Rectangle","text":"
graphics.fillRectShape(rect); // rect: {x, y, width, height}\ngraphics.fillRect(x, y, width, height);\ngraphics.strokeRectShape(rect);  // rect: {x, y, width, height}\ngraphics.strokeRect(x, y, width, height);\n
"},{"location":"graphics/#rounded-rectangle","title":"Rounded rectangle","text":"
graphics.fillRoundedRect(x, y, width, height, radius);\ngraphics.strokeRoundedRect(x, y, width, height, radius);\n
  • radius : number or an object {tl, tr, bl, br},
    • Positive value : Convex corner.
    • Negative value : Concave corner.
"},{"location":"graphics/#triangle","title":"Triangle","text":"
graphics.fillTriangleShape(triangle); // triangle: {x1, y1, x2, y2, x3, y3}\ngraphics.fillTriangle(x1, y1, x2, y2, x3, y3);\ngraphics.strokeTriangleShape(triangle); // triangle: {x1, y1, x2, y2, x3, y3}\ngraphics.strokeTriangle(x1, y1, x2, y2, x3, y3);\n
"},{"location":"graphics/#point","title":"Point","text":"
graphics.fillPointShape(point, size); // point: {x, y}\ngraphics.fillPoint(x, y, size);\n
"},{"location":"graphics/#line","title":"Line","text":"
graphics.strokeLineShape(line); // line: {x1, y1, x2, y2}\ngraphics.lineBetween(x1, y1, x2, y2);\ngraphics.lineTo(x, y);\ngraphics.moveTo(x, y);\n
"},{"location":"graphics/#lines","title":"Lines","text":"
graphics.strokePoints(points, closeShape, closePath, endIndex);  // points: [{x, y}, ...]\ngraphics.fillPoints(points, closeShape, closePath, endIndex);  // points: [{x, y}, ...]\n
  • points : Array of {x, y}
  • closeShape : When true, the shape is closed by joining the last point to the first point.
  • closePath : When true, the path is closed before being stroked.
  • endIndex : The index of points to stop drawing at. Defaults to points.length.
"},{"location":"graphics/#circle","title":"Circle","text":"
graphics.fillCircleShape(circle); // circle: {x, y, radius}\ngraphics.fillCircle(x, y, radius);\ngraphics.strokeCircleShape(circle);  // circle: {x, y, radius}\ngraphics.strokeCircle(x, y, radius);\n

Draw or fill circle shape by points.

"},{"location":"graphics/#ellipse","title":"Ellipse","text":"
graphics.strokeEllipseShape(ellipse, smoothness);   // ellipse: Phaser.Geom.Ellipse\ngraphics.strokeEllipse(x, y, width, height, smoothness);\ngraphics.fillEllipseShape(ellipse, smoothness);    // ellipse: Phaser.Geom.Ellipse\ngraphics.fillEllipse(x, y, width, height, smoothness);\n

Draw or fill ellipse shape by points.

"},{"location":"graphics/#arc","title":"Arc","text":"
graphics.arc(x, y, radius, startAngle, endAngle, anticlockwise);\ngraphics.arc(x, y, radius, startAngle, endAngle, anticlockwise, overshoot);\n

Draw arc curve by points.

"},{"location":"graphics/#pie-chart-slice","title":"Pie-chart slice","text":"
graphics.slice(x, y, radius, startAngle, endAngle, anticlockwise);\ngraphics.slice(x, y, radius, startAngle, endAngle, anticlockwise, overshoot);\n

Draw pie-chart slice shape by points.

Fill this shape

graphics.fillPath();\n
"},{"location":"graphics/#clear-pattern","title":"Clear pattern","text":"
graphics.setTexture();\n
"},{"location":"graphics/#transfer","title":"Transfer","text":"
graphics.save();\ngraphics.restore();\ngraphics.translateCanvas(x, y);\ngraphics.scaleCanvas(x, y);\ngraphics.rotateCanvas(radians);\n
"},{"location":"graphics/#generate-texture","title":"Generate texture","text":"
graphics.generateTexture(key, width, height);  // key: texture key\n
"},{"location":"graphics/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"graphics/#create-mask","title":"Create mask","text":"
var mask = graphics.createGeometryMask();\n

See mask

"},{"location":"graphics/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"gridalign/","title":"Quad/Hexagon grid align","text":""},{"location":"gridalign/#introduction","title":"Introduction","text":"

Align objects on quadrilateral or hexagon grid.

See also built-in grid-align.

  • Author: Rex
  • Methods
"},{"location":"gridalign/#usage","title":"Usage","text":"

Sample code

"},{"location":"gridalign/#install-plugin","title":"Install plugin","text":""},{"location":"gridalign/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexgridalignplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgridalignplugin.min.js', true);\n
  • Grid-align objects
    scene.plugins.get('rexgridalignplugin').quad(gameObjects, config);\nscene.plugins.get('rexgridalignplugin').hexagon(gameObjects, config);\n
"},{"location":"gridalign/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GridAlignPlugin from 'phaser3-rex-plugins/plugins/gridalign-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGridAlign',\nplugin: GridAlignPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Grid-align objects
    scene.plugins.get('rexGridAlign').quad(gameObjects, config);\nscene.plugins.get('rexGridAlign').hexagon(gameObjects, config);\n
"},{"location":"gridalign/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { QuadGridAlign, HexagonGridAlign } from 'phaser3-rex-plugins/plugins/gridalign.js';\n
  • Grid-align objects
    QuadGridAlign(gameObjects, config);\nHexagonGridAlign(gameObjects, config);\n
"},{"location":"gridalign/#quadrilateral-grid","title":"Quadrilateral grid","text":"
scene.plugins.get('rexGridAlign').quad(gameObjects, {\nwidth: -1,\nheight: -1,\ncellWidth: 1,\ncellHeight: 1,\ntype: 0,\nposition: Phaser.Display.Align.CENTER,\nx: 0,\ny: 0\n});\n
  • width : The width of the grid in items (not pixels). -1 means lay all items out horizontally, regardless of quantity.
  • height : The height of the grid in items (not pixels). -1 means lay all items out vertically, regardless of quantity.
  • cellWidth : The width of the cell, in pixels.
  • cellHeight : The height of the cell, in pixels.
  • type
    • 0, or orthogonal
    • 1, or isometric
  • position : The alignment position.
    • 0, or Phaser.Display.Align.TOP_LEFT
    • 1, or Phaser.Display.Align.TOP_CENTER
    • 2, or Phaser.Display.Align.TOP_RIGHT
    • 3, or Phaser.Display.Align.LEFT_TOP
    • 4, or Phaser.Display.Align.LEFT_CENTER
    • 5, or Phaser.Display.Align.LEFT_BOTTOM
    • 6, or Phaser.Display.Align.CENTER
    • 7, or Phaser.Display.Align.RIGHT_TOP
    • 8, or Phaser.Display.Align.RIGHT_CENTER
    • 9, or Phaser.Display.Align.RIGHT_BOTTOM
    • 10, or Phaser.Display.Align.BOTTOM_LEFT
    • 11, or Phaser.Display.Align.BOTTOM_CENTER
    • 12, or Phaser.Display.Align.BOTTOM_RIGHT
  • x, y : Position of first item.
"},{"location":"gridalign/#hexagon-grid","title":"Hexagon grid","text":"
scene.plugins.get('rexGridAlign').hexagon(gameObjects, {\nwidth: -1,\nheight: -1,\ncellWidth: 1,\ncellHeight: 1,\nstaggeraxis: 'x',\nstaggerindex: 'odd',\nposition: Phaser.Display.Align.CENTER,\nx: 0,\ny: 0\n});\n
  • width : The width of the grid in items (not pixels). -1 means lay all items out horizontally, regardless of quantity.
  • height : The height of the grid in items (not pixels). -1 means lay all items out vertically, regardless of quantity.
  • cellWidth : The width of the cell, in pixels.
  • cellHeight : The height of the cell, in pixels.
  • staggeraxis
    • 0, or y
    • 1, or x
  • staggerindex
    • 0, or even
    • 1, or odd
  • position : The alignment position.
    • 0, or Phaser.Display.Align.TOP_LEFT
    • 1, or Phaser.Display.Align.TOP_CENTER
    • 2, or Phaser.Display.Align.TOP_RIGHT
    • 3, or Phaser.Display.Align.LEFT_TOP
    • 4, or Phaser.Display.Align.LEFT_CENTER
    • 5, or Phaser.Display.Align.LEFT_BOTTOM
    • 6, or Phaser.Display.Align.CENTER
    • 7, or Phaser.Display.Align.RIGHT_TOP
    • 8, or Phaser.Display.Align.RIGHT_CENTER
    • 9, or Phaser.Display.Align.RIGHT_BOTTOM
    • 10, or Phaser.Display.Align.BOTTOM_LEFT
    • 11, or Phaser.Display.Align.BOTTOM_CENTER
    • 12, or Phaser.Display.Align.BOTTOM_RIGHT
  • x, y : Position of first item.
"},{"location":"gridalign/#types-of-hexagon-grid","title":"Types of hexagon grid","text":"

Reference

  • odd-r : staggeraxis = x, staggerindex = odd
  • even-r : staggeraxis = x, staggerindex = even
  • odd-q : staggeraxis = y, staggerindex = odd
  • even-q :staggeraxis = y, staggerindex = even
"},{"location":"gridcutimage/","title":"Grid cut image","text":""},{"location":"gridcutimage/#introduction","title":"Introduction","text":"

Grid cut image texture to frames, then create image game objects from these frames.

  • Author: Rex
  • Methods
"},{"location":"gridcutimage/#live-demos","title":"Live demos","text":"
  • Cut image
  • Cut rendertexture
"},{"location":"gridcutimage/#usage","title":"Usage","text":"

Sample code

"},{"location":"gridcutimage/#install-plugin","title":"Install plugin","text":""},{"location":"gridcutimage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexgridcutimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgridcutimageplugin.min.js', true);\n
  • Create images
    var images = scene.plugins.get('rexgridcutimageplugin').gridCut(gameObjects, columns, rows, config);\n
"},{"location":"gridcutimage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GridCutImagePlugin from 'phaser3-rex-plugins/plugins/gridcutimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGridCutImage',\nplugin: GridCutImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create images
    var images = scene.plugins.get('rexGridCutImage').gridCut(gameObjects, columns, rows, config);\n
"},{"location":"gridcutimage/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import GridCutImage from 'phaser3-rex-plugins/plugins/gridcutimage.js';\n
  • Create images
    var images = GridCutImage(gameObjects, columns, rows, config);\n
"},{"location":"gridcutimage/#grid-cut","title":"Grid cut","text":"
var cellImages = scene.plugins.get('rexGridCutImage').gridCut(gameObjects, columns, rows, {\n// createImageCallback: undefined,\n// ImageClass: Phaser.GameObjects.Image,\n\n// originX: 0.5,\n// originY: 0.5,\n// add: true,\n// align: true,\n// objectPool: undefined\n})\n
  • gameObjects : Target game object which has a texture, ex Image, RenderTexture.
  • columns, rows : Cut texture in columns x rows grids
  • createImageCallback : Custom callback to return an image game object, optional.
    function(scene, texture, frame) {\nreturn gameObject;\n}\n
    • texture : A texture object.
    • frame : Frame name.
  • ImageClass : Create image game object from this class. Default value is built-in Image class. Used when createImageCallback is undefined.
  • originX, originY : Origin of created image game objects
  • add :
    • true : Add these created image game objects to scene. Default value.
    • false : Don't add created image game objects to scene.
  • align :
    • true : Align position of created image game objects to target game object (gameObjects). Default value when add is set to true.
    • false : Don't set position of created image game objects. Default value when add is set to false.
  • objectPool : An array of image game objects, will reuse image game objects from this pool. Optional.
  • cellImages : Return image game objects.
"},{"location":"gridtable/","title":"Grid table","text":""},{"location":"gridtable/#introduction","title":"Introduction","text":"

Viewer of grid table, to manipulate game object of each visible cell.

  • Author: Rex
  • Game object
"},{"location":"gridtable/#live-demos","title":"Live demos","text":"
  • Grid table
  • Grid table & slider
  • Grid table & scroller
  • Grid table & slider & scroller
  • Horizontal scrolling
  • Varying cell height
"},{"location":"gridtable/#usage","title":"Usage","text":"

Sample code

"},{"location":"gridtable/#install-plugin","title":"Install plugin","text":""},{"location":"gridtable/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexgridtableplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgridtableplugin.min.js', true);\n
  • Add table object
    var table = scene.add.rexGridTable(x, y, width, height, config);\n
"},{"location":"gridtable/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GridTablePlugin from 'phaser3-rex-plugins/plugins/gridtable-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGridTablePlugin',\nplugin: GridTablePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add table object
    var table = scene.add.rexGridTable(x, y, width, height, config);\n
"},{"location":"gridtable/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import GridTable from 'phaser3-rex-plugins/plugins/gridtable.js';\n
  • Add table object
    var table = new GridTable(scene, x, y, width, height, config);\nscene.add.existing(table);\n
"},{"location":"gridtable/#create-instance","title":"Create instance","text":"
var table = scene.add.rexGridTable(x, y, width, height, {\nscrollMode: 0,        // 0|'v'|'vertical'|1|'h'|'horizontal'\ncellsCount: 0,\ncolumns: 1,\n// rows: 1,\ncellHeight: 30,\ncellWidth: 30,\n// fixedCellSize: false,\n\ncellVisibleCallback: null,\n// cellVisibleCallback: function (cell, cellContainer, table) {},\ncellVisibleCallbackScope: undefined,\nreuseCellContainer: false,\n\ncellInvisibleCallback: null,\n// cellInvisibleCallback: function(cell) {},\ncellInvisibleCallbackScope: undefined,\nclampTableOXY: true,\n\nmask: {\npadding: 0, // or {left, right, top, bottom}\n// updateMode: 0,\n// layer: undefined,\n},\n// enableLayer: false\n});\n
  • scrollMode :
    • 0, or 'v', or 'vertical' : Scroll table vertically.
    • 1, or 'h', or 'horizontal' : Scroll table horizontally.
  • cellsCount : Total cells count.
  • columns : Columns count of each row. Can be used in vertical or horizontal scroll mode.
  • rows : Rows count of each column. Can be used in horizontal scroll mode.
  • cellHeight : Default height of each cell.
    • Expand cell height to fit table height : set cellHeight to undefined, and scrollMode is 'horizontal'.
  • cellWidth : Width of each cell.
    • Expand cell width to fit table width : set cellWidth to undefined, and scrollMode is 'vertical'.
  • fixedCellSize : Assign columns according to cellWidth (if scrollMode is 0) or cellHeight (if scrollMode is 1) , when initialize and resizing. \u3000\u3000- false : Ignore this parameter. Default behavior.
    • true : Set columns according to cellWidth/cellHeight.
  • cellVisibleCallback , cellVisibleCallbackScope : Callback when cell begins visible.
    function (cell, cellContainer, table) {\nif (cellContainer === null) { // No reusable cell container, create a new one\nvar scene = cell.scene;\n// cellContainer = scene.add.container();\n}\n// Set child properties of cell container ...\ncell.setContainer(cellContainer); // Assign cell container\n}\n
  • reuseCellContainer : Set true to reuse cell container when cell is visible.
  • cellInvisibleCallback, cellInvisibleCallbackScope: Callback when cell begins invisible
    function (cell) {\n// var container = cell.popContainer();\n}\n
  • clampTableOXY : Set true to clamp tableOX, tableOY when out-of-bound,
    • Set false when dragging by scroller
  • mask : A rectangle mask of cells
    • mask.padding :
      • A number : Extra left/right/top/bottom padding spacing of this rectangle mask. Default value is 0.
      • A plain object {left, right, top, bottom}
    • mask.updateMode : When to update cells mask
      • 0, or update : Apply mask to cell container only when table.updateTable() is invoked. Default behavior.
      • 1, or everyTick : Apply mask to cell container every tick. Use this mode if game objects of cell are moved after table.updateTable() and still been masked.
    • mask.layer :
      • undefined, false, null : Disable this feature, default behavior
      • Layer game object : Draw children game object of panel on this layer game object, then apply mask on this layer game object.
    • false : No mask.
  • enableLayer :
    • false : Add cell game objects into scene's display list. Default behavior.
    • true : Add cell game objects into an internal layer game object. See also.

Add grid table from JSON

var table = scene.make.rexGridTable({\nx: 0,\ny: 0,\nwidth: 256,\nheight: 256,\n\n// cellsCount: 0,   // total cells count\n// ...\n// origin: {x: 0.5, y: 0.5},\n});\n
"},{"location":"gridtable/#custom-class","title":"Custom class","text":"
  • Define class
    class MyGridTable extends GridTable {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var table = new MyGridTable(scene, x, y, width, height, config);\n
"},{"location":"gridtable/#cell-begins-visible","title":"Cell begins visible","text":"

Add container of cell when it begins visible in event cellvisible.

table.on('cellvisible', function(cell, cellContainer, table){\nif (cellContainer === null) { // No reusable cell container, create a new one\nvar scene = cell.scene;\n// cellContainer = scene.add.container();\n}\n// Set child properties of cell container ...\ncell.setContainer(cellContainer); // Assign cell container\n})\n

It is equal to cellVisibleCallback in configuration.

{\n// ...\ncellVisibleCallback: function(cell, cellContainer, table) {\ncell.setContainer(cellContainer); // Assign cell container\n},\n// ...\n}\n
  • cell
    • Scene object of grid table.
      var scene = cell.scene;\n
    • Index of cell.
      var index = cell.index;\n
    • Size of cell.
      var cellWidth = cell.width;\nvar cellHeight = cell.height;\n
      • Change size of cell :
        • Change cell height in scoll-vertical mode.
          cell.setHeight(newHeight);\n// cell.height = newHeight;\n
          or
          cell.setDeltaHeight(deltaHeight);\n// cell.deltaHeight = deltaHeight;\n
        • Reset cell height in scoll-vertical mode.
          cell.setDeltaHeight(0);\n// cell.deltaHeight = 0;\n
        • Change cell width in scroll-horizontal mode.
          cell.setWidth(newWidth);\n// cell.width = newWidth;\n
          or
          cell.setDeltaWidth(deltaWidth);\n// cell.deltaWidth = deltaWidth;\n
        • Reset cell height in scroll-horizontal mode.
          cell.setDeltaWidth(0);\n// cell.deltaWidth = 0;\n
    • Assign cell container. Set origin point of this cell container to (0,0).
      cell.setContainer(cellContainer);\n
    • Alignment of cellContainer :
      cell.setCellContainerAlign(align);\n
      • align :
        • undefined : Set position of cellContainer to left-top of cell space. Default behavior.
        • 'center', or Phaser.Display.Align.CENTER : Align game object at center of cell space.
        • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center of cell space.
        • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center of cell space.
        • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game object at top-center of cell space.
        • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at bottom-center of cell space.
  • cellContainer : Cell container picked from object pool for reusing. Set reuseCellContainer to true to enable this feature.
    • null : No cell container available.
    • Game object : Reusable cell container.
  • table : Grid table.

Each cell only has one container gameObject, old container will be destroyed when assigning a new container.

"},{"location":"gridtable/#cell-begins-invisible","title":"Cell begins invisible","text":"

Container of an invisible cell will be destroyed automatically.

To resue container gameObject

  • Set reuseCellContainer to true to put invisible cell container into object pool.
  • Or, pop that container by cell.popContainer() in event cellinvisible.
table.on('cellinvisible', function(cell){\n// var container = cell.popContainer();\n})\n

It is equal to cellInvisibleCallback in configuration.

{\n// ...\ncellInvisibleCallback: function(cell) {\n// var container = cell.popContainer();\n},\n// ...\n}\n
"},{"location":"gridtable/#scroll-table-content","title":"Scroll table content","text":"
  • Set
    table.setTableOY(oy).updateTable();\ntable.addTableOY(dy).updateTable();\n
    table.setTableOX(ox).updateTable();\ntable.addTableOX(dx).updateTable();\n
    table.setTableOXY(ox, oy).updateTable();\ntable.addTableOXY(dx, dy).updateTable();\n
    or
    table.tableOY = oy;  // include table.updateTable()\ntable.tableOX = ox;\n
    • These will trigger cellvisible, or cellinvisible events.
  • Get
    var tableOY = table.tableOY;\nvar tableOX = table.tableOX;\n

Use case

Scroll table by scroller behavior.

"},{"location":"gridtable/#scroll-by-percentage","title":"Scroll by percentage","text":"
  • Set
    table.setTableOYByPercentage(t).updateTable();  // t: 0~1\n
    or
    table.t = t;  // include table.updateTable()\n
  • Get
    var t = table.getTableOYPercentage();\n//var t = table.t;\n

Use case

Scroll table by slider behavior.

"},{"location":"gridtable/#scroll-to-bottom","title":"Scroll to bottom","text":"
table.scrollToBottom();\n
"},{"location":"gridtable/#scroll-to-row","title":"Scroll to row","text":"
  • Scroll to next row
    table.scrollToNextRow();\n
  • Scroll to next n row
    table.scrollToNextRow(n);\n
  • Scroll to row
    table.scrollToRow(rowIndex);\n
  • Get current row index
    var rowIndex = table.startRowIndex;\n
"},{"location":"gridtable/#refresh-table-content","title":"Refresh table content","text":"
  • Refresh all visible cells.
    table.updateTable(true);\n
  • Update a visible cell
    table.updateVisibleCell(cellIndex);\n
"},{"location":"gridtable/#table-size-in-cells","title":"Table size in cells","text":"
  • Set table size
    table.setGridSize(colCount, rowCount).updateTable();\n
"},{"location":"gridtable/#total-cells-count","title":"Total cells count","text":"
  • Get
    var count = table.cellsCount;\n
  • Set
    table.setCellsCount(count).updateTable();\n
"},{"location":"gridtable/#columns-count","title":"Columns count","text":"
  • Get
    var columnCount = table.columnCount;\n
  • Set
    table.setColumnCount(count).updateTable(true);\n
"},{"location":"gridtable/#table-size-in-pixels","title":"Table size in pixels","text":"
  • Table height in pixels
    var tableHeight = table.tableHeight;\n
  • Table width in pixels
    var tableWidth = table.tableWidth;\n
"},{"location":"gridtable/#bounds-of-tableox-tableoy","title":"Bounds of tableOX, tableOY","text":"
  • Top bound of tableOY
    var topTableOY = table.topTableOY;  // 0\n
  • Bottom bound of tableOY
    var bottomTableOY = table.bottomTableOY; // A negative number\n
  • Left bound of tableOX
    var leftTableOX = table.leftTableOX;  // 0\n
  • Right bound of tableOX
    var rightTableOX = table.rightTableOX; // A negative number\n

Use case

Set bounds of scroller

"},{"location":"gridtable/#resize-table","title":"Resize table","text":"
table.resize(width, height);\n
"},{"location":"gridtable/#cell","title":"Cell","text":""},{"location":"gridtable/#get-cell","title":"Get cell","text":"
var cell = table.getCell(cellIndex);\n
"},{"location":"gridtable/#get-cell-from-position","title":"Get cell from position","text":"
var cellIndex = table.pointToCellIndex(x, y);\nvar cell = table.getCell(cellIndex);\n
"},{"location":"gridtable/#cell-height","title":"Cell height","text":"
  • Get
    var height = cell.height;\n
  • Set cell height, only worked in scoll-vertical mode.
    cell.height = height;\n// cell.setHeight(height);\n
    or
    table.setCellHeight(cellIndex, cellHeight);\n
    • Refresh table after the cell size is changed.
      table.updateTable(true);\n
    • Emit 'cellheightchange' event.
      table.on('cellheightchange', function (cell, cellContainer, table) {\n});\n
"},{"location":"gridtable/#cell-width","title":"Cell width","text":"
  • Get
    var width = cell.width;\n
  • Set cell width, only worked in scoll-horizontal mode.
    cell.width = width;\n// cell.setWidth(width);\n
    or
    table.setCellWidth(cellIndex, cellWidth);\n
    • Refresh table after the cell size is changed.
      table.updateTable(true);\n
    • Emit 'cellwidthchange' event.
      table.on('cellwidthchange', function (cell, cellContainer, table) {\n});\n
"},{"location":"gridtable/#reset-size-of-all-cells","title":"Reset size of all cells","text":"
table.resetAllCellsSize(width, height);\n
"},{"location":"gridtable/#fore-each-visible-cell","title":"Fore each visible cell","text":"
  • For when you absolutely know this Set won't be modified during the iteration
    table.iterateVisibleCell(function(cell){\n// ...\n});\n
  • For when you know this Set will be modified during the iteration.
    table.eachVisibleCell(function(cell){\n// ...\n});\n
"},{"location":"gridtable/#container","title":"Container","text":"
  • Get
    var container = cell.getContainer();\n
  • Pop (get and remove)
    var container = cell.popContainer();\n
  • Set
    cell.setContainer(container);\n
  • Remove
    cell.destroyContainer();\n
"},{"location":"gridtable/#properties","title":"Properties","text":"
var cellIndex = cell.index;\n
"},{"location":"gridtable/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"group/","title":"Group","text":""},{"location":"group/#introduction","title":"Introduction","text":"

Objects pool, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"group/#usage","title":"Usage","text":""},{"location":"group/#add-group-object","title":"Add group object","text":"
var group = scene.add.group(config);\n// var group = scene.add.group(gameObjects, config);  // Add game objects into group\n
  • config
    {\nclassType: Phaser.GameObjects.Sprite,\ndefaultKey: null,\ndefaultFrame: null,\nactive: true,\nmaxSize: -1,\nrunChildUpdate: false,\ncreateCallback: null,\nremoveCallback: null,\ncreateMultipleCallback: null\n}\n
    • classType :
      • Sprite : Phaser.GameObjects.Sprite
      • Image : Phaser.GameObjects.Image
    • runChildUpdate : Set true to run gameObject.update() every tick.
    • createCallback : A function to be called when adding or creating group members.
      var callback = function(gameObject) {\n}\n
    • removeCallback : A function to be called when removing group members.
      var callback = function(gameObject) {\n}\n
    • createMultipleCallback : A function to be called when creating several group members at once.
      var callback = function(gameObjects) {\n}\n
"},{"location":"group/#add-game-object","title":"Add game object","text":"
group.add(gameObject);\n// group.add(gameObject, true);  // add this game object to display and update list of scene\n
group.addMultiple(gameObjects);   // array of game objects\n// group.addMultiple(gameObjects, true);\n
  • Game object will only be added once.
  • Game object will be removed automatically when destroyed.
"},{"location":"group/#remove-game-object","title":"Remove game object","text":"
group.remove(gameObject);\n// group.remove(gameObject, true);  // also remove this game object from display and update list of scene\n

Remove all game objects

group.clear();\n// group.clear(removeFromScene, destroyChild);\n
"},{"location":"group/#get-game-objects","title":"Get game objects","text":"
  • Get all game objects.
    var gameObjects = group.getChildren();  // array of game objects\n
  • Get all matching game objects
    var gameObjects = group.getMatching(property, value);\n// var gameObjects = group.getMatching(property, value, startIndex, endIndex);\n
  • Amount of game objects.
    var len = group.getLength();\n
  • Group is full. Maximun size is set in maxSize.
    var isFull = group.isFull();\n
  • Game object is in group.
    var isInGroup = group.contains(child);\n
"},{"location":"group/#group-actions","title":"Group actions","text":""},{"location":"group/#property","title":"Property","text":"
  • Set property
    group.propertyValueSet(key, value);\n// group.propertyValueSet(key, value, step, index, direction);\n
    • direction :
      • 1 : From beginning to end
      • -1 : From end to beginning
  • Increase property
    group.propertyValueInc(key, value);\n// group.propertyValueInc(key, value, step, index, direction);\n
    • direction :
      • 1 : From beginning to end
      • -1 : From end to beginning
"},{"location":"group/#position","title":"Position","text":"
  • Set Position
    group.setX(value);\n// group.setX(value, step);\ngroup.setX(value);\n// group.setY(value, step);\ngroup.setXY(x, y);\n// group.setXY(x, y, stepX, stepY);\n
  • Increase Position
    group.incX(value);\n// group.incX(value, step);\ngroup.incY(value);\n// group.incY(value, step);\ngroup.incXY(x, y);\n// group.incXY(x, y, stepX, stepY);\n
  • Shift position
    group.shiftPosition(x, y);\n// group.shiftPosition(x, y, direction);\n
    • direction :
      • 0 : First to last
      • 1 : Last to first
"},{"location":"group/#angle","title":"Angle","text":"
  • Set angle
    group.angle(value);\n// group.angle(value, step);\n
    group.rotate(value);\n// group.rotate(value, step);\n
  • Rotate around
    group.rotateAround(point, angle);\n
    group.rotateAroundDistance(point, angle, distance);\n
"},{"location":"group/#visible","title":"Visible","text":"
  • Set visible
    group.setVisible(value);\n// group.setVisible(value, index, direction);\n
    • index : An optional offset to start searching from within the items array.
    • direction : The direction to iterate through the array.
      • 1 : From beginning to end
      • -1 : From end to beginning
  • Toggle visible
    group.toggleVisible();\n
"},{"location":"group/#alpha","title":"Alpha","text":"
  • Set alpha
    group.setAlpha(value);\n// group.setAlpha(value, step);\n
"},{"location":"group/#tint","title":"Tint","text":"
  • Set tint
    group.setTint(value);\n// group.setTint(topLeft, topRight, bottomLeft, bottomRight);\n
"},{"location":"group/#blend-mode","title":"Blend mode","text":"
  • Set blend mode
    group.setBlendMode(value);\n
"},{"location":"group/#scale","title":"Scale","text":"
  • Set scale
    group.scaleX(value);\n// group.scaleX(value, step);\ngroup.scaleY(value);\n// group.scaleY(value, step);\ngroup.scaleXY(scaleX, scaleY);\n// group.scaleXY(scaleX, scaleY, stepX, stepY);\n
"},{"location":"group/#origin","title":"Origin","text":"
  • Set origin
    group.setOrigin(originX, originY);\n// group.setOrigin(originX, originY, stepX, stepY);\n
"},{"location":"group/#depth","title":"Depth","text":"
  • Set depth
    group.setDepth(value, step);\n
"},{"location":"group/#animation","title":"Animation","text":"
  • Play animation
    group.playAnimation(key, startFrame);\n
"},{"location":"group/#hit-area","title":"Hit area","text":"
  • Set hit-area
    group.setHitArea();\n// group.setHitArea(hitArea, hitAreaCallback);\n
"},{"location":"group/#shuffle","title":"Shuffle","text":"
  • Shuffle array
    group.shuffle();\n
"},{"location":"group/#activeinactive-game-objects","title":"Active/inactive game objects","text":"
  • Set inactive
    group.kill(gameObject);         // gameObject.setActive(false)\ngroup.killAndHide(gameObject);  // gameObject.setActive(false).setVisible(false)\n
  • Amount of active game objects
    var activeCount = group.countActive();\n
    or
    var activeCount = group.getTotalUsed();\n
  • Amount of active game objects
    var inactiveCount = group.countActive(false);\n
  • Amount of free (maxSize - activeCount) game objects
    var freeCount = group.getTotalFree();  // group.maxSize - group.getTotalUsed()\n
  • Get first active/inactive game object,
    • Return null if no game object picked.
      var gameObject = group.getFirst(active);  // active = true/false\nvar gameObject = group.getFirstAlive(); // Equal to group.getFirst(true, ...)\nvar gameObject = group.getFirstDead(); // Equal to group.getFirst(false, ...)\n
    • Create one if no game object picked.
      var gameObject = group.getFirst(active, true, x, y, key, frame, visible);  // active = true/false\nvar gameObject = group.getFirstAlive(true, x, y, key, frame, visible); // Equal to group.getFirst(true, ...)\nvar gameObject = group.getFirstDead(true, x, y, key, frame, visible); // Equal to group.getFirst(false, ...)\nvar gameObject = group.get(x, y, key, frame, visible); // Equal to group.getFirst(false, true, ...)\n
      • Use (x, y, key, frame) to create Image/Sprite game object.
        var newGameObject = new GameObjectClass(x, y, key, frame);\n
"},{"location":"group/#create-game-objects","title":"Create game objects","text":"
var gameObjects = group.createFromConfig(config);\nvar gameObjects = group.createMultiple(config);    // config in array\n
  • config
    {\nclassType: this.classType,\nkey: undefined,             // Required\nframe: null,\nvisible: true,\nactive: true,\nrepeat: 0,                  // Create (1 + repeat) game objects\ncreateCallback: undefined,  // Override this.createCallback if not undefined\n\n// Position\nsetXY: {\nx:0,\ny:0,\nstepX:0,\nstepY:0\n},\n// Actions.SetXY(gameObjects, x, y, stepX, stepY)\ngridAlign: false,\n// {\n//     width: -1,\n//     height: -1,\n//     cellWidth: 1,\n//     cellHeight: 1,\n//     position: Phaser.Display.Align.TOP_LEFT,\n//     x: 0,\n//     y: 0\n// }\n// Actions.GridAlign(gameObjects, gridAlign)\n\n// Angle\nsetRotation: {\nvalue: 0,\nstep:\n},\n// Actions.SetRotation(gameObjects, value, step)\n\n// Scale\nsetScale: {\nx:0,\ny:0,\nstepX:0,\nstepY:0\n},\n// Actions.SetScale(gameObjects, x, y, stepX, stepY)\n\n// Alpha\nsetAlpha: {\nvalue: 0,\nstep:\n},\n// Actions.SetAlpha(gameObjects, value, step)\n\nsetOrigin: {\nx:0,\ny:0,\nstepX:0, stepY:0\n},\n\n// Input\nhitArea: null,\nhitAreaCallback: null,\n// Actions.SetHitArea(gameObjects, hitArea, hitAreaCallback)\n}\n
    • classType :
      • Sprite: Phaser.GameObjects.Sprite
      • Image: Phaser.GameObjects.Image
"},{"location":"group/#destroy","title":"Destroy","text":"
  • Destroy group only
    group.destroy();\n
  • Destroy group and children
    group.destroy(true);\n
"},{"location":"groupactions/","title":"Group actions","text":""},{"location":"groupactions/#introduction","title":"Introduction","text":"

Set properties of game objects, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"groupactions/#usage","title":"Usage","text":""},{"location":"groupactions/#call-function","title":"Call function","text":"
Phaser.Actions.Call(gameObjects, function(gameObject) {\n\n}, scope);\n
"},{"location":"groupactions/#set-any-property","title":"Set any property","text":"
Phaser.Actions.PropertyValueSet(gameObjects, key, value, step, index, direction);\n
  • gameObjects : An array of game objects.
  • key : The property to be updated.
  • value : The amount to be added to the property.
  • step : This is added to the value amount, multiplied by the iteration counter.
  • index : An optional offset to start searching from within the items array.
  • direction :
    • 1 : from beginning to end.
    • -1: from end to beginning.
Phaser.Actions.PropertyValueInc(gameObjects, key, value, step, index, direction);\n
Phaser.Actions.SmootherStep(gameObjects, key, min, max, inc));\n
Phaser.Actions.SmoothStep(gameObjects, key, min, max, inc));\n
Phaser.Actions.Spread(gameObjects, key, min, max, inc));\n
"},{"location":"groupactions/#position","title":"Position","text":"
Phaser.Actions.SetX(gameObjects, value, step, index, direction);\n
Phaser.Actions.IncX(gameObjects, value, step, index, direction);\n
Phaser.Actions.SetY(gameObjects, value, step, index, direction);\n
Phaser.Actions.IncY(gameObjects, value, step, index, direction);\n
Phaser.Actions.SetXY(gameObjects, x, y, stepX, stepY, index, direction);\n
Phaser.Actions.IncXY(gameObjects, x, y, stepX, stepY, index, direction);\n
"},{"location":"groupactions/#shift-position","title":"Shift position","text":"

Set the position of first game object to (x, y), others to the position of previous game object.

Phaser.Actions.ShiftPosition(gameObjects, x, y, direction, output);\n
"},{"location":"groupactions/#position-on-shape","title":"Position on shape","text":""},{"location":"groupactions/#grid-align","title":"Grid align","text":"
Phaser.Actions.GridAlign(gameObjects, {\nwidth: -1,\nheight: -1,\ncellWidth: 1,\ncellHeight: 1,\nposition: Phaser.Display.Align.TOP_LEFT,\nx: 0,\ny: 0\n});\n
  • width : The width of the grid in items (not pixels). -1 means lay all items out horizontally, regardless of quantity.
  • height : The height of the grid in items (not pixels). -1 means lay all items out vertically, regardless of quantity.
  • cellWidth : The width of the cell, in pixels.
  • cellHeight : The height of the cell, in pixels.
  • position : The alignment position.
    • 0, or Phaser.Display.Align.TOP_LEFT
    • 1, or Phaser.Display.Align.TOP_CENTER
    • 2, or Phaser.Display.Align.TOP_RIGHT
    • 3, or Phaser.Display.Align.LEFT_TOP
    • 4, or Phaser.Display.Align.LEFT_CENTER
    • 5, or Phaser.Display.Align.LEFT_BOTTOM
    • 6, or Phaser.Display.Align.CENTER
    • 7, or Phaser.Display.Align.RIGHT_TOP
    • 8, or Phaser.Display.Align.RIGHT_CENTER
    • 9, or Phaser.Display.Align.RIGHT_BOTTOM
    • 10, or Phaser.Display.Align.BOTTOM_LEFT
    • 11, or Phaser.Display.Align.BOTTOM_CENTER
    • 12, or Phaser.Display.Align.BOTTOM_RIGHT
  • x, y : Position of first item.
"},{"location":"groupactions/#line","title":"Line","text":"

Line :

var line = new Phaser.Geom.Line(x1, y1, x2, y2);\n
Phaser.Actions.PlaceOnLine(gameObjects, line);\n// Phaser.Actions.PlaceOnLine(gameObjects, line, ease);\n
  • ease :
    • A string
    • A function object.
Phaser.Actions.RandomLine(gameObjects, line);\n
"},{"location":"groupactions/#circle","title":"Circle","text":"

Circle :

var circle = new Phaser.Geom.Circle(x, y, radius);\nPhaser.Actions.PlaceOnCircle(gameObjects, circle, startAngle, endAngle);\n
Phaser.Actions.RandomCircle(gameObjects, circle);\n
"},{"location":"groupactions/#ellipse","title":"Ellipse","text":"

Ellipse :

var ellipse = new Phaser.Geom.Ellipse(x, y, width, height);\nPhaser.Actions.PlaceOnEllipse(gameObjects, ellipse, startAngle, endAngle);\n
"},{"location":"groupactions/#triangle","title":"Triangle","text":"

Triangle :

var triangle = new Phaser.Geom.Triangle(x1, y1, x2, y2, x3, y3);\nPhaser.Actions.PlaceOnTriangle(gameObjects, triangle, stepRate);\n
Phaser.Actions.RandomTriangle(gameObjects, triangle);\n
"},{"location":"groupactions/#rectangle","title":"Rectangle","text":"

Rectangle :

var rect = new Phaser.Geom.Rectangle(x, y, width, height);\nPhaser.Actions.PlaceOnRectangle(gameObjects, rect, shift;\n
Phaser.Actions.RandomRectangle(gameObjects, rect);\n
Phaser.Actions.WrapInRectangle(gameObjects, rect, padding);\n
"},{"location":"groupactions/#angle","title":"Angle","text":"
Phaser.Actions.Angle(gameObjects, value, step, index, direction);\n// value: angle in radians\n
Phaser.Actions.Rotate(gameObjects, value, step, index, direction);\n// value: angle in degree\n
Phaser.Actions.RotateAround(gameObjects, point, angle);\n// point: {x, y}, angle: angle in radians\n
Phaser.Actions.RotateAroundDistance(gameObjects, point, angle, distance);\n// point: {x, y}, angle: angle in radians\n
"},{"location":"groupactions/#visible","title":"Visible","text":"
Phaser.Actions.SetVisible(gameObjects, value, index, direction);\n
Phaser.Actions.ToggleVisible(gameObjects);\n
"},{"location":"groupactions/#alpha","title":"Alpha","text":"
Phaser.Actions.SetAlpha(gameObjects, value, step, index, direction);\n
"},{"location":"groupactions/#tint","title":"Tint","text":"
Phaser.Actions.setTint(gameObjects, value);\n//Phaser.Actions.setTint(gameObjects, topLeft, topRight, bottomLeft, bottomRight);\n
"},{"location":"groupactions/#origin","title":"Origin","text":"
Phaser.Actions.SetOrigin(gameObjects, originX, originY, stepX, stepY, index, direction);\n
"},{"location":"groupactions/#scale","title":"Scale","text":"
Phaser.Actions.ScaleX(gameObjects, value, step, index, direction);\n
Phaser.Actions.ScaleY(gameObjects, value, step, index, direction);\n
Phaser.Actions.ScaleXY(gameObjects, x, y, stepX, stepY, index, direction);\n
"},{"location":"groupactions/#scroll-factor","title":"Scroll factor","text":"
Phaser.Actions.SetScrollFactorX(gameObjects, value, step, index, direction);\n
Phaser.Actions.SetScrollFactorY(gameObjects, value, step, index, direction);\n
Phaser.Actions.SetScrollFactor(gameObjects, x, y, stepX, stepY, index, direction);\n
"},{"location":"groupactions/#depth","title":"Depth","text":"
Phaser.Actions.SetDepth(gameObjects, value, step, index, direction);\n
"},{"location":"groupactions/#hit-area","title":"Hit area","text":"
Phaser.Actions.SetHitArea(gameObjects, hitArea, hitAreaCallback);\n
"},{"location":"groupactions/#blend-mode","title":"Blend mode","text":"
Phaser.Actions.SetBlendMode(gameObjects, blendMode, index, direction);\n
  • blendMode : Blend mode
"},{"location":"groupactions/#play-animation","title":"Play animation","text":"
Phaser.Actions.PlayAnimation(gameObjects, key, ignoreIfPlaying);\n
"},{"location":"groupactions/#shuffle","title":"Shuffle","text":"
Phaser.Actions.Shuffle(gameObjects);\n
"},{"location":"groupnavigator/","title":"Group navigator","text":""},{"location":"groupnavigator/#introduction","title":"Introduction","text":"

Navigate between existing game objects, focus on next/previous/next-row/previous row game object.

  • Author: Rex
  • Member of scene
"},{"location":"groupnavigator/#live-demos","title":"Live demos","text":"
  • 1D targets
  • 2D targets
"},{"location":"groupnavigator/#usage","title":"Usage","text":"

Sample code

"},{"location":"groupnavigator/#install-plugin","title":"Install plugin","text":""},{"location":"groupnavigator/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexgroupnavigatorplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgroupnavigatorplugin.min.js', true);\n
  • Create navigator
    var navigator = scene.plugins.get('rexgroupnavigatorplugin').add(config);\n
"},{"location":"groupnavigator/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GroupNavigatorPlugin from 'phaser3-rex-plugins/plugins/groupnavigator-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGroupNavigator',\nplugin: GroupNavigatorPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create navigator
    var navigator = scene.plugins.get('rexGroupNavigator').add(config);\n
"},{"location":"groupnavigator/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import GroupNavigator from 'phaser3-rex-plugins/plugins/groupnavigator.js';\n
  • Create navigator
    var navigator = new GroupNavigator(config);\n
"},{"location":"groupnavigator/#create-navigator","title":"Create navigator","text":"
var navigator = scene.plugins.get('rexGroupNavigator').add({\n// enable: true,\n\ntargets: gameObjects,\n// columns: undefined,\n\n// getFocusEnableCallback(gameObject) { \n//     return focusEnable;\n// }\n// focusEnableDataKey: undefined,\n// focusEnableKey: undefined\n});\n
  • enable :
    • true : Can navigate between game objects. Default behavior.
    • false : Ignore navigation actions (navigator.next(), navigator.previous(), navigator.nextRow(), navigator.previousRow())
  • targe1ts :
    • 1D array of game objects for navigator.next(), or navigator.previous()
    • 2D array of game objects for navigator.next(), navigator.previous(), navigator.nextRow(), navigator.previousRow()
  • columns : A number : Convert 1D targets array to 2D array, each row has columns game objects.
    • undefined : Ignore this parameter. Default behavior.
  • Focus enable : Get focus enable of game object by one of these parameter.
    • getFocusEnableCallback : A callback to return focus enable of this game object.
      function(gameObject) {\nreturn focusEnable;\n}\n
    • focusEnableDataKey : Get focus enable from private data of this game object.
    • focusEnableKey : Get focus enable from property of this game object.
    • Focus enable is always true if none of these parameter is given. Default behavior.
"},{"location":"groupnavigator/#enable","title":"Enable","text":"
  • Get
    var enable = navigator.enable;\n
  • Set
    navigator.setEnable(enable);\n
"},{"location":"groupnavigator/#navigate","title":"Navigate","text":"
  • Focus on next/previous game object, for 1D and 2D array of targets
    navigator.next();\n
    navigator.previous();\n
    Will fire blur and focus events
  • Focus on next row/previous row game object, for 2D array of targets
    navigator.nextRow();\n
    navigator.previousRow();\n
    Will fire blur and focus events
  • Focus on first/last game object
    navigator.first();\n
    navigator.last();\n
    Will fire blur and focus events
"},{"location":"groupnavigator/#current-focused-game-object","title":"Current focused game object","text":"
  • Get current focused game object
    var gameObject = navigator.getFocusedTarget();\n// var gameObject = navigator.focusedTarget;\n
  • Focus on game object. Do nothing if that game object is not focus-enable.
    navigator.focus(gameObject);\n
    Will fire blur and focus events.
  • Blur
    navigator.blur();\n
    Will fire blur event.
"},{"location":"groupnavigator/#target-game-objects","title":"Target game objects","text":"
  • Get
    var gameObjects = navigator.targets;\n
    • gameObjects : 1D/2D array of game objects
  • Set
    navigator.setTargets(targets);\n// navigator.setTargets(targets, columns);\n
  • Modify
    navigator.targets.push(newGameObject);    
    Phaser.Utils.Array.AddAt(navigator.targets, newGameObject, index);\n
    Phaser.Utils.Array.Remove(navigator.targets, gameObject);\n
"},{"location":"groupnavigator/#events","title":"Events","text":"
  • On focus
    navigator.on('focus', function(gameObject){\n\n})\n
  • On blur
    navigator.on('blur', function(gameObject){\n\n})\n
"},{"location":"handlebars/","title":"Handlebars","text":""},{"location":"handlebars/#introduction","title":"Introduction","text":"

Format string with variables, largely compatible with Mustache templates. Reference

"},{"location":"handlebars/#usage","title":"Usage","text":"
var template = 'hello, {{name}}';\nvar view = {\nname: 'rex'\n};\nvar result = Mustache.render(template, view);\n
"},{"location":"handlebars/#pre-compile","title":"Pre-compile","text":"
const template = Handlebars.compile(\"{{foo}}\");\ntemplate({}, {\n// allowProtoPropertiesByDefault: false,\n// allowProtoMethodsByDefault: false\n});\n
"},{"location":"hiddeninputtext/","title":"Hidden edit","text":""},{"location":"hiddeninputtext/#introduction","title":"Introduction","text":"

An invisible Input DOM element to receive character input and display on text, bbocodetext, or tagtext.

Inspirited from CanvasInput.

  • Author: Rex
  • Behavior of text object
"},{"location":"hiddeninputtext/#live-demos","title":"Live demos","text":"
  • With Text
  • With BBCodeText
  • With rexui-Label
  • With bitmaptext
  • Number input
"},{"location":"hiddeninputtext/#usage","title":"Usage","text":"

Sample code

"},{"location":"hiddeninputtext/#install-plugin","title":"Install plugin","text":""},{"location":"hiddeninputtext/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexhiddeninputtextplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexhiddeninputtextplugin.min.js', true);\n
  • Add text-edit behavior
    var hiddenInputText = scene.plugins.get('rexhiddeninputtextplugin').add(textGameObject, config);\n
"},{"location":"hiddeninputtext/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import HiddenInputTextPlugin from 'phaser3-rex-plugins/plugins/hiddeninputtext-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexHiddenInputTextPlugin',\nplugin: HiddenInputTextPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text-edit behavior
    var hiddenInputText = scene.plugins.get('rexHiddenInputTextPlugin').add(textGameObject, config);\n
"},{"location":"hiddeninputtext/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import HiddenInputText from 'phaser3-rex-plugins/plugins/hiddeninputtext.js';\n
  • Add text-edit behavior
    var hiddenInputText = new HiddenInputText(textGameObject, config);\n
"},{"location":"hiddeninputtext/#add-input-text-object","title":"Add input text object","text":"
var hiddenInputText = scene.plugins.get('rexHiddenInputTextPlugin').add(textGameObject, {\n// inputType: 'text',    // 'text'|'password'|'textarea'|...\n// type: 'text',    // 'text'|'password'|'textarea'|...\n\ncursor: '|',\ncursorFlashDuration: 1000,\n\n// enterClose: true,\n\n// onOpen: function (textObject, hiddenInputText) {   // Or onFocus:\n// },\n// onClose: function (textObject, hiddenInputText) {  // Or onBlur:\n// },\n// onUpdate: function (text, textObject, hiddenInputText) {\n//     return text;\n// },\n});\n
  • textGameObject :
  • inputType, or type : Type of element
    • 'text', 'password', 'textarea', ...
  • cursor : Cursor character used in default update text callback.
    • null, or '' : Don't insert cursor character.
  • cursorFlashDuration : Display cursor character or a space string to create a flash cursor.
  • enterClose :
    • true : Close input text when enter-key was pressed. Default value is true if inputType is not 'textarea'.
    • false : If inputType is set to 'textarea', default value will be false.
  • onOpen, or onFocuse : Callback invoked when focus on this hidden input text.
    function (textObject, hiddenInputText) {\n}\n
  • onClose, or onBlur : Callback invoked when blur.
    function (textObject, hiddenInputText) {\n}\n
  • onUpdate :
    • A callback invoked in each tick of editing.
      function (text, textObject, hiddenInputText) {\n// return text;\n}\n
      • Can return a new string for text game object displaying.
    • 'number' : Only output number string.

Note

This hiddenInputText will be destroyed when textGameObject is destroyed.

"},{"location":"hiddeninputtext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyHiddenText extends HiddenInputText {\nconstructor(textGameObject, config) {\nsuper(textGameObject, config) {\n// ...            \n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var hiddenInputText = new MyHiddenText(textGameObject, config);\n
"},{"location":"hiddeninputtext/#cursor","title":"Cursor","text":"
  • Set
    hiddenInputText.setCursor(s);\n
  • Get
    var cursor = hiddenInputText.cursor;\n
"},{"location":"hiddeninputtext/#open-editor","title":"Open editor","text":"
hiddenInputText.open();\n
"},{"location":"hiddeninputtext/#close-editor","title":"Close editor","text":"
hiddenInputText.close();\n
"},{"location":"hiddeninputtext/#is-opened","title":"Is opened","text":"
var isOpened = hiddenInputText.isOpened;\n
"},{"location":"hiddeninputtext/#select-text","title":"Select text","text":"

This feature does not support.

"},{"location":"hiddeninputtext/#bypass-key-input","title":"Bypass key input","text":"

Registered keyboard events might capture key input.

var keyObj = scene.input.keyboard.addKey('W', enableCapture, emitOnRepeat);\n

Set enableCapture to false to bypass key input to this input-text game objecct.

"},{"location":"hiddeninputtext/#event","title":"Event","text":"
  • On text change
    hiddenInputText.on('textchange', function(text, textGameObject){\n})\n
  • Not a number input
    hiddenInputText.on('nan', function(text){\n\n})\n
  • Close editor by ENTER key down
    hiddenInputText.on('keydown-ENTER', function(){\n})\n
"},{"location":"i18next/","title":"i18next","text":""},{"location":"i18next/#introduction","title":"Introduction","text":"

i18next is a very popular internationalization framework for browser or any other javascript environment.

  • Author: i18next
  • Application plugin : Text translation
"},{"location":"i18next/#usage","title":"Usage","text":""},{"location":"i18next/#import-class","title":"Import class","text":"
  • Install i18next, i18next-http-backend from npm
    npm i i18next\nnpm i i18next-http-backend\n
  • Import i18next
    import i18next from 'i18next';\nimport Backend from 'i18next-http-backend';\n
  • Initialize
    i18next.use(Backend).init(config);\n
  • Translation
    var result = i18next.t(key);\n
"},{"location":"i18next/#initialize","title":"Initialize","text":"
i18next\n.use(Backend)\n.init({\nlng: 'dev',\nfallbackLng: 'dev',\nns: 'translation',\n\n// resources: {\n//     'dev': {\n//         'translation': {\n//             key: value,  \n//         }\n//     }\n// }\n\n// debug: true,\n})\n
  • lng : Language to use. Will fallback to 'dev'.
  • ns : String or array of namespaces to load. Default value is 'translation'.
  • debug : Logs info level to console output. Helps finding issues with loading not working. Default value is false.
  • resources : Resources to initialize with.
  • backend.loadPath : Path where resources get loaded from, or a function returning a path.
    function(lngs, namespaces) { return customPath; }\n
  • backend.parse : Parse data after it has been fetched. Optional.
    function(data) { return JSON.parse(data); }\n

See also Configuration Options, and Backend Options

"},{"location":"i18next/#change-language","title":"Change language","text":"
i18next.changeLanguage(\"en\");\n

Fire event 'languageChanged'.

"},{"location":"i18next/#set-default-namespace","title":"Set default namespace","text":"
i18next.setDefaultNamespace(namespace);\n
"},{"location":"i18next/#translate","title":"Translate","text":"
var result = i18next.t(key);\n// var result = i18next.t(key, interpolation);\n
"},{"location":"i18next/#events","title":"Events","text":"
  • On language changed, triggered by i18next.changeLanguage(lng).
    i18next.on('languageChanged', function (lng) {\n});\n
"},{"location":"image/","title":"Image","text":""},{"location":"image/#introduction","title":"Introduction","text":"

Display of static images, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"image/#usage","title":"Usage","text":""},{"location":"image/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"image/#add-image-object","title":"Add image object","text":"
var image = scene.add.image(x, y, key);\n// var image = scene.add.image(x, y, key, frame);\n

Add image from JSON

var image = scene.make.image({\nx: 0,\ny: 0,\nkey: '',\n// frame: '',\n\n// angle: 0,\n// alpha: 1,\n// flipX: true,\n// flipY: true,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
  • key, frame :
    • A string
    • An array of string to pick one element at random
  • x, y, scale.x, scale.y :
    • A number
    • A callback to get return value
      function() { return 0; }\n
    • Random integer between min and max
      { randInt: [min, max] }\n
    • Random float between min and max
      { randFloat: [min, max] }\n
"},{"location":"image/#custom-class","title":"Custom class","text":"
  • Define class
    class MyImage extends Phaser.GameObjects.Image {\nconstructor(scene, x, y, texture, frame) {\nsuper(scene, x, y, texture, frame);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyImage(scene, x, y, key);\n
"},{"location":"image/#texture","title":"Texture","text":"

See game object - texture

"},{"location":"image/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"image/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"image/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"imagebox/","title":"Image box","text":""},{"location":"imagebox/#introduction","title":"Introduction","text":"

Keep aspect ratio of image game object when scale-down resizing. A containerLite game object with 1 image game object.

  • Author: Rex
  • Game object
"},{"location":"imagebox/#live-demos","title":"Live demos","text":"
  • Resize
"},{"location":"imagebox/#usage","title":"Usage","text":"

Sample code

"},{"location":"imagebox/#install-plugin","title":"Install plugin","text":""},{"location":"imagebox/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('reximageboxplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/reximageboxplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexImageBox(x, y, texture, frame, config);\n
"},{"location":"imagebox/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ImageBoxPlugin from 'phaser3-rex-plugins/plugins/imagebox-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexImageBoxPlugin',\nplugin: ImageBoxPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexImageBox(x, y, texture, frame, config);\n
"},{"location":"imagebox/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ImageBox from 'phaser3-rex-plugins/plugins/imagebox.js';\n
  • Add image object
    var image = new ImageBox(scene, x, y, texture, frame, config);\nscene.add.existing(image);\n
"},{"location":"imagebox/#create-instance","title":"Create instance","text":"
var image = scene.add.rexImageBox(x, y, texture, frame, {\n// scaleUp: false,\n// width: undefined,\n// height: undefined,\n\n// background: undefined,\n// image: undefined\n});\n
  • scaleUp : Scale up or keep original size of image when size of imageBox is larger.
    • true : Scale up image when size of imageBox is larger.
    • false : Keep original size of image size of imageBox is larger. Default behavior.
  • width, height : Resize this game object.
    • undefined : Use original size. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of imageBox.
  • image : Custom image game object instance.
    • undefined : Use built-in image game object. Default behavior.

Add imagebox from JSON

var image = scene.make.rexImageBox({\nx: 0,\ny: 0,\nkey: null,\nframe: null,\n\n// width: undefined,\n// height: undefined,\n\n// background: undefined,\n// image: undefined\n\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
"},{"location":"imagebox/#custom-class","title":"Custom class","text":"
  • Define class
    class MyImageBox extends ImageBox {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyImageBox(scene, x, y, texture, frame, config);\n
"},{"location":"imagebox/#resize","title":"Resize","text":"
image.resize(width, height);\n

Note

  • If new size is bigger than original size, uses original size. (i.e won't scale up)
  • If new size is smaller than original size, scales down and keeps aspect ratio.
"},{"location":"imagebox/#set-texture","title":"Set texture","text":"
image.setTexture(key, frame);\n
"},{"location":"imagebox/#current-texture","title":"Current texture","text":"
var textureKey = image.texture.key;\nvar frameName = image.frame.name;\n
"},{"location":"imagebox/#clear-texture","title":"Clear texture","text":"
image.setTexture();\n

Will set internal image game object to invisible.

"},{"location":"imagebox/#scale-image","title":"Scale image","text":"
image.scaleImage();\n

image.resize(width, height), or image.setTexture(key, frame) will invoke this method internally.

"},{"location":"imagebox/#internal-image-game-object","title":"Internal image game object","text":"
var internalImageGO = image.image;\n
"},{"location":"imagebox/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"imagebox/#create-mask","title":"Create mask","text":"

Create mask from internal image game object (image.image).

var mask = image.image.createBitmapMask();\n

See mask

"},{"location":"imagebox/#shader-effects","title":"Shader effects","text":"

Internal image game object (image.image) support preFX and postFX effects

"},{"location":"imageuriloader/","title":"Imageuriloader","text":"

Note

Phaser3.80 can load image by uri (base64 string) in preload stage.

"},{"location":"imageuriloader/#introduction","title":"Introduction","text":"

Load image by uri (base64 string) in preload stage.

Built-in image loader dosen't support loading local image uri.

  • Author: Rex
  • Custom File of loader
"},{"location":"imageuriloader/#usage","title":"Usage","text":"

Sample code

"},{"location":"imageuriloader/#install-plugin","title":"Install plugin","text":""},{"location":"imageuriloader/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    var sceneConfig = {\n// ....\npack: {\nfiles: [{\ntype: 'plugin',\nkey: 'reximageuriloaderplugin',\nurl: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/reximageuriloaderplugin.min.js',\nstart: true\n}]\n}\n};\nclass MyScene extends Phaser.Scene {\nconstructor() {\nsuper(sceneConfig)\n}\n// ....\n\npreload() {\n// reximageuriloaderplugin will be installed before preload(), but not added to loader yet\n// Call addToScene(scene) to add this await loader to loader of this scene\nthis.plugins.get('reximageuriloaderplugin').addToScene(this);\n\nthis.load.rexImageURI(key, uri);\n}\n}\n
"},{"location":"imageuriloader/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ImageURILoaderPlugin from 'phaser3-rex-plugins/plugins/imageuriloader-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexImageURILoader',\nplugin: ImageURILoaderPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • In preload stage
    scene.load.rexImageURI(key, uri);\n
"},{"location":"imageuriloader/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ImageURILoader from 'phaser3-rex-plugins/plugins/imageuriloader.js';\n
  • Start loading task
    ImageURILoader.call(scene.load, key, uri);\n
"},{"location":"imageuriloader/#load-image","title":"Load image","text":"

In preload stage:

this.load.rexImageURI(key, uri);\n
  • key : Texture key.
  • uri : URI, a base64 string.
"},{"location":"imageuriloader/#load-sprite-sheet","title":"Load sprite sheet","text":"

In preload stage:

this.load.rexImageURI(key, uri, frameConfig);\n
  • key : Texture key.
  • uri : URI, a base64 string.
  • frameConfig :
    • frameWidth : The width of the frame in pixels.
    • frameHeight : The height of the frame in pixels. Uses the frameWidth value if not provided.
    • startFrame : The first frame to start parsing from.
    • endFrame : The frame to stop parsing at. If not provided it will calculate the value based on the image and frame dimensions.
    • margin : The margin in the image. This is the space around the edge of the frames.
    • spacing : The spacing between each frame in the image.
"},{"location":"input-to-camera/","title":"Control by input","text":""},{"location":"input-to-camera/#introduction","title":"Introduction","text":"

Control camera's scroll by pan/cursor-at-bounds(scroll), and zoom by pinch/mouse-wheel.

  • Author: Rex
  • Member of scene
"},{"location":"input-to-camera/#live-demos","title":"Live demos","text":"
  • Camera controller
"},{"location":"input-to-camera/#usage","title":"Usage","text":"

Sample code

"},{"location":"input-to-camera/#install-plugin","title":"Install plugin","text":""},{"location":"input-to-camera/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcameracontrollerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcameracontrollerplugin.min.js', true);\n
  • Add camera-controller object
    var cameraController = scene.plugins.get('rexcameracontrollerplugin').add(scene, config);\n
"},{"location":"input-to-camera/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CameraControllerPlugin from 'phaser3-rex-plugins/plugins/cameracontroller-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCameraController',\nplugin: CameraControllerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add camera-controller object
    var cameraController = scene.plugins.get('rexCameraController').add(scene, config);\n
"},{"location":"input-to-camera/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CameraController from 'phaser3-rex-plugins/plugins/cameracontroller.js';\n
  • Add camera-controller object
    var cameraController = new CameraController(scene, config);\n
"},{"location":"input-to-camera/#create-instance","title":"Create instance","text":"
var cameraController = scene.plugins.get('rexCameraController').add(scene, {\n// camera: scene.cameras.main,\n// minZoom: undefined,\n// maxZoom: undefined,\n\n// panScroll: true,\n// panScrollEnable: true,\n\n// pinchZoom: true,\n// pinchZoomEnable: true,\n// pinchZoomMin: undefined,\n// pinchZoomMax: undefined,\n\n// inputTarget: undefined,\n\n// boundsScroll: true,\n// boundsScrollEnable: true,\n\n// mouseWheelZoom: truem\n// mouseWheelZoomEnable: true,\n// mouseWheelZoomStep: 0.01,\n// mouseWheelZoomMin: undefined,\n// mouseWheelZoomMax: undefined,\n\n// enable: true\n});\n
  • scene : Target scene.
  • camera :
    • undefined : Default camera of this scene.
    • A camera object : Control this camera object.
  • minZoom, maxZoom : Minumun/maximum camera zoom value for pinchZoom and mouseWheelZoom behaviors.
    • undefined : No max/min constraint. Default behavior.
  • Pan scroll:
    • panScroll : Set to false will discard pan-scroll controller. Default is true.
    • panScrollEnable : Set to true to enable pan-scroll behavior. Default value is true.
    • inputTarget :
      • undefined : Receive pan/pinch input by scene's input event. Default behavior.
      • A game object : Receive pan/pinch input only on this game object.
  • Pinch zoom:
    • pinchZoom : Set to false will discard pinch-zoom controller. Default is true.
    • pinchZoomEnable : Set to true to enable pinch-zoom behavior. Default value is true.
    • pinchZoomMin, pinchZoomMax : Minumun/maximum camera zoom value. Default value is minZoom, maxZoom.
    • inputTarget :
      • undefined : Receive pan/pinch input by scene's input event. Default behavior.
      • A game object : Receive pan/pinch input only on this game object.
  • cursor-at-bounds scroll :
    • boundsScroll : Set to false will discard cursor-at-bounds-scroller controller. Default is true.
    • boundsScrollEnable : Set to true to enable bounds-scroll behavior. Default value is true.
  • mouse-wheel zoom :
    • mouseWheelZoom : Set to false will discard mouse-wheel-zoom controller. Default is true.
    • mouseWheelZoomEnable : Set to true to enable mouse-wheel-zoom behavior. Default value is true.
    • mouseWheelZoomStep : Camera zoom incremental. Default value is 0.1.
    • mouseWheelZoomMin, mouseWheelZoomMax : Minumun/maximum camera zoom value. Default value is minZoom, maxZoom.
  • enable :
    • false : Disable all camera-controller temporary.
    • true : Restore all camera-controller's enable state to previous value. Default behavior.
"},{"location":"input-to-camera/#set-target-camera","title":"Set target camera","text":"
cameraController.setCamera(camera);\n
"},{"location":"input-to-camera/#enable-controller-behavior","title":"Enable controller behavior","text":"
  • Pan-scroll
    cameraController.setPanScrollEnable(enable);\n// cameraController.panScrollEnable = enable;\n
  • Pinch-zoom
    cameraController.setPinchZoomEnable(enable);\n// cameraController.pinchZoomEnable = enable;\n
  • Bounds-scroll
    cameraController.setBoundsScrollEnable(enable);\n// cameraController.boundsScrollEnable = enable;\n
  • Wheel-zoom
    cameraController.setMouseWheelZoomEnable(enable);\n// cameraController.mouseWheelZoomEnable = enable;\n
  • Disable all behaviors
    cameraController.setEnable(false);\n// cameraController.enable = false;\n
  • Restore enable state of all behaviors
    cameraController.setEnable();\n// cameraController.enable = true;\n
  • Toggle enable state
    cameraController.toggleEnable();\n// cameraController.enable = !cameraController.enable;\n
"},{"location":"input/","title":"Input","text":""},{"location":"input/#introduction","title":"Introduction","text":"

Input system of each scene, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"input/#usage","title":"Usage","text":""},{"location":"input/#enabledisable","title":"Enable/disable","text":"
scene.input.enabled = enabled; // enabled: true/false\n
"},{"location":"inputtext/","title":"Input text","text":""},{"location":"inputtext/#introduction","title":"Introduction","text":"

Input DOM element.

  • Author: Rex
  • DOM Game object
"},{"location":"inputtext/#live-demos","title":"Live demos","text":"
  • Input text
  • Number input
  • In fullscreen
"},{"location":"inputtext/#usage","title":"Usage","text":"

Sample code

"},{"location":"inputtext/#install-plugin","title":"Install plugin","text":""},{"location":"inputtext/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexinputtextplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexinputtextplugin.min.js', true);\n
  • Add input-text object
    var inputText = scene.add.rexInputText(x, y, width, height, config);\n
"},{"location":"inputtext/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import InputTextPlugin from 'phaser3-rex-plugins/plugins/inputtext-plugin.js';\nvar config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexInputTextPlugin',\nplugin: InputTextPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add input-text object
    var inputText = scene.add.rexInputText(x, y, width, height, config);\n
"},{"location":"inputtext/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import InputText from 'phaser3-rex-plugins/plugins/inputtext.js';\n
  • Add input-text object
    var inputText = new InputText(scene, x, y, width, height, config);\nscene.add.existing(inputText);\n
"},{"location":"inputtext/#add-input-text-object","title":"Add input text object","text":"
var inputText = scene.add.rexInputText(x, y, width, height, config);\n// var inputText = scene.add.rexInputText(x, y, config);\n// var inputText = scene.add.rexInputText(config);\n

Default configuration

{\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\n\ntype: 'text',    // 'text'|'password'|'textarea'|'number'|'color'|...\n\n// Element properties\nid: undefined,\ntext: undefined,\nmaxLength: undefined,\nminLength: undefined,    placeholder: undefined,\ntooltip: undefined,\nreadOnly: false,\nspellCheck: false,\nautoComplete: 'off',\n\n// Style properties\nalign: undefined,\npaddingLeft: undefined,\npaddingRight: undefined,\npaddingTop: undefined,\npaddingBottom: undefined,\nfontFamily: undefined,\nfontSize: undefined,\ncolor: '#ffffff',\nborder: 0,\nbackgroundColor: 'transparent',\nborderColor: 'transparent',\nborderRadius: undefined,\noutline: 'none',\ndirection: 'ltr',\n\nselectAll: false\n}\n
  • x, y : Position
  • width, height : Size of element
  • type : Type of element
    • 'text', 'password', 'textarea', 'number', 'color', ...
  • Element properties
    • id : id element property.
    • text : value element property.
    • maxLength : maxLength element property.
    • minLength : minLength element property.
    • placeholder : placeholder element property.
    • tooltip : title element property.
    • readOnly : readonly element property.
    • spellCheck : spellcheck element property.
    • autoComplete : autocomplete element property.
  • Element style properties
    • align : text-align style property.
    • paddingLeft, paddingRight, paddingTop, paddingBottom : padding-left, padding-right, padding-top, padding-bottom style property.
    • fontFamily : font-family style property.
    • fontSize : font-size style property.
    • color : color style property.
    • backgroundColor : backgroundColor style property.
    • border, borderColor, borderRadius : border, borderColor, border-radius style property.
    • outline : outline style property.
    • direction : direction style property.
  • selectAll : Set true to select all text.
"},{"location":"inputtext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyText extends InputText {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config) {\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var inputText = new MyText(scene, x, y, width, height, config);\n
"},{"location":"inputtext/#text","title":"Text","text":"
  • Get
    var text = inputText.text;\n
  • Set
    inputText.setText(text);\n// inputText.text = text;\n
  • Scroll to bottom
    inputText.scrollToBottom();\n
"},{"location":"inputtext/#style","title":"Style","text":"
  • Get
    var value = inputText.getStyle(key);\n
  • Set
    inputText.setStyle(key, value)\n
"},{"location":"inputtext/#focus","title":"Focus","text":"
  • Focus
    inputText.setFocus();\n
  • Blur
    inputText.setBlur();\n
  • Is focused
    var isFocused = inputText.isFocused;\n
"},{"location":"inputtext/#font-color","title":"Font color","text":"
  • Get
    var color = inputText.fontColor;\n// var color = inputText.node.style.color;\n
  • Set
    inputText.fontColor = color;  // CSS color string\n// inputText.node.style.color = color;\n
    or
    inputText.setFontColor(color);  // CSS color string\n
"},{"location":"inputtext/#max-length","title":"Max length","text":"
  • Get
    var value = inputText.maxLength;\n
  • Set
    inputText.maxLength = value;\n
    or
    inputText.setMaxLength(value);\n
"},{"location":"inputtext/#min-length","title":"Min length","text":"
  • Get
    var value = inputText.minLength;\n
  • Set
    inputText.minLength = value;\n
    or
    inputText.setMinLength(value);\n
"},{"location":"inputtext/#placeholder","title":"Placeholder","text":"
  • Get
    var value = inputText.placeholder;\n
  • Set
    inputText.placeholder = value;\n
    or
    inputText.setPlaceholder(value);\n
"},{"location":"inputtext/#tooltip","title":"Tooltip","text":"
  • Get
    var value = inputText.tooltip;\n
  • Set
    inputText.tooltip = value;\n
    or
    inputText.setTooltip(value);\n
"},{"location":"inputtext/#readonly","title":"Readonly","text":"
  • Get
    var readOnly = inputText.readOnly;\n
  • Set
    inputText.readOnly = value;\n
    inputText.setReadOnly();\n// inputText.setReadOnly(value);\n
"},{"location":"inputtext/#resize","title":"Resize","text":"
inputText.resize(width, height);\n
"},{"location":"inputtext/#select-text","title":"Select text","text":"
  • Select all text
    inputText.selectText();\n// inputText.selectAll();\n
  • Select sub-string
    inputText.selectText(selectionStart, selectionEnd);\n
"},{"location":"inputtext/#cursor-position","title":"Cursor position","text":"
  • Get
    var cursorPosition = inputText.cursorPosition;\n
    • Equal to inputText.selectionStart.
  • Set
    inputText.setCursorPosition(cursorPosition);\ninputText.cursorPosition = cursorPosition;\n
    • Equal to inputText.setSelectionRange(cursorPosition, cursorPosition)
"},{"location":"inputtext/#events","title":"Events","text":"
  • On text changed
    inputText.on('textchange', function(inputText, e){ }, scope);\n
  • On focus
    inputText.on('focus', function(inputText, e){ }, scope);\n
  • On blur
    inputText.on('blur', function(inputText, e){ }, scope);\n
  • On click, double click
    inputText.on('click', function(inputText, e){ }, scope);\n
    inputText.on('dblclick', function(inputText, e){ }, scope);\n
    • Touch/mouse events on input text object won't be propagated to game canvas.
  • On keydown, keyup
    inputText.on('keydown', function(inputText, e){ }, scope);\n
    inputText.on('keyup', function(inputText, e){ }, scope);\n
    • Keyboard events on input text object won't be propagated to game canvas.
  • On pointerdown, pointermove, pointerup
    inputText.on('pointerdown', function(inputText, e){ }, scope);\n
    inputText.on('pointermove', function(inputText, e){ }, scope);\n
    inputText.on('pointerup', function(inputText, e){ }, scope);\n
    • Mouse/touch events on input text object won't be propagated to game canvas.
  • On select
    inputText.on('select', function(inputText, e){ var selectedString = inputText.selectedText;\nvar selectionStart = inputText.selectionStart;\nvar selectionEnd = inputText.selectionEnd;\n}, scope);\n
  • On composition inpit
    inputText.on('compositionStart', function(inputText, e){ }, scope);\n
    inputText.on('compositionEnd', function(inputText, e){ }, scope);\n
    inputText.on('compositionUpdate', function(inputText, e){ }, scope);\n
"},{"location":"inputtext/#bypass-key-input","title":"Bypass key input","text":"

Registered keyboard events might capture key input.

var keyObj = scene.input.keyboard.addKey('W', enableCapture, emitOnRepeat);\n

Set enableCapture to false to bypass key input to this input-text game objecct.

"},{"location":"inputtext/#other-properties","title":"Other properties","text":"

See dom game object, game object

"},{"location":"inputtext/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"

See dom-element's Interactive with other game objects

"},{"location":"inputtext/#close-editing","title":"Close editing","text":"
  • Close editing (set blur) when pointerdown outside
    scene.input.on('pointerdown', function () {\ninputText.setBlur();\n})\n
  • Close editing (set blur) when ENTER key press
    inputText.on('keydown', function (inputText, e) {\nif ((inputText.inputType !== 'textarea') && (e.key === 'Enter')) {\ninputText.setBlur();\n}\n})\n
    • inputType : 'text', 'textarea', ...
"},{"location":"interception/","title":"Interception","text":""},{"location":"interception/#introduction","title":"Introduction","text":"

Predict the intersection position of two game objects with constant moving speed.

  • Author: Rex
  • Behavior of game object
"},{"location":"interception/#usage","title":"Usage","text":"

Sample code

"},{"location":"interception/#install-plugin","title":"Install plugin","text":""},{"location":"interception/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexinterceptionplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexinterceptionplugin.min.js', true);\n
  • Add interception behavior
    var interception = scene.plugins.get('rexinterceptionplugin').add(gameObject, config);\n
"},{"location":"interception/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import InterceptionPlugin from 'phaser3-rex-plugins/plugins/interception-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexInterception',\nplugin: InterceptionPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add interception behavior
    var interception = scene.plugins.get('rexInterception').add(gameObject, config);\n
"},{"location":"interception/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Interception from 'phaser3-rex-plugins/plugins/interception.js';\n
  • Add interception behavior
    var interception = new Interception(gameObject, config);\n
"},{"location":"interception/#create-instance","title":"Create instance","text":"
var interception = scene.plugins.get('rexInterception').add(gameObject, {\n// target: undefined,\n// enable: true\n});\n
  • target : Game object.
  • enable : Set true to enable predicting.
"},{"location":"interception/#target","title":"Target","text":"
  • Set
    interception.setTarget(gameObject);\n
    or
    interception.target = gameObject;\n
  • Disalbe
    interception.setTarget(undefined);\n
    or
    interception.target = undefined;\n
  • Get
    var target = interception.target;\n
"},{"location":"interception/#enable-predicting","title":"Enable predicting","text":"
  • Enable
    interception.setEnable();\n
  • Disable, uses target position as predicted position
    interception.setEnable(false);\n
"},{"location":"interception/#predicted-result","title":"Predicted result","text":"
  • Predicted position
    var position = interception.predictedPosition; // {x, y}\n
  • Angle to predicted position
    var rotation = interception.predictedAngle; // Angle in radian\n
"},{"location":"interpolation/","title":"Interpolation","text":""},{"location":"interpolation/#introduction","title":"Introduction","text":"

Calculates interpolation value over t (0~1), built-in method of phaser.

  • Author: Richard Davey
"},{"location":"interpolation/#usage","title":"Usage","text":"
  • Linear interpolation (lerp) two values
    var result = Phaser.Math.Linear(p0, p1, t);\n
  • Linear interpolation (lerp) two Vectors
    var result = Phaser.Math.LinearXY(vector0, vector1, t);\n
    • vector0, vector1 : Phaser.Math.Vector2
  • Smooth interpolation
    var result = Phaser.Math.Interpolation.SmoothStep(t, min, max);\n
    • t : 0~1
  • Smoother interpolation
    var result = Phaser.Math.Interpolation.SmootherStep(t, min, max);\n
    • t : 0~1
  • Quadratic bezier interpolation
    var result = Phaser.Math.Interpolation.QuadraticBezier(t, p0, p1, p2);\n
    • t : 0~1
    • p0 : The start point.
    • p1 : The control point.
    • p2 : The end point.
  • Cubic bezier interpolation
    var result = Phaser.Math.Interpolation.CubicBezier(t, p0, p1, p2, p3);\n
    • t : 0~1
    • p0 : The start point.
    • p1 : The first control point.
    • p2 : The second control point.
    • p3 : The end point.
"},{"location":"intouching/","title":"In touching","text":""},{"location":"intouching/#introduction","title":"Introduction","text":"

Fires 'intouch' event every tick when pressing on a game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"intouching/#live-demos","title":"Live demos","text":"
  • Cooldown
  • Is in touching
"},{"location":"intouching/#usage","title":"Usage","text":"

Sample code

"},{"location":"intouching/#install-plugin","title":"Install plugin","text":""},{"location":"intouching/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexintouchingplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexintouchingplugin.min.js', true);\n
  • Add intouching behavior
    var intouching = scene.plugins.get('rexintouchingplugin').add(gameObject, config);\n
"},{"location":"intouching/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import InTouchingPlugin from 'phaser3-rex-plugins/plugins/intouching-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexInTouchingn',\nplugin: InTouchingPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add intouching behavior
    var intouching = scene.plugins.get('rexInTouchingn').add(gameObject, config);\n
"},{"location":"intouching/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import InTouching from 'phaser3-rex-plugins/plugins/intouching.js';\n
  • Add intouching behavior
    var intouching = new InTouching(gameObject, config);\n
"},{"location":"intouching/#create-instance","title":"Create instance","text":"
var intouching = scene.plugins.get('rexInTouching').add(gameObject, {\n// enable: true,\n// cooldown: undefined\n});\n
  • enable : Can touch.
  • cooldown : Fire 'intouch' event every tick, or periodically.
    • undefined : Fire 'intouch' event every tick.
"},{"location":"intouching/#events","title":"Events","text":"
  • In-touching
    intouching.on('intouch', function (intouching, gameObject, pointer) {\n// ...\n}, scope);\n
  • Touching-start
    intouching.on('touchstart', function (intouching, gameObject) {\n// ...\n}, scope);\n
  • Touching-end
    intouching.on('touchend', function (intouching, gameObject) {\n// ...\n}, scope);\n
"},{"location":"intouching/#in-touching","title":"In touching","text":"
var isInTouching = intouching.isInTouching;\n
"},{"location":"intouching/#enable","title":"Enable","text":"
  • Get
    var enabled = intouching.enable;  // enabled: true, or false\n
  • Set
    intouching.setEnable(enabled);  // enabled: true, or false\n// intouching.enable = enabled;\n
  • Toggle
    intouching.toggleEnable();\n
"},{"location":"intouching/#cooldown","title":"Cooldown","text":"
  • Get
    var cooldownTime = intouching.cooldownTime;\n
  • Set
    intouching.setCooldown(time);\n
    or
    intouching.cooldownTime = cooldownTime;\n
"},{"location":"keyboardcombo/","title":"Combo events","text":""},{"location":"keyboardcombo/#introduction","title":"Introduction","text":"

Combo-keys events.

  • Author: Richard Davey
"},{"location":"keyboardcombo/#usage","title":"Usage","text":"
  1. Create combo
    var keyCombo = scene.input.keyboard.createCombo(keys, {\n// resetOnWrongKey: true,\n// maxKeyDelay: 0,\n// resetOnMatch: false,\n// deleteOnMatch: false,\n});\n
    • keys : Array of keyCodes
      • In strings. ex: ['up', 'up', 'down', 'down'], or ['UP', 'UP', 'DOWN', 'DOWN']
      • In key map. ex: [Phaser.Input.Keyboard.KeyCodes.UP, ... ]
      • In numbers. ex: [38, 38, 40, 40]
    • resetOnWrongKey : Set true to reset the combo when press the wrong key.
    • maxKeyDelay : The max delay in ms between each key press. Set 0 to disable this feature.
    • resetOnMatch : Set true to reset the combo when previously matched.
    • deleteOnMatch : Set true to delete this combo when matched.
  2. Listen combo matching event
    scene.input.keyboard.on('keycombomatch', function (keyCombo, keyboardEvent) { /* ... */ });\n
"},{"location":"keyboardevents/","title":"Keyboard events","text":""},{"location":"keyboardevents/#introduction","title":"Introduction","text":"

Built-in keyboard events of phaser.

  • Author: Richard Davey
"},{"location":"keyboardevents/#usage","title":"Usage","text":""},{"location":"keyboardevents/#quick-start","title":"Quick start","text":"
  • Is key-down/is key-up
    var keyObject = scene.input.keyboard.addKey('W');  // Get key object\nvar isDown = keyObject.isDown;\nvar isUp = keyObject.isUp;\nvar shiftKey = keyObject.shiftKey;\n
  • Key is down after a duration
    var keyObject = scene.input.keyboard.addKey('W');  // Get key object\nvar isDown = scene.input.keyboard.checkDown(keyObject, duration);\n
  • On key-down/on key-up
    var keyObject = scene.input.keyboard.addKey('W');  // Get key object\nkeyObject.on('down', function(event) { /* ... */ });\nkeyObject.on('up', function(event) { /* ... */ });\n
    or
    scene.input.keyboard.on('keydown-' + 'W', function (event) { /* ... */ });\nscene.input.keyboard.on('keyup-' + 'W', function (event) { /* ... */ });\n
  • Any key-down/any key-up
    scene.input.keyboard.on('keydown', function (event) { /* ... */ });\nscene.input.keyboard.on('keyup', function (event) { /* ... */ });\n
    • event : KeyboardEvent
      • event.code : 'Key' + 'W'
"},{"location":"keyboardevents/#key-object","title":"Key object","text":"
  • Get key object
    var keyObject = scene.input.keyboard.addKey('W');  // see `Key map` section\n// var keyObject = scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.W);\n
    or
    var keyObject = scene.input.keyboard.addKey('W', enableCapture, emitOnRepeat);\n
    • enableCapture : Automatically call preventDefault on the native DOM browser event for the key codes being added.
    • emitOnRepeat : Controls if the Key will continuously emit a 'down' event while being held down (true), or emit the event just once (false, the default).
  • Get key objects
    var keyObjects = scene.input.keyboard.addKeys('W,S,A,D');  // keyObjects.W, keyObjects.S, keyObjects.A, keyObjects.D\n// var keyObjects = scene.input.keyboard.addKeys('W,S,A,D', enableCapture, emitOnRepeat);\n
    or
    var keyObjects = scene.input.keyboard.addKeys({\nup: 'W',\ndown: 'S',\nleft: 'A',\nright: 'D'\n});  // keyObjects.up, keyObjects.down, keyObjects.left, keyObjects.right\n
  • Remove key object
    scene.input.keyboard.removeKey('W');\n// scene.input.keyboard.removeKey(Phaser.Input.Keyboard.KeyCodes.W);\n// scene.input.keyboard.removeKey(key, destroy, removeCapture);\n
    • destroy : Call Key.destroy on each removed Key object
    • removeCapture : Remove all key captures for Key objects owened by this plugin?
  • Remove all key objects
    scene.input.keyboard.removeAllKeys(true);\n// scene.input.keyboard.removeAllKeys(destroy, removeCapture);\n
    • destroy : Call Key.destroy on each removed Key object
    • removeCapture : Remove all key captures for Key objects owened by this plugin?
  • Key-down/key-up state
    var isDown = keyObject.isDown;\nvar isUp = keyObject.isUp;\n
  • Duration of key-down
    var duration = keyObject.getDuration(); // ms\n
  • Enable/disable
    keyObject.enabled = enabled; // Set false to disable key event\n
"},{"location":"keyboardevents/#key-object-of-cursorkeys","title":"Key object of cursorkeys","text":"
  1. Get key state object
    var cursorKeys = scene.input.keyboard.createCursorKeys();\n
  2. Get key state
    var isUpDown = cursorKeys.up.isDown;\nvar isDownDown = cursorKeys.down.isDown;\nvar isLeftDown = cursorKeys.left.isDown;\nvar isRightDown = cursorKeys.right.isDown;\nvar isSpaceDown = cursorKeys.space.isDown;\nvar isShiftDown = cursorKeys.shift.isDown;\n
"},{"location":"keyboardevents/#order-of-key-downkey-up-events","title":"Order of key-down/key-up events","text":"
  1. Key-down/key-up events of key object
    var keyObject = scene.input.keyboard.addKey('W');  // Get key object\nkeyObject.on('down', function(event) { /* ... */ });\nkeyObject.on('up', function(event) { /* ... */ });\n
    • event.stopImmediatePropagation() : Stop any further listeners from being invoked in the current Scene.
    • event.stopPropagation() : Stop it reaching any other Scene.
  2. On key-down/on key-up
    scene.input.keyboard.on('keydown-' + 'W', function (event) { /* ... */ });\nscene.input.keyboard.on('keyup-' + 'W', function (event) { /* ... */ });\n
    • event.stopImmediatePropagation() : Stop any further listeners from being invoked in the current Scene.
    • event.stopPropagation() : Stop it reaching any other Scene.
    • Invoke event.preventDefault() to stop event propagation to native DOM.
  3. Any key-down/on key-up
    scene.input.keyboard.on('keydown', function (event) { /* ... */ });\nscene.input.keyboard.on('keyup', function (event) { /* ... */ });\n
    • event.key : 'a'
    • event.keyCode : 65
    • event.code : 'KeyA'
    • event.stopImmediatePropagation() : Stop any further listeners from being invoked in the current Scene.
    • event.stopPropagation() : Stop it reaching any other Scene.
"},{"location":"keyboardevents/#destroy-key-object","title":"Destroy key object","text":"
keyObject.destroy();\n
"},{"location":"keyboardevents/#key-map","title":"Key map","text":"
  • A ~ Z
  • F1 ~ F12
  • BACKSPACE
  • TAB
  • ENTER
  • SHIFT
  • CTRL. ALT
  • PAUSE
  • CAPS_LOCK
  • ESC
  • SPACE
  • PAGE_UP, PAGE_DOWN
  • END, HOME
  • LEFT, UP, RIGHT,DOWN
  • PRINT_SCREEN
  • INSERT, DELETE
  • ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE
  • NUMPAD_ZERO, NUMPAD_ONE, NUMPAD_TWO, NUMPAD_THREE, NUMPAD_FOUR, NUMPAD_FIVE, NUMPAD_SIX, NUMPAD_SEVEN, NUMPAD_EIGHT, NUMPAD_NINE, NUMPAD_ADD, NUMPAD_SUBTRACT
  • OPEN_BRACKET, CLOSED_BRACKET
  • SEMICOLON_FIREFOX, COLON, COMMA_FIREFOX_WINDOWS, COMMA_FIREFOX, BRACKET_RIGHT_FIREFOX, BRACKET_LEFT_FIREFOX
"},{"location":"keyshub/","title":"Keys hub","text":""},{"location":"keyshub/#introduction","title":"Introduction","text":"

Key object interface mapping from multiple source of key objects.

  • Author: Rex
  • Member of scene
"},{"location":"keyshub/#live-demos","title":"Live demos","text":"
  • Multiple mode
  • Single mode
  • Define key
"},{"location":"keyshub/#usage","title":"Usage","text":"

Sample code

"},{"location":"keyshub/#install-plugin","title":"Install plugin","text":""},{"location":"keyshub/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexkeyshubplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexkeyshubplugin.min.js', true);\n
  • Add keys-hub object
    var keysHub = scene.plugins.get('rexkeyshubplugin').add(scene, config);\n
"},{"location":"keyshub/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import KeysHubPlugin from 'phaser3-rex-plugins/plugins/keyshub-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexKeysHub',\nplugin: KeysHubPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add keys-hub object
    var keysHub = scene.plugins.get('rexKeysHub').add(scene, config);\n
"},{"location":"keyshub/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import KeysHub from 'phaser3-rex-plugins/plugins/keyshub.js';\n
  • Add keys-hub object
    var keysHub = new KeysHub(scene, config);\n
"},{"location":"keyshub/#create-instance","title":"Create instance","text":"
var keysHub = scene.plugins.get('rexKeysHub').add(scene, {\n// singleMode: false,\n});\n
  • singleMode :
    • true : Unplug old key object then plug new key object.
    • false : Plug new key object without unplug previous key object. Default behavior.
"},{"location":"keyshub/#destroy","title":"Destroy","text":"
keysHub.destroy();\n
"},{"location":"keyshub/#plug-key-object","title":"Plug key object","text":"
  • Plug a set of key objects
    keysHub.plugKeyObject({\nkeyCode0: keyObject0,\nkeyCode1: keyObject1,\n// ...\n});\n
    for example :
    var keyObjects = scene.input.keyboard.addKeys({\nup: 'W',\ndown: 'S',\nleft: 'A',\nright: 'D'\n});\nkeysHub.plugKeyObject(keyObjects);\n
    var keyObjects = scene.input.keyboard.createCursorKeys();\nkeysHub.plugKeyObject(keyObjects);\n
    or
    var keyObjects = joystick.createCursorKeys();\nkeysHub.plugKeyObject(keyObjects);\n
    • keyObjects : {keyCode : keyObject}
    • joystick : Virtual joystick
  • Plug a key object
    keysHub.plugKeyObject(keyObject, keyCode);\n
"},{"location":"keyshub/#unplug-key-object","title":"Unplug key object","text":"
  • Unplug a set of key objects
    keysHubunplugKeyObjects(keyObjects);\n
    • keyObjects : {keyCode : keyObject}
  • Unplugin a key object
    keysHub.unplugKeyObject(keyObject);\n
"},{"location":"keyshub/#key-object-interfacee","title":"Key object interfacee","text":"
  • Get key object
    var keyObject = keysHub.addKey('W');  // see `Key map` section\n// var keyObject = keysHub.addKey(Phaser.Input.Keyboard.KeyCodes.W);\n
    or
    var keyObject = keysHub.addKey('W');\n
  • Get key objects
    var keyObjects = keysHub.addKeys('W,S,A,D');  // keyObjects.W, keyObjects.S, keyObjects.A, keyObjects.D\n
    or
    var keyObjects = keysHub.addKeys({\nup: 'W',\ndown: 'S',\nleft: 'A',\nright: 'D'\n});  // keyObjects.up, keyObjects.down, keyObjects.left, keyObjects.right\n
  • Get curor key objects
    var cursorKeys = keysHub.createCursorKeys();\n
"},{"location":"keyshub/#get-plugged-key-objects","title":"Get plugged key objects","text":"
var keyObject = keysHub.getKeyObjects(key);\n
  • key : Key string, or keyCode number.
  • keyObject :
    • A key object if singleMode is set to true
    • A list of key objects if if singleMode is set to false
"},{"location":"keyshub/#re-define-key-map","title":"Re-define key map","text":"

Set singleMode to ture when creating keysHub instance.

"},{"location":"keyshub/#start-definition-task","title":"Start definition task","text":"
keysHub.defineKeyStart(key);  // key: key string\n
  • Fire 'definekey.start' event
"},{"location":"keyshub/#listen-key-input","title":"Listen key input","text":"
  • From keyboard
    keysHub.listenFromKeyboard();\n
"},{"location":"keyshub/#cancel-definition-task","title":"Cancel definition task","text":"
keysHub.defineKeyCancel();\n
  • Fire 'definekey.complete' event.
"},{"location":"keyshub/#complete-definition-task","title":"Complete definition task","text":"

Complete when any key input

  • Fire 'definekey.complete' event.
"},{"location":"keyshub/#events","title":"Events","text":"
  • On key object plug
    keysHub.on('plug', function(key, keyObject) {\n\n})\n
  • On key object unplug
    keysHub.on('unplug', function(key, keyObject) {\n\n})\n
  • On define-key start
    keysHub.on('definekey.start', function(key) {\n\n})\n
  • On define-key complete
    keysHub.on('definekey.complete', function(key, keyObject) {\n\n})\n
    • key :
      • A string : Plug new key object to that Key object interface.
      • undefined : Cancel define-key task.
    • keyObject :
      • A key object : New plugged key object.
      • undefined : Remove current plugged key.
"},{"location":"layer/","title":"Layer","text":""},{"location":"layer/#introduction","title":"Introduction","text":"

A local display list, built-in game object of phaser.

Layers have no position or size

Layers have no position or size within the Scene

  • Cannot enable a Layer for physics or input.
  • Cannot change the position, rotation or scale of a Layer.
  • No scroll factor, texture, tint, origin, crop or bounds.

Layers cannot be added to Containers

Containers can be added to Layers, but Layers cannot be added to Containers.

  • Author: Richard Davey
"},{"location":"layer/#usage","title":"Usage","text":""},{"location":"layer/#add-layer","title":"Add layer","text":"
var layer = scene.add.layer();\n// var layer = scene.add.layer(children);\n
  • children : Array of game objects added to this layer.
"},{"location":"layer/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLayer extends Phaser.GameObjects.Layer {\nconstructor(scene, children) {\nsuper(scene, children);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var layer = new MyLayer(scene, children);\n
"},{"location":"layer/#add-child","title":"Add child","text":"
  • Add child
    layer.add(gameObject);\n// layer.add(gameObjects);\n
    • gameObject : A game object, or an array of game objects.
  • Add child at
    layer.addAt(gameObject, index);\n
  • Replace child
    layer.replace(oldGameObject, newGameObject);\n
"},{"location":"layer/#remove-child","title":"Remove child","text":"
  • Remove child
    var removed = layer.remove(gameObject);\n
  • Remove child at
    var removed = layer.removeAt(index);\n
  • Remove children between indexes
    var removed = layer.removeBetween(startIndex, endIndex);\n
  • Remove all children
    layer.removeAll();\n

Removed game object won't be added to display list of scene, use

gameObject.addToDisplayList();\n

to add it back to scene's display list.

"},{"location":"layer/#get-child","title":"Get child","text":"
  • Get child at
    var gameObject = layer.getAt(index);\n
  • Get first child by name
    var gameObject = layer.getByName(name);\n
  • Get first child by property
    var gameObject = layer.getFirst(property, value);\n// var gameObject = layer.getFirst(property, value, startIndex, endIndex);\n
  • Get random child
    var gameObject = layer.getRandom();\n// var gameObject = layer.getRandom(startIndex, length);\n
  • Get all children
    var gameObjects = layer.getAll();\n
  • Get index of child
    var index = layer.getIndex(gameObject);\n
  • Get child count
    var count = layer.count(property, value);\n
  • Get total children count
    var count = layer.length;\n
  • Has child
    var hasChild = layer.exists(gameObject);\n
"},{"location":"layer/#iterate","title":"Iterate","text":"
  • Get first child (set iterator index to 0)
    var gameObject = layer.first;\n
  • Get last child (set iterator index to last)
    var gameObject = layer.last;\n
  • Get next child (increase iterator index, until last)
    var gameObject = layer.next;\n
  • Get previous child (decrease iterator index, until 0)
    var gameObject = layer.previous;\n
"},{"location":"layer/#move-child","title":"Move child","text":"
  • Swap
    layer.swap(gameObject1, gameObject2);\n
  • Move to
    layer.moveTo(gameObject, index);\n
  • Bring to top
    layer.bringToTop(gameObject);\n
  • Send to back
    layer.sendToBack(gameObject);\n
  • Move up
    layer.moveUp(gameObject);\n
  • Move down
    layer.moveDown(gameObject);\n
  • Move child1 above child2
    layer.moveAbove(child1, child2);\n
  • Move child1 below child2
    layer.moveBelow(child1, child2);\n
  • Sort
    layer.sort(property);\n
    or
    layer.sort('', function(gameObject1, gameObject2) { return 1; // 0, or -1\n});\n
  • Reverse
    layer.reverse();\n
  • Shuffle
    layer.shuffle();\n

Note

Children game objects also sort by depth.

"},{"location":"layer/#for-each-child","title":"For each child","text":"
layer.each(function(gameObject) {\n\n}, scope);\n
"},{"location":"layer/#set-property","title":"Set property","text":"
layer.setAll(property, value);\n// layer.setAll(property, value, startIndex, endIndex);\n
"},{"location":"layer/#events","title":"Events","text":"
  • On add game object
    layer.events.on('addedtoscene', function(gameObject, scene) {\n\n})\n
  • On remove game object
    layer.events.on('removedfromscene', function(gameObject, scene) {\n\n})\n

layer.events references to scene.events.

"},{"location":"layer/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"layer/#create-mask","title":"Create mask","text":"
var mask = layer.createBitmapMask();\n

See mask

"},{"location":"layer/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"layermanager/","title":"Layer manager","text":""},{"location":"layermanager/#introduction","title":"Introduction","text":"

A dictionary to store Layer game objects. Each layer can have a dedicate camera.

  • Author: Rex
  • Container of game objects
"},{"location":"layermanager/#relationship-diagram","title":"Relationship diagram","text":"

Camera - layer - game object

graph RL\n\n    subgraph Cameras\n      cameraBG[BG]\n      cameraGO[GO]\n      cameraUI[UI]\n    end\n\n    subgraph Layers\n      subgraph BG\n        layerBGBottom[BG-bottom]\n        layerBG[BG]\n        layerBGTop[BG-top]\n      end\n\n      subgraph GO\n        layerGOBottom[GO-bottom]\n        layerGO[GO]\n        layerGOTop[GO-top]\n      end\n\n      subgraph UI\n        layerUIBottom[UI-bottom]\n        layerUI[UI]\n        layerUITop[UI-top]\n      end\n    end\n\n    layerBGBottom --> cameraBG\n    layerBG --> cameraBG\n    layerBGTop --> cameraBG\n\n    layerGOBottom --> cameraGO\n    layerGO --> cameraGO\n    layerGOTop --> cameraGO\n\n    layerUIBottom --> cameraUI\n    layerUI --> cameraUI\n    layerUITop --> cameraUI\n\n    subgraph GameObjects\n      goBG0[\"Background\"] --> layerBG\n      goBG1[\"Background\"] --> layerBG\n\n      go0[GameObject] --> layerGO\n      go1[GameObject] --> layerGO\n      go2[GameObject] --> layerGO\n      go3[GameObject] --> layerGO\n\n      goUI0[Panel] --> layerUI\n      goUI1[Panel] --> layerUI\n      goSYSUI[System dialog] --> layerUITop\n    end
"},{"location":"layermanager/#usage","title":"Usage","text":"

Sample code

"},{"location":"layermanager/#install-plugin","title":"Install plugin","text":""},{"location":"layermanager/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlayermanagerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlayermanagerplugin.min.js', true);\n
  • Add layer manager
    var layerManager = scene.plugins.get('rexlayermanagerplugin').add(scene, config);\n
"},{"location":"layermanager/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LayerManagerPlugin from 'phaser3-rex-plugins/plugins/layermanager-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLayerManager',\nplugin: LayerManagerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add layer manager
    var layerManager = scene.plugins.get('rexLayerManager').add(scene, config);\n
"},{"location":"layermanager/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LayerManager from 'phaser3-rex-plugins/plugins/layermanager.js';\n
  • Add move-to behavior
    var layerManager = new LayerManager(scene, config);\n
"},{"location":"layermanager/#create-instance","title":"Create instance","text":"
var layerManager = scene.plugins.get('rexLayerManager').add(scene, {\n// layers: ['layer0', 'layer1', ...]\n// layers: [{name, cameraName, scrollFactor}, ...]\n\n// depth: undefined,\n// rootLayer: undefined,\n});\n

or

var layerManager = scene.plugins.get('rexLayerManager').add(scene, ['layer0', 'layer1', ...]\n// [{name, cameraName, scrollFactor}, ...]\n);\n
  • layers : Add some initial layers
    • A string array : Add layers by string name
    • A array of plain object { name, cameraName, scrollFactor }
      1. Add layer by string name
      2. Apply scroll factor to all children of this layer.
      3. Bind this layer to dedicate camera (indexed by cameraName), ignore other cameras Add a new camera if this target camera is not existing
  • depth : Set depth to each layer game object.
    • undefined : Keep default depth value (0)
  • rootLayer : Add all layer game objects created by this layer-manager into this root layer.
"},{"location":"layermanager/#destroy","title":"Destroy","text":"
layerManager.destroy()\n

Also destroy all layers in this layer manager.

"},{"location":"layermanager/#add-layer","title":"Add layer","text":"
layerManager.add(name);\n// layerManager.add(name, depth);\n
"},{"location":"layermanager/#add-game-object-to-layer","title":"Add game object to layer","text":"
layerManager.addToLayer(name, gameObject);\n
  • name : Name of layer
  • gameObject : Any kind of game object, include containerLite and related game objects.

Note

Print a warn message if specific layer is not existed.

"},{"location":"layermanager/#get-layer","title":"Get layer","text":"
  • Get layer by name
    var layer = layerManager.getLayer(name);\n
  • Get all layers in this layer manager
    var layers = layerManager.getLayers();\n// var out = layerManager.getLayers(out);\n
"},{"location":"layermanager/#has-layer","title":"Has layer","text":"
var hasLayer = layerManager.has(name);\n// var hasLayer = layerManager.exists(name);\n
"},{"location":"layermanager/#clear-layer","title":"Clear layer","text":"
  • Destroy all children at layer
    layerManager.clearLayer(name);\n
  • Move all children from layer to scene's display list
    layerManager.clearLayer(name, false);\n
"},{"location":"layermanager/#change-depth","title":"Change depth","text":"
  • Bring a layer (layerName) to top of displayList
    layerManager.bringLayerToTop(layerName);\n
  • Send a layer (layerName) to bottom of displayList
    layerManager.sendLayerToBack(layerName);\n
  • Move a layer (layerName) above another layer (baseLayerName)
    layerManager.moveLayerAbove(layerName, baseLayerName)\n
  • Move a layer (layerName) below another layer (baseLayerName)
    layerManager.moveLayerBelow(layerName, baseLayerName)\n
"},{"location":"layermanager/#set-scroll-factor","title":"Set scroll factor","text":"
layerManager.setScrollFactor(scrollFactor);\n// layerManager.setScrollFactor(scrollFactorX, scrollFactorY);\n

Apply scroll factor to all children of this layer.

"},{"location":"layermanager/#bind-camera","title":"Bind camera","text":"
  • Set camera
    layerManager.setCamera(layerName, cameraName);\n
    Bind this layer to dedicate camera (indexed by cameraName), ignore other cameras Add a new camera if this target camera is not existing
  • Get camera
    var camera = layerManager.getCamera(layerName);\n
"},{"location":"levelcounter/","title":"Level counter","text":""},{"location":"levelcounter/#introduction","title":"Introduction","text":"

Map level value from experience value, by callback or a number array.

  • Author: Rex
  • Object
"},{"location":"levelcounter/#live-demos","title":"Live demos","text":"
  • Exp-bar
"},{"location":"levelcounter/#usage","title":"Usage","text":"

Sample code

"},{"location":"levelcounter/#install-plugin","title":"Install plugin","text":""},{"location":"levelcounter/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlevelcounterplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlevelcounterplugin.min.js', true);\n
  • Add level-counter object
    var levelCounter = scene.plugins.get('rexlevelcounterplugin').add(config);\n
"},{"location":"levelcounter/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LevelCounterPlugin from 'phaser3-rex-plugins/plugins/levelcounter-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLevelCounter',\nplugin: LevelCounterPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add level-counter object
    var levelCounter = scene.plugins.get('rexLevelCounter').add(config);\n
"},{"location":"levelcounter/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LevelCounter from 'phaser3-rex-plugins/plugins/levelcounter.js';\n
  • Add level-counter object
    var levelCounter = new LevelCounter(config);\n
"},{"location":"levelcounter/#create-instance","title":"Create instance","text":"
var levelCounter = scene.plugins.get('rexLevelCounter').add({\ntable: function(level) { return level * 100; },\n// table: [0, 100, 200, 300,],\n\n// maxLevel: -1,\n\n// exp: 0,\n});\n
  • table : Level table, return experience value from level value. Level value starts from 0.
    • A callback
      function(level) {\nreturn experience;\n}\n
    • A number array : Experience value of each level.
  • maxLevel :
    • undefined : Default value
      • No upper limit for callback level table.
      • (table.length - 1) for number array level table.
    • A number : Maximum level value
  • exp : Initial experience value. Default value is 0.
"},{"location":"levelcounter/#accumulate-experience","title":"Accumulate experience","text":"
  • Accumulate experience
    levelCounter.gainExp(incExp);\n// levelCounter.exp += incExp;\n
    or
    levelCounter.gainExp(incExp, callback, scope);\n
    • Will fire 'levelup' event, or invoke callback many times.
      function(level, fromExp, toExp, levelStartExp, levelEndExp){        }\n
      • level : To next level
      • fromExp, toExp : Experience increment from fromExp to toExp.
      • levelStartExp, levelEndExp : Range of this level.
  • Reset experience value
    levelCounter.resetExp(exp);\n
    • Won't fire 'levelup' event.
  • Force level up
    levelCounter.setLevel(level);\n
    or
    levelCounter.setLevel(level, callback, scope);\n
    • Will fire 'levelup' event, or invoke callback many times.
      function(level, fromExp, toExp, levelStartExp, levelEndExp){        }\n
      • level : To next level
      • fromExp, toExp : Experience increment from fromExp to toExp.
      • levelStartExp, levelEndExp : Range of this level.
"},{"location":"levelcounter/#level-and-experience","title":"Level and experience","text":"
  • Get current experience
    var exp = levelCounter.getExp();\n// var exp = levelCounter.exp;\n
  • Get current level
    var level = levelCounter.getLevel();\n// var level = levelCounter.level;\n
  • Get current required experience to next level
    var exp = levelCounter.requiredExp;\n
  • Get experience of level
    var exp = levelCounter.getExp(level);\n
  • Get level from experience
    var level = levelCounter.getLevel(exp);\n
  • Get required experience to level
    var exp = levelCounter.getRequiredExpToNextLevel(level);\n// var exp = levelCounter.getRequiredExpToNextLevel(level, exp);\n
"},{"location":"levelcounter/#events","title":"Events","text":"
  • Level-up when accumulating experience
    levelCounter.on('levelup', function(level, fromExp, toExp, levelStartExp, levelEndExp){        }, scope);\n
    • level : To next level
    • fromExp, toExp : Experience increment from fromExp to toExp.
    • levelStartExp, levelEndExp : Range of this level.
"},{"location":"lifetime/","title":"Life time","text":""},{"location":"lifetime/#introduction","title":"Introduction","text":"

Destroy game object when time-out.

  • Author: Rex
  • Behavior of game object
"},{"location":"lifetime/#usage","title":"Usage","text":"

Sample code

"},{"location":"lifetime/#install-plugin","title":"Install plugin","text":""},{"location":"lifetime/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlifetimeplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlifetimeplugin.min.js', true);\n
  • Add life-time behavior
    var lifeTime = scene.plugins.get('rexlifetimeplugin').add(gameObject, config);\n
"},{"location":"lifetime/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LifeTimePlugin from 'phaser3-rex-plugins/plugins/lifetime-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLifeTime',\nplugin: LifeTimePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add life-time behavior
    var lifeTime = scene.plugins.get('rexLifeTime').add(gameObject, config);\n
"},{"location":"lifetime/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LifeTime from 'phaser3-rex-plugins/plugins/lifetime.js';\n
  • Add life-time behavior
    var lifeTime = new LifeTime(gameObject, config);\n
"},{"location":"lifetime/#create-instance","title":"Create instance","text":"
var lifeTime = scene.plugins.get('rexLifeTime').add(gameObject, {\nlifeTime: 1000,\n// destroy: true,\n// start: true\n});\n
  • lifeTime : Life time in ms.
  • destroy : Set true to destroy game object when time-out.
  • start: Set true to starting counting now.
"},{"location":"lifetime/#events","title":"Events","text":"
  • On time-out
    lifeTime.on('complete', function(gameObject, lifeTime){});\n// lifeTime.once('complete', function(gameObject, lifeTime){});\n
"},{"location":"lifetime/#life-time","title":"Life-time","text":"
  • Set
    lifeTime.setLifeTime(time);\n
  • Add to
    lifeTime.addToLifeTime(time);\n
  • Get life-time
    var time = lifeTime.lifeTime;\n
  • Get remainder time
    var time = lifeTime.remainder;\n
  • Is alive
    var isAlive = lifeTime.isAlive;\n
"},{"location":"lifetime/#startstoppauseresume","title":"Start/Stop/Pause/Resume","text":"
  • Start
    lifeTime.start();\n
  • Stop
    lifeTime.stop();\n
  • Pause
    lifeTime.pause();\n
  • Resume
    lifeTime.resume();\n
"},{"location":"light/","title":"Light","text":""},{"location":"light/#introduction","title":"Introduction","text":"

lighting system from normal map.

  • Author: Richard Davey

WebGL only

It only works in WebGL render mode.

"},{"location":"light/#usage","title":"Usage","text":""},{"location":"light/#light-system","title":"Light system","text":""},{"location":"light/#enable","title":"Enable","text":"
  • Enable
    scene.lights.enable();\n
  • Disable
    scene.lights.disable();\n
    or
    scene.lights.active = false;\n
"},{"location":"light/#ambient-color","title":"Ambient color","text":"
scene.lights.setAmbientColor(color);\n
  • color : Integer color value.
"},{"location":"light/#light","title":"Light","text":"
  • Add
    var light = scene.lights.addLight(x, y, radius);\n// var light = scene.lights.addLight(x, y, radius, color, intensity);\n
    • x, y : The horizontal/vertical position of the Light.
    • radius : The radius of the Light.
    • color : The integer RGB color of the light. Default is 0xffffff.
    • intensity : The intensity of the Light.
  • Remove
    scene.lights.removeLight(light);\n
"},{"location":"light/#position","title":"Position","text":"
  • Set
    light.setPosition(x, y);\n
    or
    light.x = x;\nlight.y = y;\n
  • Get
    var x = light.x;\nvar y = light.y;\n
"},{"location":"light/#color","title":"Color","text":"
  • Set
    • Red, green, blue
      light.color.set(red, green, blue);\n
      or
      light.color.r = red;\nlight.color.g = green;\nlight.color.b = blue;\n
    • Integer value
      light.setColor(colorInteger);\n
  • Get
    • Red, green, blue
      var red = light.color.r;\nvar green = light.color.g;\nvar blue = light.color.b;\n
"},{"location":"light/#size","title":"Size","text":"
  • Set
    light.setRadius(radius);\n// light.radius = radius;\n
    or
    light.diameter = diameter;\n// light.width = diameter;\n// light.height = diameter;\n// light.displayWidth = diameter;\n// light.displayHeight = diameter;\n
  • Get
    var radius = light.radius;\n
    or
    var diameter = light.diameter;\n// var diameter = light.displayWidth;\n// var diameter = light.displayHeight;\n// var diameter = light.width;\n// var diameter = light.height;\n
"},{"location":"light/#intensity","title":"Intensity","text":"
  • Set
    light.setIntensity(intensity);\n
    or
    light.intensity = intensity;\n
  • Get
    var intensity = light.intensity;\n
"},{"location":"light/#game-object","title":"Game object","text":""},{"location":"light/#load-texture-with-normal-map","title":"Load texture with normal map","text":"
scene.load.image(key, [url, normalMapUrl]);\n
  • url : Url of texture.
  • url : Url of texture.
  • normalMapUrl : Url of normal map.
"},{"location":"light/#apply-light-pipeline","title":"Apply light pipeline","text":"
gameObject.setPipeline('Light2D');\n
"},{"location":"line/","title":"Line","text":""},{"location":"line/#introduction","title":"Introduction","text":"

Draw a line with start/end/body textures, extended from RenderTexture game object.

  • Author: Rex
  • Game object
"},{"location":"line/#live-demos","title":"Live demos","text":"
  • Line
"},{"location":"line/#usage","title":"Usage","text":"

Sample code

"},{"location":"line/#install-plugin","title":"Install plugin","text":""},{"location":"line/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlineplugin.min.js', true);\n
  • Add line object
    var line = scene.add.rexLine(config);\n
"},{"location":"line/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LinePlugin from 'phaser3-rex-plugins/plugins/line-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLinePlugin',\nplugin: LinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add line object
    var line = scene.add.rexLine(config);\n
"},{"location":"line/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Line from 'phaser3-rex-plugins/plugins/line.js';\n
  • Add line object
    var line = new Line(scene, config);\nscene.add.existing(line);\n
"},{"location":"line/#create-instance","title":"Create instance","text":"
var line = scene.add.rexLine({\nstart: {\nx: 0, y: 0,\nkey: undefined, frame: undefined, origin: 0.5,\n},\n// start: key,\n// start: undefined,\n\nend: {\nx: 0, y: 0,\nkey: undefined, frame: undefined, origin: 1,\n},\n// end: key,\n// end: undefined,\n\nbody: {\nkey: undefined, frame: undefined, extendMode: 1,\nwidth: undefined,\n},\n// body: key,\n});\n
  • start : Configuration of line-start. Or texture key of line-start.
    • start.x, start.y : Position of line-start.
    • start.key, start.frame : Texrure of line-start.
    • start.origin : Origin of line-start. Default is 0.5.
  • end : Configuration of line-end. Or texture key of line-end.
    • end.x, end.y : Position of line-end.
    • end.key, end.frame : Texrure of line-end.
    • end.origin : Origin of line-end. Default is 1.
  • body : Configuration of line-body. Or texture key of line-body.
    • body.key, body.frame : Texrure of line-body. Line-body will be drawn repeatedly.
    • body.extendMode : Extend mode of line-body.
      • 0, or 'scale' : Draw line-body with scaled image game object.
      • 1, or 'repeat' : Draw line-body with tile-sprute game object. (Default value)
    • body.width : Line width.
"},{"location":"line/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLine extends Line {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var line = new MyLine(scene, config);\n
"},{"location":"line/#position-of-line-startline-end","title":"Position of line-start/line-end","text":"
  • Line start
    • Get
      var x0 = line.x0;\nvar y0 = line.y0;\n
    • Set
      line.setLineStartPosition(x, y);\n
      or
      line.x0 = x;\nline.y0 = y;\n
  • Line end
    • Get
      var x1 = line.x1;\nvar y1 = line.y1;\n
    • Set
      line.setLineEndPosition(x, y);\n
      or
      line.x1 = x;\nline.y1 = y;\n
"},{"location":"line/#set-textures","title":"Set textures","text":"
  • Line-start
    • Set line-start texture
      line.setLineStartTexture(key, frameName);\n
    • Set origin of line-start texture
      line.setLineStartOrigin(origin);\n
      • origin : 0~1. Default is 0, to align the left side of line-start texture with start position.
  • Line-end
    • Set line-end texture
      line.setLineEndTexture(key, frameName);\n
    • Set origin of line-end texture
      line.setLineEndOrigin(origin);\n
      • origin : 0~1. Default is 1, to align the right side of line-end texture with end position.
  • Line-body
    • Set line-body texture
      line.setLineBodyTexture(key, frameName);\n
    • Set line-body extend mode
      line.setLineBodyExtendMode(mode);\n
      • mode :
        • 0, or 'scale' : Draw line-body with scaled image game object.
        • 1, or 'repeat' : Draw line-body with tile-sprute game object.
    • Set line-body width
      line.setLineBodyWidth(width);\n
"},{"location":"line/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"line/#create-mask","title":"Create mask","text":"
var mask = line.createBitmapMask();\n

See mask

"},{"location":"line/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"list-inputtext/","title":"Input text","text":"

Solutions of single or multiple line(s) input text.

  • Input text game object (Display: dom / Edit: dom) :
    • Demo
      • type or inputType :
        • 'text' : Single line input.
        • 'textarea' : Multiple line input.
  • Text game object with Text edit behavior (Display: text / Edit: dom) :
    • Demo
      • type :
        • 'text' : Single line input.
        • 'textarea' : Multiple line input.
  • Text game object with Hidden text edit behavior (Display: text / Edit: text, invisible dom) :
    • Demo
      • type or inputType :
        • 'text' : Single line input.
        • 'textarea' : Multiple line input.
  • Canvas input game object (Display: canvas-input / Edit: canvas-input, invisible dom) :
    • Single line input
    • Multiple line input, Text area input
      • textArea : Set true for multiple line input.
"},{"location":"live2d/","title":"Live2d","text":""},{"location":"live2d/#introduction","title":"Introduction","text":"

Display live2d model.

  • Author: Rex
  • Game object
"},{"location":"live2d/#live-demos","title":"Live demos","text":"
  • Transform and hit area
  • Change model

The example Live2D models, Haru and Hiyori, are redistributed under Live2D's Free Material License.

"},{"location":"live2d/#usage","title":"Usage","text":"

Sample code

"},{"location":"live2d/#install-plugin","title":"Install plugin","text":""},{"location":"live2d/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlive2dplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlive2dplugin.min.js', true);\n
  • Load live2d core script, in preload stage
    scene.load.rexLive2dCoreScript(coreScriptURL);\n
  • Load model assets, in preload stage
    scene.load.rexLive2d(key, modelSettingURL);\n
  • Add live2d object
    var live2dGameObject = scene.add.rexLive2d(x, y, key, config);\n
"},{"location":"live2d/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import Live2dPlugin from 'phaser3-rex-plugins/plugins/live2d-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLive2dPlugin',\nplugin: Live2dPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Load live2d core script, in preload stage
    scene.load.rexLive2dCoreScript(coreScriptURL);\n
  • Load model assets, in preload stage
    scene.load.rexLive2d(key, modelSettingURL);\n
  • Add live2d object
    var live2dGameObject = scene.add.rexLive2d(x, y, key, config);\n
"},{"location":"live2d/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import {\nLive2dCoreScriptFileCallback,\nLive2dFileCallback,\nLive2dGameObject\n} from 'phaser3-rex-plugins/plugins/live2d.js';\n
  • Load live2d core script, in preload stage
    Live2dCoreScriptFileCallback.call(scene.load, coreScriptURL);\n
  • Load model assets, in preload stage
    Live2dFileCallback.call(scene.load, key, modelSettingURL);\n
  • Add live2d object
    var live2dGameObject = new Live2dGameObject(scene, x, y, key, config);\nscene.add.existing(live2dGameObject);\n
"},{"location":"live2d/#create-instance","title":"Create instance","text":"
var live2dGameObject = scene.add.rexLive2d(x, y, key, {\n// autoPlayIdleMotion: motionGroupName\n});\n
  • autoPlayIdleMotion : Start motion when idle (i.e. all motions are finished).

Add live2d from JSON

var live2d = scene.make.rexLive2d({\nx: 0,\ny: 0,\nkey: 256,\n// autoPlayIdleMotion: motionGroupName,\n\nadd: true\n});\n
"},{"location":"live2d/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLive2d extends Live2d {\nconstructor(scene, x, y, key, config) {\nsuper(scene, x, y, key, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var live2dGameObject = new MyLive2d(scene, x, y, key, config);\n
"},{"location":"live2d/#change-model","title":"Change model","text":"
live2dGameObject.setModel(key);\n

or

live2dGameObject.setModel(key, {\n// autoPlayIdleMotion: motionGroupName\n})\n
"},{"location":"live2d/#expression","title":"Expression","text":"
  • Set expression
    live2dGameObject.setExpression(name);\n
  • Get expression names
    var names = live2dGameObject.getExpressionNames();\n
    • names : Array of expression names
"},{"location":"live2d/#motion","title":"Motion","text":"
  • Start motion
    live2dGameObject.startMotion(group, no);\n// live2dGameObject.startMotion(group, no, priority);\n
    • group : Group name of motion
    • no : Number of motion in group
    • priority : Priority of this motion
      • 'idle', or 1
      • 'normal', or 2, default value
      • 'force' or 3
  • Start random motion
    live2dGameObject.startMotion(group);\n// live2dGameObject.startMotion(group, undefined, priority);\n
  • Stop all motions
    live2dGameObject.stopAllMotions();\n
  • Get motion names
    var names = live2dGameObject.getMotionNames();\n
  • Get motion names of a group
    var names = live2dGameObject.getMotionNames(group);\n
    • group : Group name of motion
  • Get motion group names
    var names = live2dGameObject.getMotionGroupNames();\n
  • Get current playing motion names
    var names = live2dGameObject.getPlayinigMotionNames();\n
  • Is any motion playing?
    var isPlaying = live2dGameObject.isAnyMotionPlaying();\n
  • Start motion when idle (i.e. all motions are finished)
    live2dGameObject.autoPlayIdleMotion(group);\n
    • group : Group name of motion
  • Set time-scale
    live2dGameObject.setTimeScale(timeScale);\n
    or
    live2dGameObject.timeScale = timeScale;\n
"},{"location":"live2d/#look-at","title":"Look at","text":"
  • Look at
    live2dGameObject.lookAt(x, y, {\n// camera: scene.cameras.main,\n\n// eyeBallX: 1, eyeBallY: 1,\n// angleX: 30, angleY: 30, angleZ: 30,\n// bodyAngleX: 10\n})\n
    • x, y : Look at position.
    • camera : Default value is scene.cameras.main.
    • eyeBallX, eyeBallY : Weight of parameter ParamEyeBallX, ParamEyeBallY.
    • angleX, angleY, angleZ : Weight of parameter ParamAngleX, ParamAngleY, ParamAngleZ.
    • bodyAngleX : Weight of parameter ParamBodyAngleX.
  • Look forward
    live2dGameObject.lookForward();\n
"},{"location":"live2d/#lip-sync","title":"Lip sync","text":"
  • Set lip sync value
    live2dGameObject.setLipSyncValue(value);\n
    or
    live2dGameObject.lipSyncValue = value;\n
  • Get lip sync value
    var value = live2dGameObject.lipSyncValue;\n
"},{"location":"live2d/#hit-test","title":"Hit test","text":""},{"location":"live2d/#touch-events","title":"Touch events","text":"
  1. Set interactive
    live2dGameObject.setInteractive();\n
  2. Register touch events of hit area
    • On pointer down
      live2dGameObject.on('pointerdown-' + hitAreaName, function(pointer, localX, localY, event){\n\n}, scope);\n
      or
      live2dGameObject.on('pointerdown', function(pointer, localX, localY, event){\nvar hitTestResult = live2dGameObject.getHitTestResult(); // {hitAreaName: isHit}\n}, scope);\n
    • On pointer up
      live2dGameObject.on('pointerup-' + hitAreaName, function(pointer, localX, localY, event){\n\n}, scope);\n
      or
      live2dGameObject.on('pointerup', function(pointer, localX, localY, event){\nvar hitTestResult = live2dGameObject.getHitTestResult(); // {hitAreaName: isHit}\n}, scope);\n
    • On pointer move
      live2dGameObject.on('pointermove-' + hitAreaName, function(pointer, localX, localY, event){\n\n}, scope);\n
      or
      live2dGameObject.on('pointermove', function(pointer, localX, localY, event){\nvar hitTestResult = live2dGameObject.getHitTestResult(); // {hitAreaName: isHit}\n}, scope);\n
"},{"location":"live2d/#is-hit","title":"Is hit","text":"
var isHit = live2dGameObject.hitTest(hitAreaName, x, y);\n// var isHit = live2dGameObject.hitTest(hitAreaName, x, y, camera);\n
"},{"location":"live2d/#parameter","title":"Parameter","text":"
  1. Register parameter
    live2dGameObject.registerParameter(name);\n
    • name : Register parameter id = Param + capitalize(name)
  2. Reset and add value
    live2dGameObject\n.resetParameterValue(name)\n.addParameterValue(name, value);\n
    or
    var parameters = live2dGameObject.getParameters();  // {name: value}\nparameters[name] = value;\n
"},{"location":"live2d/#limitation","title":"Limitation","text":"
  • alpha, tint properties does not work
  • Can't apply any post-fx effect or blend mode.
"},{"location":"loader/","title":"Loader","text":""},{"location":"loader/#introduction","title":"Introduction","text":"

Load assets, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"loader/#usage","title":"Usage","text":""},{"location":"loader/#loading-in-preload-stage","title":"Loading in preload stage","text":"
scene.load.image(key, url);\n// scene.load.image(config); // config: {key, url}\n

Loader in preload stage will start loading automatically by scene.

"},{"location":"loader/#loading-after-preload-stage","title":"Loading after preload stage","text":"
scene.load.image(key, url);   // add task\n// scene.load.image(config); // config: {key, url}\nscene.load.once('complete', callback, scope);  // add callback of 'complete' event\nscene.load.start();                     // start loading\n
"},{"location":"loader/#set-path","title":"Set path","text":"
scene.load.setPath(path)\n
"},{"location":"loader/#more-configurations","title":"More configurations","text":"

More configurations in game config

loader:{\nbaseURL: '',\npath: '',\nenableParallel: true,\nmaxParallelDownloads: 4,\ncrossOrigin: undefined,\nresponseType: '',\nasync: true,\nuser: '',\npassword: '',\ntimeout: 0,\nmaxRetries: 2,\nwithCredentials: false,\nimageLoadType: 'XHR',    // 'HTMLImageElement' \nlocalScheme: [ 'file://', 'capacitor://' ]\n},\n
"},{"location":"loader/#events","title":"Events","text":"
  • Load file complete event
    scene.load.on('filecomplete', function(key, type, data) {}, scope);\n
    scene.load.on('filecomplete-' + type + '-' + key, function(key, type, data) {}, scope);\n
  • Add loading file event
    scene.load.on('addfile', function(key, type, file) {}, scope);\n
  • Start loading
    scene.load.once('start', function(){}, scope);\n
  • Loading progressing
    scene.load.on('progress', function(progress){}, scope);\n
    • progress value will increase when a file is loaded, and decrease when a new file loading request is added.
      var loader = scene.load;\nvar total = loader.totalToLoad;\nvar remainder = loader.list.size + loader.inflight.size;\nvar progress = 1 - (remainder / total);\n
  • Loading file progressing
    scene.load.on('fileprogress', function(file, progress){\n// var key = file.key;\n}, scope);\n
  • Loading a file object successful
    scene.load.once('load', function(fileObj){}, scope);\n
  • Loading a file object failed
    scene.load.once('loaderror', function(fileObj){}, scope);\n
  • All loading completed
    • Before releasing resources
      scene.load.once('postprocess', function(loader){}, scope);\n
    • After releasing resources
      scene.load.once('complete', function(loader){}, scope);\n
  • Scene's 'preupdate', 'update', 'postupdate', 'render' events will be triggered during preload stage.
"},{"location":"loader/#status-of-loader","title":"Status of loader","text":"
  • Ready to start loading
    var isReady = scene.load.isReady();\n
  • Is loading
    var isLoading = scene.load.isLoading();\n
"},{"location":"loader/#file-types","title":"File types","text":""},{"location":"loader/#image","title":"Image","text":"
  • Image
    scene.load.image(key, url);\n// scene.load.image(key, url, xhrSettings);\n
    • url : Url of texture, or base64 string of Uri.
  • Image and normal map
    scene.load.image(key, [url, normalMapUrl]);\n// scene.load.image(key, [url, normalMapUrl], xhrSettings);\n
    • url : Url of texture, or base64 string of Uri.
    • normalMapUrl : Url of normal map.
  • SVG
    scene.load.svg(key, url);\n// scene.load.svg(key, url, svgConfig);\n// scene.load.svg(key, url, svgConfig, xhrSettings);\n
    • svgConfig : {width, height}, or {scale}
  • Html texture
    scene.load.htmlTexture(key, url, width, height);\n// scene.load.htmlTexture(key, url, width, height, xhrSettings);\n

Get data from texture cache

var cache = scene.textures;\nvar data = cache.get(key);\n
"},{"location":"loader/#sprite-sheet","title":"Sprite sheet","text":"
scene.load.spritesheet(key, url, {\n// frameWidth: frameWidth,\n// frameHeight: frameHeight,\n// startFrame: startFrame,\n// endFrame: endFrame,\n// margin: margin,\n// spacing: spacing\n});\n// scene.load.spritesheet(key, url, frameConfig, xhrSettings);\n

Get data from texture cache

var cache = scene.textures;\nvar data = cache.get(key);\n
"},{"location":"loader/#texture-atlas","title":"Texture atlas","text":"
scene.load.atlas(key, textureURL, atlasURL);\n// scene.load.atlas(key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings);\n

Get data from texture cache

var cache = scene.textures;\nvar data = cache.get(key);\n

On load complete

scene.load.on('filecomplete-atlasjson-' + key, function(key, type, data) {}, scope);\n
"},{"location":"loader/#multi-file-texture-atlas","title":"Multi file texture atlas","text":"
scene.load.multiatlas(key, atlasURL);\n// scene.load.multiatlas(key, atlasURL, path, baseURL, atlasXhrSettings);\n
  • atlasURL : The absolute or relative URL to load the texture atlas json data file from.
  • path : Optional path to use when loading the textures defined in the atlas data.
  • baseURL : Optional Base URL to use when loading the textures defined in the atlas data.
"},{"location":"loader/#unity-texture-atlas","title":"Unity texture atlas","text":"
scene.load.unityAtlas(key, textureURL, atlasURL);\n// scene.load.unityAtlas(key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings);\n
"},{"location":"loader/#animation","title":"Animation","text":"
scene.load.animation(key, url);\n// scene.load.animation(key, url, dataKey, xhrSettings);\n

Get data from json cache

var cache = scene.json;\nvar data = cache.get(key);\n
"},{"location":"loader/#audio","title":"Audio","text":"
scene.load.audio(key, urls);\n// scene.load.audio(key, urls, {instances: 1}, xhrSettings);\n
  • urls : The absolute or relative URL to load the audio files from, or a blob, or a base64 string of Uri.
  • config.instances : Number of audio instances for HTML5Audio. Defaults to 1.

Get data from cache

var cache = scene.cache.audio;\nvar data = cache.get(key);\n
"},{"location":"loader/#audio-sprite","title":"Audio sprite","text":"
scene.load.audioSprite(key, jsonURL, audioURL, audioConfig);\n// scene.load.audioSprite(key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings);\n
  • jsonURL : The absolute or relative URL to load the json file from.
  • audioURL : The absolute or relative URL to load the audio file from.
  • audioConfig : An object containing an instances property for HTML5Audio. Defaults to 1.
"},{"location":"loader/#video","title":"Video","text":"
scene.load.video(key, url, noAudio);\n// scene.load.video(key, url, noAudio, xhrSettings);\n
  • url : The absolute or relative URL to load the video files from, or a blob.
  • loadEvent : The load event to listen for when not loading as a blob.
    • 'loadeddata' : Data for the current frame is available. Default value.
    • 'canplay' : The video is ready to start playing.
    • 'canplaythrough' : The video can be played all the way through, without stopping.
  • asBlob : Load the video as a data blob, or via the Video element? Default value is false.
  • noAudio : Does the video have an audio track? If not you can enable auto-playing on it.
  • false : Has audio track, default behavior.

Get data from video cache

var cache = scene.video;\nvar data = cache.get(key);\n
"},{"location":"loader/#bitmap-font","title":"Bitmap font","text":"
scene.load.bitmapFont(key, textureURL, fontDataURL);\n// scene.load.bitmapFont(key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings);\n
  • textureURL : The absolute or relative URL to load the font image file from.
  • fontDataURL : The absolute or relative URL to load the font xml data file from, which created by software such as
    • Angelcode Bitmap Font Generator
    • Littera
    • Glyph Designer

Get data from cache

var cache = scene.cache.bitmapFont;\nvar data = cache.get(key);\n
"},{"location":"loader/#tile-map","title":"Tile map","text":"
  • JSON : Created using the Tiled Map Editor and selecting JSON as the export format
    scene.load.tilemapTiledJSON(key, url);\n// scene.load.tilemapTiledJSON(key, url, xhrSettings);\n
  • CSV : Created in a text editor, or a 3rd party app that exports as CSV.
    scene.load.tilemapCSV(key, url);\n// scene.load.tilemapCSV(key, url, xhrSettings);\n

Get data from cache

var cache = scene.cache.tilemap;\nvar data = cache.get(key);\n
"},{"location":"loader/#text","title":"Text","text":"
scene.load.text(key, url);\n// scene.load.text(key, url, xhrSettings);\n

Get data from cache

var cache = scene.cache.text;\nvar data = cache.get(key);\n
"},{"location":"loader/#json","title":"JSON","text":"
scene.load.json(key, url);\n// scene.load.json(key, url, dataKey, xhrSettings);\n
  • dataKey : When the JSON file loads only this property will be stored in the Cache.

Get data from cache

var cache = scene.cache.json;\nvar data = cache.get(key);\n
"},{"location":"loader/#xml","title":"XML","text":"
scene.load.xml(key, url);\n// scene.load.xml(key, url, xhrSettings);\n

Get data from cache

var cache = scene.cache.xml;\nvar data = cache.get(key);\n
"},{"location":"loader/#html","title":"HTML","text":"
scene.load.html(key, url);\n// scene.load.html(key, url, xhrSettings);\n

Get data from cache

var cache = scene.cache.html;\nvar data = cache.get(key);\n
"},{"location":"loader/#css","title":"CSS","text":"
scene.load.css(key, url);\n// scene.load.css(key, url, xhrSettings);\n

Get data from cache

var cache = scene.cache.css;\nvar data = cache.get(key);\n
"},{"location":"loader/#scene","title":"Scene","text":"
scene.load.sceneFile(key, url);\n// scene.load.sceneFile(key, url, xhrSettings);\n

The key matches the class name in the JavaScript file.

"},{"location":"loader/#script","title":"Script","text":"
scene.load.script(key, url);\n// scene.load.script(key, url, type, xhrSettings);\n
  • type :\u3000'script', or 'module'.
"},{"location":"loader/#scripts","title":"Scripts","text":"
scene.load.scripts(key, urlArray);\n// scene.load.scripts(key, urlArray, xhrSettings);\n

Add scripts in the exact order of urlArray.

"},{"location":"loader/#glsl","title":"GLSL","text":"
scene.load.glsl(key, url);\n// scene.load.glsl(key, url, shaderType, xhrSettings);\n
  • shaderType : The type of shader.
    • 'fragment' : Fragment shader. Default value.
    • 'vertex' : Vertex shader.

Get data from cache

var cache = scene.cache.shader;\nvar data = cache.get(key);\n

A glsl file can contain multiple shaders, all separated by a frontmatter block.

---\nname: type: ---\n\nvoid main(void)\n{\n}\n
"},{"location":"loader/#binary","title":"Binary","text":"
scene.load.binary(key, url, dataType);  // dataType: Uint8Array\n// scene.load.binary(key, url, dataType, xhrSettings);\n
  • dataType : Optional type to cast the binary file to once loaded.
    • Uint8Array, Uint8ClampedArray, Uint16Array Uint32Array
    • Int8Array, Int16Array, Int32Array
    • Float32Array, Float64Array
    • BigInt64Array, BigUint64Array

Get data from cache

var cache = scene.cache.binary;\nvar data = cache.get(key);\n
"},{"location":"loader/#plugin","title":"Plugin","text":"
scene.load.plugin(key, url, true); // start plugin when loaded\n// scene.load.plugin(key, url, true, undefined, xhrSettings);\n
  • url : File url or class instance.
"},{"location":"loader/#scene-plugin","title":"Scene plugin","text":"
scene.load.scenePlugin(key, url, systemKey, sceneKey);\n// scene.load.scenePlugin(key, url, systemKey, sceneKey, xhrSettings);\n
  • url : File url or class instance.
"},{"location":"loader/#file-pack","title":"File pack","text":"

Load files in JSON format.

scene.load.pack(key, url);\n// scene.load.pack(key, url, dataKey, xhrSettings);\n

or

scene.load.pack(key, json);\n// scene.load.pack(key, json, dataKey);\n
  • dataKey : When the JSON file loads only this property will be stored in the Cache.

JSON pack file:

{\n'dataKey': {\n// \"prefix\": \"...\",          // optional, extend key by prefix\n// \"path\": \"...\",            // optional, extend url by path\n// \"defaultType\": \"image\",   // optional, default file type\n'files': [\n{\n'type': 'image',\n'key': '...',\n'url': '...'\n},\n{\n'type': 'image',\n'key': '...',\n'url': '...'\n}\n// ...\n]\n},\n\n'node0': {\n'node1': {\n'node2': {\n'files': [\n// ....\n]\n}\n}\n}\n// dataKey: 'node0.node1.node2'\n}\n

File type:

  • audio
  • binary
  • glsl
  • html
  • htmlTexture
  • image
  • json
  • script
  • spritesheet
  • svg
  • text
  • tilemapCSV
  • tilemapJSON
  • xml

Get pack json data from cache

var cache = scene.cache.json;  // pack json is stored in json cache\nvar data = cache.get(key);\n

Event name in 'filecomplete' event : 'filecomplete-packfile-' + key

"},{"location":"loader/#remove-pack-assets","title":"Remove pack assets","text":"
scene.load.removePack(key);\n// scene.load.removePack(key, dataKey);\n
"},{"location":"loader/#replace","title":"Replace","text":"
  1. Remove key.
  2. Load file again.
"},{"location":"loader/#cache","title":"Cache","text":""},{"location":"loader/#get-data","title":"Get data","text":"
var cache = scene.cache.text;\nvar data = cache.get(key);\n
"},{"location":"loader/#add-data","title":"Add data","text":"
var cache = scene.cache.text;\nvar data = cache.add(key);\n
"},{"location":"loader/#release-data","title":"Release data","text":"
var cache = scene.cache.text;\ncache.remove(key);\n
"},{"location":"loader/#data-in-cache","title":"Data in cache","text":"
var cache = scene.cache.text;\nvar hasData = cache.exists(key);\n// var hasData = cache.has(key);\n
"},{"location":"loader/#cache-events","title":"Cache events","text":"
  • Add any item
    cache.events.on('add', function(cache, key, item){\n\n})\n
  • Remove any item
    cache.events.on('remove', function(cache, key, item){\n\n})\n
"},{"location":"loader/#xhr-settings-object","title":"XHR Settings Object","text":"

Parameter xhrSettings

{\nasync: true,\nuser: '',\npassword: '',\ntimeout: 0,\nheaders: undefined,\nheader: undefined,\nheaderValue: undefined,\nrequestedWith: undefined,\noverrideMimeType: undefined,\nwithCredentials: false\n}\n
  • user : Optional username for the XHR request.
  • password : Optional password for the XHR request.
  • timeout : Optional XHR timeout value.
  • headers, header, headerValue, requestedWith : This value is used to populate the XHR setRequestHeader
  • overrideMimeType : Provide a custom mime-type to use instead of the default.
  • withCredentials : Whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests.
"},{"location":"loading-animation-scene/","title":"Loading animation scene","text":""},{"location":"loading-animation-scene/#introduction","title":"Introduction","text":"

Start loading animation scene, stop this scene when loading complete.

  • Author: Rex
  • Methods
"},{"location":"loading-animation-scene/#live-demos","title":"Live demos","text":"

Loading animation scene

"},{"location":"loading-animation-scene/#usage","title":"Usage","text":"

Sample code

"},{"location":"loading-animation-scene/#install-plugin","title":"Install plugin","text":""},{"location":"loading-animation-scene/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexloadinganimationsceneplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexloadinganimationsceneplugin.min.js', true);\n
  • In mainScene, start loading animation scene, or in animation scene, monitor loading status of mainScene.
    scene.plugins.get('rexloadinganimationsceneplugin').startScene(scene, animationSceneKey);\n
  • This plugin will also install AwaitLoader.
"},{"location":"loading-animation-scene/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LoadingAnimationScenePlugin from 'phaser3-rex-plugins/plugins/loadinganimationscene-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLoadingAnimationScene',\nplugin: LoadingAnimationScenePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • In mainScene, start loading animation scene, or in animation scene, monitor loading status of mainScene.
    scene.plugins.get('rexLoadingAnimationScene').startScene(config);\n
  • This plugin will also install AwaitLoader.
"},{"location":"loading-animation-scene/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import StartLoadingAnimationScene from 'phaser3-rex-plugins/plugins/loadinganimationscene.js';\n
  • In mainScene, start loading animation scene, or in animation scene, monitor loading status of mainScene.
    StartLoadingAnimationScene(config);\n
"},{"location":"loading-animation-scene/#start-loading-animation-scene","title":"Start loading animation scene","text":"

In mainScene, start loading animation scene, or in animation scene, monitor loading status of mainScene.

scene.plugins.get('rexLoadingAnimationScene').startScene({\nmainScene: animationScene:\n\nonLoadingComplete: undefined\nonLoadingProgress: undefined\n});\n
  • mainScene : Scene instaance of main scene.
  • animationScene : Scene instance or scene-key of animation scene.
    • This animation scene will be stopped wheen main scene's loading complete totally.
  • onLoadingComplete : Custom task invoked when loading complete.
    function(finishLoading, animationScene) {\n// finishLoading();\n}\n
    • Invoke finishLoading() method (later) to finish loading progress totally.
  • onLoadingProgress : Callback when loading progress is changing.
    function(progress, animationScene) {\n\n}\n
"},{"location":"loadingprogress/","title":"Loading progress","text":""},{"location":"loadingprogress/#introduction","title":"Introduction","text":"

Pop-up dialog for loading-progress, then scale-down this dialog.

  • Author: Rex
  • Behavior of game object
"},{"location":"loadingprogress/#live-demos","title":"Live demos","text":"
  • Loading progress
  • Custom transit
"},{"location":"loadingprogress/#usage","title":"Usage","text":"

Sample code

"},{"location":"loadingprogress/#install-plugin","title":"Install plugin","text":""},{"location":"loadingprogress/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexloadingprogressplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexloadingprogressplugin.min.js', true);\n
  • Add loading-progress behavior
    var loadingProgress = scene.plugins.get('rexloadingprogressplugin').add(gameObject, config);\n
"},{"location":"loadingprogress/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add loading-progress behavior
    var loadingProgress = scene.plugins.get('rexLoadingProgress').add(gameObject, config);\n
"},{"location":"loadingprogress/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LoadingProgress from 'phaser3-rex-plugins/plugins/loadingprogress.js';\n
  • Add loadingprogress behavior
    var loadingProgress = new LoadingProgressBehavoir(gameObject, config);\n
"},{"location":"loadingprogress/#create-instance","title":"Create instance","text":"
var loadingProgress = scene.plugins.get('rexLoadingProgress').add(gameObject, {\n// duration: {\n//     in: 200,\n//     out: 200\n// }\n\n// progress: function(gameObject, progress) {},\n// transitIn: function(gameObject, duration) {},\n// transitOut: function(gameObject, duration) {},\n});\n
  • gameObject : Game object for presenting loading-progress.
  • duration : Duration of transition-in, trantion-out.
    • duration.in : Duration of transition-in (open dialog).
      • 0 : No transition, open dialog immediately.-
    • duration.out : Duration of transition-out (close dialog). Game object will be destroyed after transiting out.
      • 0 : No transition, close dialog immediately.
  • progress : Callback of loading-progress
    function(gameObject, progress) {\n\n}\n
    • progress : Number between 0 to 1.
  • transitIn : Tween behavior of opening dialog.
    • Custom callback
      function(gameObject, duration) {\n\n}\n
  • transitOut : Tween behavior of closing dialog.
    • Custom callback
      function(gameObject, duration) {\n\n}\n
"},{"location":"loadingprogress/#events","title":"Events","text":"
  • On progress
    loadingProgress.on('progress', function(progress) {\n})\n
  • On opened dialog
    loadingProgress.on('open', function(gameObject, loadingProgress) {\n})\n
  • On closed dialog
    loadingProgress.on('close', function() {\n})\n
"},{"location":"localforage-files/","title":"Files","text":""},{"location":"localforage-files/#introduction","title":"Introduction","text":"

Save JSON data, using localforage.

Each file contains header and content indexed by fileID.

  • Author: Rex
  • Member of scene
"},{"location":"localforage-files/#usage","title":"Usage","text":"

Sample code

"},{"location":"localforage-files/#install-plugin","title":"Install plugin","text":""},{"location":"localforage-files/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlocalforagefilesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlocalforagefilesplugin.min.js', true);\n
  • Add localforage-files object
    var fileManager = scene.plugins.get('rexlocalforagefilesplugin').add(config);\n
"},{"location":"localforage-files/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FilesPlugin from 'phaser3-rex-plugins/plugins/localforagefiles-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFiles',\nplugin: FilesPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add localforage-files object
    var fileManager = scene.plugins.get('rexFiles').add(config);\n
"},{"location":"localforage-files/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Files from 'phaser3-rex-plugins/plugins/localforagefiles.js';\n
  • Add localforage-files object
    var fileManager = new Files(config);\n
"},{"location":"localforage-files/#create-instance","title":"Create instance","text":"
var fileManager = scene.plugins.get('rexFiles').add.files({\n// name: 'files',\n// zip: true\n});\n
  • name : Storage name.
  • zip :
    • true : Save compressed stringify json data.
    • false : Save json data directly
"},{"location":"localforage-files/#save-file","title":"Save file","text":"
  • Overwrite
    fileManager.save(fileID, header, content);\n
    • fileID : Unique ID of this file.
    • header : Header data for indexing, a JSON object.
      • Reserve keys : fileID.
    • content : Content/body, a JSON object.
      • Reserve keys : fileID.
  • Update
    fileManager.save(fileID, header, content, true);\n
"},{"location":"localforage-files/#load-headers","title":"Load headers","text":"
fileManager.loadHeaders()\n.then(function(result) { // var headers = result.headers;\n})\n.catch(function(result) {\n// var error = result.error;\n})\n
  • headers : Get header by headers[fileID], each header contains
    • header.fileID : Unique ID of this file.
"},{"location":"localforage-files/#load-file","title":"Load file","text":"
fileManager.load(fileID)\n.then(function(result) { // var header = result.header;\n// var content = result.content;\n// var fileID = result.fileID;\n})\n.catch(function(result) {\n// var error = result.error;\n// var fileID = result.fileID;\n})\n
  • header, content : Header/content of this file.
  • fileID : Unique ID of this file.
  • userID : User ID of file owner.
"},{"location":"localforage/","title":"LocalForage","text":""},{"location":"localforage/#introduction","title":"Introduction","text":"

Offline storage, improved.

  • Author: Mozilla
"},{"location":"localforage/#usage","title":"Usage","text":"

Official document

Sample code

By default, LocalForage selects backend drivers for the datastore in this order:

  1. IndexedDB
  2. WebSQL
  3. localStorage
"},{"location":"localforage/#save-data","title":"Save data","text":"
  • Callback
    localforage.setItem(key, value, function(){ /* ... */ });\n
  • Promise
    localforage.setItem(key, value)\n.then(function(value){ /* ... */ })\n.catch(function(err){ /* ... */ });\n
"},{"location":"localforage/#read-data","title":"Read data","text":"
  • Callback
    localforage.getItem(key, function(err, value){ /* ... */ });\n
  • Promise
    localforage.getItem(key)\n.then(function(value){ /* ... */ })\n.catch(function(err){ /* ... */ });\n
"},{"location":"localforage/#remove-data","title":"Remove data","text":"
  • Callback
    localforage.removeItem(key, function(){ /* ... */ });\n
  • Promise
    localforage.removeItem(key)\n.then(function(value){ /* ... */ })\n.catch(function(err){ /* ... */ });\n
"},{"location":"localstorage-data/","title":"Data manager","text":""},{"location":"localstorage-data/#introduction","title":"Introduction","text":"

Sync data from data manager to local-storage.

  • Author: Rex
  • Member of scene

Max Size

5MB per app per browser.

"},{"location":"localstorage-data/#live-demos","title":"Live demos","text":"
  • Extend game registry
  • New local storage data manager
"},{"location":"localstorage-data/#usage","title":"Usage","text":"

Sample code

"},{"location":"localstorage-data/#install-plugin","title":"Install plugin","text":""},{"location":"localstorage-data/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlocalstoragedataplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlocalstoragedataplugin.min.js', true);\n
  • Extend existed data object (game.registry, or scene.data)
    var data = scene.plugins.get('rexlocalstoragedataplugin').extend(game.registry, config);\n// var data = scene.plugins.get('rexlocalstoragedataplugin').extend(scene.data, config);\n
  • New local storage data manager
    var data = scene.plugins.get('rexlocalstoragedataplugin').add(parent, config);\n
"},{"location":"localstorage-data/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LocalStorageDataPlugin from 'phaser3-rex-plugins/plugins/localstoragedata-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLocalStorageData',\nplugin: LocalStorageDataPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Extend existed data object (game.registry, or scene.data)
    var data = scene.plugins.get('rexLocalStorageData').extend(game.registry, config);\n// var data = scene.plugins.get('rexLocalStorageData').extend(scene.data, config);\n
  • New local storage data manager
    var data = scene.plugins.get('rexLocalStorageData').add(parent, config);\n
"},{"location":"localstorage-data/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LocalStorageData from 'phaser3-rex-plugins/plugins/localstoragedata.js';\n
  • New local storage data manager
    var data = new LocalStorageData(parent, config);\n
"},{"location":"localstorage-data/#create-instance","title":"Create instance","text":"
var data = scene.plugins.get('rexLocalStorageData').add({\n// name: '',\n// load: true,\n// default: undefined,\n// reset: false\n});\n// var data = scene.plugins.get('rexLocalStorageData').add(parent, config);\n// var data = scene.plugins.get('rexRData').add(parent, eventEmitter, config);\n
  • name : Prefix of key in local storage.
  • load :
    • true : Load data from local storage. Default behavior.
    • false : Don't load data now.
  • default : Define valid keys and default values of loaded data.
    • undefined : Load all keys from local storage.
  • reset :
    • true : Reset all data to default values (default), clear keys which are not in defaultData.
  • parent : The object (a scene, or a game object) that this DataManager belongs to.
  • eventEmitter : The DataManager's event emitter.
"},{"location":"localstorage-data/#load","title":"Load","text":"
data.load(defaultData);\n// data.load(defaultData, reset);\n
  • defaultData : Define valid keys and default values of loaded data.
    • undefined : Load all keys from local storage. reset will be false in this case.
  • reset :
    • true : Reset all data to default values (defaultData), clear keys which are not in defaultData.

Note

Data loaded from local storage already, if load is true.

"},{"location":"localstorage-data/#getsetremove-value","title":"Get/set/remove value","text":"

See built-in data manager.

"},{"location":"localstorage-data/#reserved-keys","title":"Reserved keys","text":"

'__keys__' is used internally by this plugin.

"},{"location":"localstorage-data/#get-default-value","title":"Get default value","text":"
var value = data.getDefaultValue(key);\n
"},{"location":"localstorage/","title":"LocalStorage","text":""},{"location":"localstorage/#introduction","title":"Introduction","text":"

Store small data in key-value pairs locally within the user's browser.

  • Author: Built-in javascript function

Max Size

5MB per app per browser.

"},{"location":"localstorage/#usage","title":"Usage","text":"

Reference

Sample code

"},{"location":"localstorage/#save-data","title":"Save data","text":"
localStorage.setItem(key, value);\n
"},{"location":"localstorage/#read-data","title":"Read data","text":"
var value = localStorage.getItem(key);\n

Note

The keys and the values are always strings. Objects, integer keys will be automatically converted to strings.

"},{"location":"localstorage/#remove-data","title":"Remove data","text":"
localStorage.removeItem(key);\n
"},{"location":"lokijs/","title":"LokiJs","text":""},{"location":"lokijs/#introduction","title":"Introduction","text":"

In-memory JavaScript Datastore with Persistence.

  • Reference
  • Document
"},{"location":"lokijs/#usage","title":"Usage","text":"

Sample code

"},{"location":"lokijs/#create-database","title":"Create database","text":"
var db = new loki();\n// var db = new loki('loki.json', config);  // load database from file\n
"},{"location":"lokijs/#create-collection","title":"Create collection","text":"
var collection = db.addCollection(name);\n// var collection = db.addCollection(name, config);\n
"},{"location":"lokijs/#get-collection","title":"Get collection","text":"
var collection = db.getCollection(name);\n
"},{"location":"lokijs/#insert-document","title":"Insert document","text":"
var docInColl = collection.insert(doc);  // doc: an object\n

Get Id

var id = docInColl.$loki;\n
"},{"location":"lokijs/#insert-documents","title":"Insert documents","text":"
collection.insert(docArray);  // documents in array\n
"},{"location":"lokijs/#query","title":"Query","text":""},{"location":"lokijs/#get-document-by-id","title":"Get document by id","text":"
var doc = collection.get(id);  // id: `$loki`\n
"},{"location":"lokijs/#get-doc-by-unique-index","title":"Get doc by unique index","text":"
var doc = collection.by(key, value);\n
"},{"location":"lokijs/#filter-documents","title":"Filter documents","text":"
  • $eq : filter for document(s) with property of (strict) equality
    var docArray = collection.find({key: value});\n// var docArray = collection.find({key: {'$eq': value});\n
  • $aeq : filter for document(s) with property of abstract (loose) equality
    var docArray = collection.find({key: {'$aeq': value}});\n
    For example
    var results = coll.find({age: {'$aeq': 20}});  // age == '20' or age == 20\n
  • $ne : filter for document(s) with property not equal to provided value
    var docArray = collection.find({key: {'$ne': value}});\n
  • $gt : filter for document(s) with property greater than provided value
    var docArray = collection.find({key: {'$gt': value}});\n
  • $gte : filter for document(s) with property greater or equal to provided value
    var docArray = collection.find({key: {'$gte': value}});\n
  • $lt : filter for document(s) with property less than provided value
    var docArray = collection.find({key: {'$lt': value}});\n
  • $lte : filter for document(s) with property less than or equal to provided value
    var docArray = collection.find({key: {'$lte': value}});\n
  • $between : filter for documents(s) with property between provided values
    var docArray = collection.find({key: {'$between': [value0, value1]}});\n
  • $in : filter for document(s) with property matching any of the provided array values
    var docArray = collection.find({key: {'$in': [value0, value1, ...]}});\n
    Your property should not be an array but your compare values should be.
  • $nin : filter for document(s) with property not matching any of the provided array values
    var docArray = collection.find({key: {'$nin': [value0, value1, ...]}});\n
  • $contains : filter for document(s) with property containing the provided value
    var docArray = collection.find({key: {'$contains': value}});\n
    Use this when your property contains an array but your compare value is not an array
  • $containsAny : filter for document(s) with property containing any of the provided values
    var docArray = collection.find({key: {'$containsAny': [value0, value1, ...]}});\n
  • $containsNone : filter for documents(s) with property containing none of the provided values
    var docArray = collection.find({key: {'$containsNone': [value0, value1, ...]}});\n
  • $regex : filter for document(s) with property matching provided regular expression
    var docArray = collection.find({key: {'$regex': pattern}});\n// var docArray = collection.find({key: {'$regex': [pattern, options]});\n
    For example
    var docArray = collection.find({key: { '$regex': 'din' }});\nvar docArray = collection.find({key: { '$regex': ['din', 'i'] }});\n
  • $dteq: filter for document(s) with date property equal to provided date value
    var docArray = collection.find({key: {'$dteq': new Date('1/1/2017')}});\n
  • $type : filter for documents which have a property of a specified type
    var docArray = collection.find({key: {'$type': value}}); // 'string', or 'number', ...\n
  • $size : filter for documents which have array property of specified size
    var docArray = collection.find({key: {'$size': value}});\n
    (does not work for strings)
  • $len : filter for documents which have string property of specified length
    var docArray = collection.find({key: {'$len': value}});\n
  • $or : filter for documents which meet any of the nested subexpressions
    var docArray = collection.find({'$or': [\n{key0: {'$lt': value0}},\n{key1: {'$gte': value1}},\n// ...\n]});\n
"},{"location":"lokijs/#find-one-document","title":"Find one document","text":"
var doc = collection.findOne({});\n
"},{"location":"lokijs/#filter-by-function","title":"Filter by function","text":"
var docArray = collection.where(function(doc){\n// ...\nreturn isPicked;  // true to pick this document\n})\n
"},{"location":"lokijs/#sort","title":"Sort","text":"
  • Sort with a key
    var docArray = collection.chain().find({}).simplesort(key).data();  // ascending\n// var docArray = collection.chain().find({}).simplesort(key, {desc: true}).data();  // descending\n
  • Sort with mutiple keys
    var docArray = collection.chain().find({}).compoundsort([key0, key1]).data();  // key0, key1: ascending\n// var docArray = collection.chain().find({}).compoundsort([key0, [key1, true]]).data(); // key0: ascending, key1: descending\n
  • Sort with function
    var docArray = collection.chain().find({}).sort(\nfunction(doc1, doc2) {\nreturn result; // 0, 1, -1\n})\n.data();\n
    result:
    • 0: equal
    • 1: greater
    • -1: less
"},{"location":"lokijs/#pagination","title":"Pagination","text":"

Get documents from start to start+count-1.

var docArray = collection.chain().find({}).offset(start).limit(count).data();\n
"},{"location":"lokijs/#update","title":"Update","text":"

Update each filtered documents.

var docArray = collection.chain().find({}).update(\nfunction(doc) { //\nreturn doc;\n});\n
"},{"location":"lokijs/#remove","title":"Remove","text":"

Remove filtered documents.

collection.chain().find({}).remove();\n
"},{"location":"lokijs/#map","title":"Map","text":"

Map document into a new anonymous collection, won't affect original collection.

var docArray = collection.chain().find({}).map(\nfunction(doc) {\n// ...\nreturn doc\n})\n.data();\n
"},{"location":"lokijs/#map-reduce","title":"Map-reduce","text":"
  1. Map document into a new anonymous collection
  2. Run reduceFn to get final result value from result set of step 1.
var mapFn = function(doc) {\n// ...\nreturn doc\n};\nvar reduceFn = function(docArray) {\n// ...\nreturn result;\n}\nvar result = collection.chain().find({}).mapReduce(mapFn, reduceFn);\n
"},{"location":"lokijs/#clone-result-set","title":"Clone result set","text":"
var resultSet = collection.chain().find({});\nvar resultSetClone = resultSet.branch();\n\n// resultSetClone.find({}).data();\n
"},{"location":"lokijs/#dynamic-view","title":"Dynamic view","text":"
  1. Create dynamic view
    var view = children.addDynamicView(name);\n
  2. Add filters
    • find
      view.applyFind({});\n
    • where
      view.applyWhere(function(doc) { return true; });\n
    • simple sort
      view.applySimpleSort(key);\n
    • sort by multiple keys
      view.applySortCriteria([key0, key1]);\n// view.applySortCriteria([key0, [key1, true]]);\n
    • sort function
      view.applySort(function(doc1, doc2) {\nreturn result; // 0, 1, -1\n});\n
      result:
      • 0: equal
      • 1: greater
      • -1: less
  3. Get result data
    var docArray = view.data();\n

Add new filters

var docArray = view.branchResultset().find({}).data();\n

"},{"location":"lokijs/#speed-up-quering","title":"Speed-up quering","text":""},{"location":"lokijs/#custom-unique-index","title":"Custom unique index","text":"
  1. Define custom unique index
    var collection = db.addCollection(name, {\nunique: [key0]\n});\n
  2. Get document by custom unique index
    var doc = collection.by(key0, value);\n
"},{"location":"lokijs/#binary-indices","title":"Binary indices","text":"
  1. Define binary index
    var collection = db.addCollection(name, {\nindices: [key0]\n});\n
    Or
    collection.ensureIndex(key);\n
  2. Get documents by normal filters
    var docArray = collection.find({key0: {'$gt': value}});\n
"},{"location":"lokijs/#methods-of-collection","title":"Methods of collection","text":"
  • Average value of a property
    var avgValue = collection.avg(key);\n
  • Maximum value of a property
    var maxValue = collection.max(key);\n
  • Minimum value of a property
    var minValue = collection.min(key);\n
  • Median value of a property
    var medianValue = collection.median(key);\n
  • Amount of documents
    var amount = collection.count(query);  // {key: {'$gt': value}}\n
"},{"location":"lokijs/#serialize-deserialize","title":"Serialize & Deserialize","text":"
  • Database as string
    var s = db.serialize();\n
  • Load database from string
    db.loadJSON(s);\n
"},{"location":"luxon/","title":"Luxon","text":""},{"location":"luxon/#introduction","title":"Introduction","text":"

Parse, validate, manipulate, and display dates and times. Reference

"},{"location":"luxon/#usage","title":"Usage","text":"
  • Install
  • Getting started
    • Demo
    • A quick tour
    • API
"},{"location":"luxon/#creating-a-datetime","title":"Creating a DateTime","text":"
const dt = DateTime.local(2017, 5, 15, 8, 30);\n

or

var dt = DateTime.fromISO('2017-05-15');\n// var dt = DateTime.fromISO('2017-05-15T17:36');\n// var dt = DateTime.fromISO('2017-W33-4');\n// var dt = DateTime.fromISO('2017-W33-4T04:45:32.343');\n
"},{"location":"luxon/#current-date-and-time","title":"Current date and time","text":"
const now = DateTime.now();\n// const now = DateTime.local();\n
"},{"location":"luxon/#json","title":"JSON","text":"
  • To JSON
    var json = dt.toObject();\n
  • From JSON
    var dt = DateTime.fromObject(json);\n// var dt = DateTime.fromObject({year: 2017, month: 5, day: 15, hour: 17, minute: 36});\n
"},{"location":"luxon/#math","title":"Math","text":"
var dt1 = dt0.plus({ hours: 3, minutes: 2 });\nvar dt1 = dt0.minus({ days: 7 });\nvar dt1 = dt0.startOf('day');\nvar dt1 = dt0.endOf('hour');\n
"},{"location":"luxon/#difference","title":"Difference","text":"
var i1 = DateTime.fromISO('1982-05-25T09:45'),\ni2 = DateTime.fromISO('1983-10-14T10:30');\ni2.diff(i1).toObject() //=> { milliseconds: 43807500000 }\ni2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }\ni2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }\ni2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }\n
"},{"location":"luxon/#durations","title":"Durations","text":"
var dur = Duration.fromObject({ hours: 2, minutes: 7 });\n// dt.plus(dur);\n\ndur.as('seconds') //=> 7620\ndur.toObject()    //=> { hours: 2, minutes: 7 }\ndur.toISO()       //=> 'PT2H7M'\n
"},{"location":"luxon/#parseformat","title":"Parse/Format","text":"
  • Parse
    var dt = DateTime.fromFormat('12-16-2017', 'MM-dd-yyyy');\n// var dt = DateTime.fromFormat('May 25, 1982', 'MMMM dd, yyyy');\n// var dt = DateTime.fromFormat('mai 25, 1982', 'MMMM dd, yyyy', { locale: 'fr' });\n
  • Format
    var s = dt.toFormat('MM-dd-yyyy');\n// var s = dt.toFormat('MMMM dd, yyyy')\n// var s = dt.setLocale('fr').toFormat('MMMM dd, yyyy')\n
"},{"location":"luxon/#relative-time","title":"Relative time","text":"

Returns a string representation of this date relative to today.

var s = dt.toRelativeCalendar();\n
var s = dt.toRelativeCalendar({\nbase: dt0,\nlocale: string,\nunit: string\n});\n
  • base : The DateTime to use as the basis to which this time is compared. Defaults to now.
  • locale : Override the locale of this DateTime.
  • unit : Use a specific unit; if omitted, the method will pick the unit. Use one of 'years', 'quarters', 'months', 'weeks', or 'days'
"},{"location":"lzstring/","title":"LZ string","text":""},{"location":"lzstring/#introduction","title":"Introduction","text":"

Compress string using LZ-based compression algorithm. Reference

  • Author: Rex
  • Member of scene
"},{"location":"lzstring/#usage","title":"Usage","text":"

Sample code

"},{"location":"lzstring/#install-plugin","title":"Install plugin","text":""},{"location":"lzstring/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlzstringplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlzstringplugin.min.js', true);\n
  • Add lz-string object
    var lzstring = scene.plugins.get('rexlzstringplugin').add(config);\n
"},{"location":"lzstring/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LZStringPlugin from 'phaser3-rex-plugins/plugins/lzstring-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLZString',\nplugin: LZStringPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add lz-string object
    var lzstring = scene.plugins.get('rexLZString').add(config);\n
"},{"location":"lzstring/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LZString from 'phaser3-rex-plugins/plugins/lzstring.js';\n
  • Add lz-string object
    var lzstring = new LZString(config);\n
"},{"location":"lzstring/#create-instance","title":"Create instance","text":"
var lzstring = scene.plugins.get('rexLZString').add({\n// encoding: 'none'     // 'none'|0, 'base64'|1, 'utf16'|2, 'uri'|3\n});\n
  • encoding :
    • 'none', or 0 : no encoding.
    • 'base64', or 1 : base64 encoding.
    • 'utf16', or 2 : UTF16 encoding.
    • 'uri', or 3 : URI encoding.
"},{"location":"lzstring/#compression","title":"Compression","text":"
var compressionResult = lzstring.compress(src);\n
"},{"location":"lzstring/#decompression","title":"Decompression","text":"
var decompressionResult = lzstring.decompress(compressionResult);\n
"},{"location":"lzstring/#set-encoding","title":"Set encoding","text":"
lzstring.setEncoding(m);  // 0|'none'|1|'base64'|2|'utf16'|3|'uri'\n
"},{"location":"mainloop/","title":"Main loop","text":"
  1. game.events prestep event. Global Managers like Input and Sound update.
    1. trigger game.sound.update()
  2. game.events step event. User-land code and plugins
    • Register event
      scene.game.events.on('step', function(time, delta){\n//\n}, scope);\n
  3. Update the Scene Manager and all active Scenes
    1. scene.events preupdate event
      • Register event
        scene.events.on('preupdate', function(time, delta){\n//\n}, scope);\n
      • InputPlugin.preUpdate()
      • TweenManager.preUpdate() to arrange active targets
      • UpdateList.preUpdate(), to arrange game objects in UpdateList
    2. scene.events update event
      • Register event
        scene.events.on('update', function(time, delta){\n//\n}, scope);\n
      • TweenManager.update(), to run active tweens
      • UpdateList.update
        • gameObject.preUpdate
      • Update arcade world
    3. scene.update()
    4. scene.events postupdate event
      • Register event
        scene.events.on('postupdate', function(time, delta){\n//\n}, scope);\n
  4. game.events poststep event. Final event before rendering starts.
    • Register event
      scene.game.events.on('poststep', function(time, delta){\n//\n}, scope);\n
  5. game.renderer.preRender()
  6. game.events prerenderclear event
    • Register event
      scene.game.events.on('prerenderclear', function(){\n//\n}, scope);\n
  7. game.events prerender event
    • Register event
      scene.game.events.on('prerender', function(){\n//\n}, scope);\n
  8. SceneManager.render()
    1. Sort display list
    2. scene.events prerender event
      • Register event
        scene.events.on('prerender', function(renderer){\n//\n}, scope);\n
    3. Render cameras
    4. scene.events render event
      • Register event
        scene.events.on('render', function(renderer){\n//\n}, scope);\n
  9. game.renderer.postRender()
  10. game.events postrender event. Final event before the step repeats.
    • Register event
      scene.game.events.on('postrender', function(renderer, time, delta){\n//\n}, scope);\n

Note

Each scene is a standalone system.

"},{"location":"mainloop/#flow-chart","title":"Flow chart","text":""},{"location":"mainloop/#game-loop","title":"Game loop","text":"
graph TB\n\nsubgraph Render\nGameRenderPreRender[\"game.renderer.preRender()\"]\nGameEventPreRenderClear>\"game.events: prerenderclear\"]\nGameEventPreRender>\"game.events: prerender\"]\nSceneManagerRender[\"SceneManager.render()<br>...See 'Scene steps'...\"]\nGameRenderPostRender[\"game.renderer.postRender()\"]\nGameEventPostRender>\"game.events: postrender\"]\nend\n\nsubgraph Step\nGameEventPreStep>\"game.events: prestep<br><br>sound.update()\"]\nGameEventStep>\"game.events: step\"]\nSceneManagerUpdate[\"SceneManager.update()<br>...See 'Scene steps'...\"]\nGameEventPostStep>\"game.events: poststep\"]\nend\n\n\nGameEventPreStep --> GameEventStep\nGameEventStep --> SceneManagerUpdate\nSceneManagerUpdate --> GameEventPostStep\nGameEventPostStep --> GameRenderPreRender\nGameRenderPreRender --> GameEventPreRenderClear\nGameEventPreRenderClear --> GameEventPreRender\nGameEventPreRender --> SceneManagerRender\nSceneManagerRender --> GameRenderPostRender\nGameRenderPostRender --> GameEventPostRender\nGameEventPostRender --> GameEventPreStep
"},{"location":"mainloop/#scene-steps","title":"Scene steps","text":"
graph TB\n\nsubgraph Render\nSceneEventPreRender>\"scene.events: prerender\"]\nSceneCameraRender[\"scene.cameras.render()\"]\nSceneEventRender>\"scene.events: render\"]\nend\n\nsubgraph Update\nSceneEventPreUpdate>\"scene.events: preupdate<br><br>InputPlugin.preUpdate()<br>TweenManager.preUpdate()<br>UpdateList.preUpdate()\"]\nSceneEventUpdate>\"scene.events: update<br><br>TweenManager.update()<br>UpdateList.update()<br>gameObject.preUpdate()\"]\nSceneUpdate[\"scene.update()\"]\nSceneEventPostUpdate>\"scene.events: postupdate\"]\nend\n\n\nSceneEventPreUpdate --> SceneEventUpdate\nSceneEventUpdate --> SceneUpdate\nSceneUpdate --> SceneEventPostUpdate\n\nSceneEventPostUpdate -.-> SceneEventPreRender\nSceneEventPreRender --> SceneCameraRender\nSceneCameraRender --> SceneEventRender
"},{"location":"mainloop/#rendering-order","title":"Rendering order","text":"
  • For each scene from bottom to top, in game
    • For each camera from bottom to top, in scene
      • For each game object from bottom to top in scene's displayList
        • Render this game object
          • Render children game objects, if game object is a container or a layer

Note

A game object can be seen by all cameras of this scene, therefore game object could be rendering more than one times.

See also Ignore game object

"},{"location":"markedeventsheet/","title":"Markdown event sheets","text":""},{"location":"markedeventsheet/#introduction","title":"Introduction","text":"

Event sheets contains main condition(s) and actions, in simple markdown format (headings, code block).

  • Author: Rex
  • Member of scene
"},{"location":"markedeventsheet/#live-demos","title":"Live demos","text":"
  • Command executor
"},{"location":"markedeventsheet/#usage","title":"Usage","text":"
  • Sample code
  • Event sheets
"},{"location":"markedeventsheet/#install-plugin","title":"Install plugin","text":""},{"location":"markedeventsheet/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexmarkedeventsheetsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexmarkedeventsheetsplugin.min.js', true);\n
  • Add event-sheet-manager object
    var eventSheetManager = scene.plugins.get('rexmarkedeventsheetsplugin').add(config);\n
"},{"location":"markedeventsheet/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import MarkedEventSheetsPlugin from 'phaser3-rex-plugins/plugins/markedeventsheets-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexMarkedEventSheets',\nplugin: MarkedEventSheetsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add event-sheet-manager object
    var eventSheetManager = scene.plugins.get('rexMarkedEventSheets').add(config);\n
"},{"location":"markedeventsheet/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import MarkedEventSheets from 'phaser3-rex-plugins/plugins/markedeventsheets.js';\n
  • Add event-sheet-manager object
    var eventSheetManager = new MarkedEventSheets(config);\n
"},{"location":"markedeventsheet/#create-instance","title":"Create instance","text":"
var eventSheetManager = scene.plugins.get('rexMarkedEventSheets').add({\ncommandExecutor: Object,\nparallel: false\n});\n
  • commandExecutor : Command executor of actions.
    • This plugin provides a built-in command executor.
  • parallel :
    • false : Test condition then execute event sheet one by one. Default behavior.
    • true : Test all condition of event sheets then execute event sheets one by one.
"},{"location":"markedeventsheet/#add-event-sheet","title":"Add event sheet","text":"

Each event sheet belong a group.

eventSheetManager.addEventSheet(content, {\ncommentLineStart: '\\/\\/',\nlineBreak: '\\\\',\nparallel: undefined,\nactive: true,\nonce: false\n})\n

or

eventSheetManager.addEventSheet(content, groupName, {\ncommentLineStart: '\\/\\/',\nlineBreak: '\\\\',\nparallel: undefined,\nactive: true,\nonce: false\n})\n

or

eventSheetManager.addEventSheet(content, {\ngroupName: '_'\ncommentLineStart: '\\/\\/',\nlineBreak: '\\\\',\nparallel: undefined,\nactive: true,\nonce: false\n})\n
  • content : See structure of event sheet
  • commentLineStart : Content line start by this symobl (default value is //) will be ignored as a comment line.
  • lineBreak : Markdown will use \\ as line break. So the last character \\ will be discarded.
  • parallel :
    • undefined : Use default parallel property.
  • active :
    • true : Eval condition of this event sheet every round. Default behavior.
    • false : Skip this event sheet.
  • once :
    • true : Set active of this event sheet to false when exection of this event sheet is complete.
    • false : Do nothing when exection of this event sheet is complete. Default behavior.
  • groupName : Each event sheet belong a group. Ignore this parameter to use default group.
    • '_' : Default group name.
"},{"location":"markedeventsheet/#remove-event-sheet","title":"Remove event sheet","text":"
  • Remove an event sheet in default group
    eventSheetManager.removeEventSheet(title);\n
  • Remove an event sheet in a specific group
    eventSheetManager.removeEventSheet(title, groupName);\n
  • Remove all event sheets in default group
    eventSheetManager.removeAllEventSheets();\n
  • Remove all event sheets in a specific group
    eventSheetManager.removeAllEventSheets(groupName);\n
"},{"location":"markedeventsheet/#start-running","title":"Start running","text":"

Starting command will be ignored if group is running.

"},{"location":"markedeventsheet/#start-running-a-group-of-event-sheets","title":"Start running a group of event sheets","text":"
  • Start running default group
    eventSheetManager.startGroup();\n
  • Start running a specific group of event sheets
    eventSheetManager.startGroup(groupName);\n
"},{"location":"markedeventsheet/#flow-chart","title":"Flow chart","text":"
graph TD\n\n    startGroup{{\"startGroup()\"}}  ------>  eventstart>Fire event\\nstart]\n    eventstart --> foreacheventsheet((For each\\nevent sheet))\n    foreacheventsheet --> |Next| activate{activate}\n\n    subgraph Event sheet\n    activate --> |True| condition{\"Test\\n[condition]\"}\n    condition --> |True| enterevent>Fire event\\neventsheet.enter]\n    condition --> |False| eventcatch>Fire event\\neventsheet.catch] \n\n    subgraph Run\n    enterevent --> actions[Run\\nactions\\n...\\n...]\n    actions --> exitevent>Fire event\\neventsheet.exit]    \n    end\n\n    subgraph Catch\n    eventcatch --> catch[\"Run\\n[catch]\"]\n    end\n\n    end\n\n    exitevent --> foreacheventsheet\n    catch --> foreacheventsheet\n\n    activate --> |False| foreacheventsheet\n\n    foreacheventsheet --> eventcomplete>Fire event\\ncomplete]\n    eventcomplete --> endnode{{End}}
"},{"location":"markedeventsheet/#start-running-a-event-sheet-in-a-group","title":"Start running a event sheet in a group","text":"
  • Start running default group
    eventSheetManager.start();\n
  • Start running an event sheet (indexed by title) without condition testing, in default group.
    eventSheetManager.start(title);\n
  • Start running an event sheet (indexed by title) without condition testing, in a specific group.
    eventSheetManager.start(title, groupName);\n
  • Start running an event sheet (indexed by title) with condition testing, in default group.
    eventSheetManager.start(title, false);\n
  • Start running an event sheet (indexed by title) with condition testing, in a specific group.
    eventSheetManager.start(title, groupName, false);\n
"},{"location":"markedeventsheet/#start-running-a-group-by-event","title":"Start running a group by event","text":"
eventSheetManager.startGroup(eventName, groupName);\n// eventSheetManager.startGroup(eventName, groupName, once);\n

or

eventSheetManager.startGroup({\neventName:\ngroupName:\nonce: false\n});\n
"},{"location":"markedeventsheet/#round-counter","title":"Round counter","text":"

Round counter is started from 0.

  • Increase round counter
    eventSheetManager.updateRoundCounter();\n// eventSheetManager.$roundCounter += 1;\n
  • Set round counter
    eventSheetManager.updateRoundCounter(value);\n// eventSheetManager.$roundCounter = value;\n
  • Get round counter
    var roundCounter = eventSheetManager.getRoundCounter();\n// var roundCounter = eventSheetManager.$roundCounter;\n
"},{"location":"markedeventsheet/#active","title":"Active","text":"
  • Activate state of event sheet (indexed by title)
    eventSheetManager.setEventSheetActiveState(title);\n// eventSheetManager.setEventSheetActiveState(title, true);\n
  • Inactivate state of event sheet (indexed by title)
    eventSheetManager.setEventSheetActiveState(title, false);\n
  • Get active state of event sheet (indexed by title)
    var active = eventSheetManager.getEventSheetActiveState(title);\n

Note

Event sheet which has once property will set active property to false when exection of this event sheet is complete.

"},{"location":"markedeventsheet/#stop-running","title":"Stop running","text":"

Stop running a group of event sheet, also fires 'eventsheet.exit' event. And game objects with 'autoClear' will be destroyed.

  • Stop running default group
    eventSheetManager.stopGroup();\n
    or
    eventSheetManager.stop();\n
  • Stop running a specific group of event sheets
    eventSheetManager.stopGroup(groupName);\n
    or
    eventSheetManager.stop(groupName);\n
"},{"location":"markedeventsheet/#local-memory","title":"Local memory","text":"

Local memory is shared for all event sheets.

  • Set value
    eventSheetManager.setData(key, value);\n
    or
    eventSheetManager.setData(data);  // data : a plain json object\n
  • Toggle value
    eventSheetManager.toggleData(key, value);\n
  • Increase value
    eventSheetManager.incData(key, inc);\n
  • Get value
    var value = eventSheetManager.getData(key);\n
  • Has key
    var hasData = eventSheetManager.hasData(key);\n
  • Local memory as a dictionary
    var data = eventSheetManager.memory;\n
"},{"location":"markedeventsheet/#custom-expression","title":"Custom expression","text":"
eventSheetManager.addExpression(name, callback);\n
  • name : A string value
  • callback : A function object retuen a number
    function(a, b, c, ...) { return x; }\n

For example :

eventSheetManager.addExpression('randomInt', function (a, b) {\nreturn Math.floor(a + Math.random() * (b - a + 1));\n});\n

Expression will store at local memory

"},{"location":"markedeventsheet/#states","title":"States","text":"
  • Dump state of event sheets of all groups
    var states = eventSheetManager.dumpState();\n
  • Load state of event sheet of all groups
    eventSheetManager.loadState(states);\n
"},{"location":"markedeventsheet/#events","title":"Events","text":"
  • Start A group of event sheets
    eventSheetManager.on('start', function(groupName, eventSheetManager){ });\n
  • A group of event sheets has been executed completed
    eventSheetManager.on('complete', function(groupName, eventSheetManager){ });\n
  • Enter an event sheet
    eventSheetManager.on('eventsheet.enter', function(title, groupName, eventSheetManager){ });\n
  • Exit an event sheet
    eventSheetManager.on('eventsheet.exit', function(title, groupName, eventSheetManager){ });\n
  • Enter a label (any heading) an event sheet
    eventSheetManager.on('label.enter', function(headingTitle, eventSheetTitle, groupName, eventSheetManager){ });\n
  • Exit a label (any heading) of an event sheet
    eventSheetManager.on('label.exit', function(headingTitle, eventSheetTitle, groupName, eventSheetManager){ });\n
  • Test condition of an event sheet failed
    eventSheetManager.on('eventsheet.catch', function(title, groupName, eventSheetManager){ });\n
"},{"location":"markedeventsheet/#structure-of-event-sheet","title":"Structure of event sheet","text":"

Sample

"},{"location":"markedeventsheet/#main-headings","title":"Main headings","text":"
# Title\n\ngroupName\nparallel\nactive=false\nonce\n\n## [Condition]\n\ncoin > 5\n\n## Script\n\n## [Catch]\n
  • H1 heading : Title of this event sheet
  • Content under Title (H1 heading) : Setting of this event sheet, optional.
    • groupName : Assign groupName in event sheet, put this event sheet in to that group.
    • parallel : Set parallel property of this event sheet to true.
    • active=false : Set active property of this event sheet to false.
    • once : Set once property of this event sheet to true.
  • H2 heading with [Condition] : Main condition.
    • Each line under [Condition] is a boolean equation, composed of AND logic.
    • Can have many [Condition] heading, each [Condition] heading will be composed of OR logic.
    • Read data from local memory
  • H2/H3/... headings between [Condition] and [Catch] : Actions when main condition is true.
    • Flow control instructions of headings
    • Actions : Custom command
  • H2 heading with [Catch] : Actions when main condition is false.
"},{"location":"markedeventsheet/#flow-control-instructions","title":"Flow control instructions","text":""},{"location":"markedeventsheet/#if-else-if-else","title":"If, Else if, Else","text":"
### [If coin > 10]\n\nactions...\n\n### [Else If (coin > 5) && (coin <10)]\n\nactions...\n\n### [Else]\n\nactions...\n
  • H2/H3/... heading with [If expression], or [Else if expression] : If/Else If condition with expression
    • Read data from local memory
    • Boolean expression AND/OR : &&.
    • Boolean expression OR : ||.
    • Actions when expression is true.
  • H2/H3/... heading with [Else] :
    • Actions when previous expressions are all false.
## [If]\n\ncoin > 10\n\n### Label\n\nactions...\n\n## [Else If]\n\ncoin > 5\ncoin < 10\n\n### Label\n\nactions...\n\n## [Else]\n\n### Label\n\nactions...\n
  • H2/H3/... heading with [If], or [Else if] : If, Else If condition
    • Each line under [If], [Else If] is a boolean equation, composed of AND logic.
    • Read data from local memory
  • H3/H4/... heading under [If], [Else if] : - Actions when previous expressions are all false.
"},{"location":"markedeventsheet/#repeat-loop","title":"Repeat loop","text":"
## [Repeat 3]\n\nactions...\n

or

## [Repeat loopCount]\n\nactions...\n

or

## [Repeat 3]\n\n### Label\n\nactions...\n
  • H2/H3/... heading with [Repeat N], or [Repeat var] : Repeat loop N times
"},{"location":"markedeventsheet/#while-loop","title":"While loop","text":"
## [While loopCount > 0]\n\nactions...\n
  • H2/H3/... heading with [While expression] : While loop with expression
    • Read data from local memory
    • Actions when expression is true.
## [While]\n\nloopCount > 0\n\n### Label\n\nactions...\n
  • H2/H3/... heading with [While] : While loop
    • Each line under [While] is a boolean equation, composed of AND logic.
    • Read data from local memory
  • H3/H4/... heading under [While] : Actions running when condition is true
"},{"location":"markedeventsheet/#break","title":"Break","text":"
[break]\n
  • Action line with [break] : Ignore remainder actions in current label (heading).
"},{"location":"markedeventsheet/#exit","title":"Exit","text":"
[exit]\n
  • Action line with [exit] : Skip remainder label (heading) and actions.
"},{"location":"markedeventsheet/#deactivate","title":"Deactivate","text":"
[deactivate]\n

or

[deactivate title]\n
  • Action line with [deactivate], or [deactivate title] : Deactivate this event sheet, or deactivate event sheet by title in the same tree group. i.e. Set active property of this event shhet to false.
"},{"location":"markedeventsheet/#activate","title":"Activate","text":"
[activate]\n

or

[activate title]\n
  • Action line with [activate], or [activate title] : Activate this event sheet, or activate event sheet by title in the same tree group. i.e. Set active property of this event shhet to true.
"},{"location":"markedeventsheet/#custom-command","title":"Custom command","text":"
commandName\n  param0=value\n  param1=value\n
  • Each command is divided by space line. i.e. add space lines above and below command.
  • First line is the command name.
    1. Invoke commandExecutor.commandName method if this commandName method is existed.
      commandName(config, eventSheetManager) {\n// var resumeCallback = eventSheetManager.pauseEventSheet();\n// ... \n// resumeCallback()\n}\n
      • config : Parameter and value in a dictionary.
      • eventSheetManager : This event mangager.
        • Pause running of current event sheet
          var resumeCallback = eventSheetManager.pauseEventSheet();  //  resumeCallback();  // Resume running of current event sheet      \n
        • Pause running of current event sheet until another eventName firing from eventEmitter
          eventSheetManager.pauseEventSheetUnitlEvent(eventEmitter, eventName);\n
    2. Otherwise, invoke commandExecutor.defaultHandler.
      defaultHandler(commandName, config, eventSheetManager) {\n// var resumeCallback = eventSheetManager.pauseEventSheet();\n// ... \n// resumeCallback()\n}\n
      • commandName : Command name.
      • config : Parameter and value in a dictionary.
      • eventSheetManager : This event mangager.
        • Pause running of current event sheet
          var resumeCallback = eventSheetManager.pauseEventSheet(); //  resumeCallback();  // Resume running of current event sheet\n
        • Pause running of current event sheet until another eventName firing from eventEmitter
          eventSheetManager.pauseEventSheetUnitlEvent(eventEmitter, eventName);\n
  • Remainder lines are parameter composed of parameter name and value, with =
    • Space characters at line start will be discarded.
    • Value will be parsed to number, boolean, or string.
      • String value contains {{, and }} will be interpolation by mustache template syntax, return a string value.
      • String value wrapped by #( ) will be treated as expression, return a number value.
  • Any line start with // will be ignored as comment line.

For multiple lines parameter :

```commandName,param0=value,param1=value\nline0\nline1\nline2\n```\n
  • Lines in code block will be assigned to text parameter.

So it will be equal to

commandName\n  text=...\n  param0=value\n  param1=value\n
  • '\\n'
"},{"location":"markedeventsheet/#command-executor","title":"Command executor","text":"

A command executor for phaser3 engine.

"},{"location":"markedeventsheet/#create-command-executor-instance","title":"Create command executor instance","text":"
var commandExecutor = scene.plugins.get('rexMarkedEventSheets').addCommandExecutor(scene, {\n// layers: ['layer0', 'layer1', ...]\n// layers: [{name, cameraName}, ...]\n\n// layerDepth: undefined,\n// rootLayer: undefined,\n\nlog: {\ndelimiters: '[]'\nenable: true\n}\n});\n\n// Add to event sheet manager\n// var eventSheetManager = scene.plugins.get('rexMarkedEventSheets').add({\n//     commandExecutor: commandExecutor\n// });\n

or

// import MarkedEventSheets from 'phaser3-rex-plugins/plugins/markedeventsheets.js';\n// import CommandExecutor from 'phaser3-rex-plugins/plugins/commandexecutor.js';\n\nvar commandExecutor = new CommandExecutor(scene, config);\n\n// var eventSheetManager = new MarkedEventSheets({\n//     commandExecutor: commandExecutor\n// });\n
  • layers : Add some initial layers
    • A string array : Add layers by string name
    • A array of plain object { name, cameraName }
      1. Add layer by string name
      2. Bind this layer to dedicate camera (indexed by cameraName), ignore other cameras Add a new camera if this target camera is not existing
  • layerDepth : Set depth to each layer game object.
    • undefined : Keep default depth value (0)
  • rootLayer : Add all layer game objects created by layer-manager into this root layer.
  • log : Configuration of BBCodeLog
    • log.delimiters : String of left-delimiter and right-delimiter.
      • A single string with 2 characters. Default value is '[]'.
      • A array with 2 strings
    • log.enable :
      • true : Can print message on console. Default behavior.
      • false : Don't print any message on console.
"},{"location":"markedeventsheet/#local-memory-of-event-sheet-manager","title":"Local memory of event sheet manager","text":"
  • Set value by key
    setData\n  key=value\n
  • Increase value of key
    incData\n  key=value\n
    or
    setData\n  key=#(key+value)\n
  • Toggle value of key
    toggleData\n  key\n

See Local memory

"},{"location":"markedeventsheet/#bbcode-log","title":"BBCode Log","text":""},{"location":"markedeventsheet/#print-message-on-console","title":"Print message on console","text":"
log\n  text=...\n

or

log\n  text=...\n  // logType='log'\n  // showTitle=true\n  // title\n  // titleColor='green'\n
  • text : Message with bbcode format.
    • [color=gold]...[/color]
    • [bgcolor=green]...[/bgcolor]
    • [b]...[/b]
    • [i]...[/i]
    • [u]...[/u]
  • logType :
    • 'log' : console.log. Default value.
    • 'warn': console.warn
  • showTitle
    • true : Show title before text message. Default behavior.
    • false : Don't show title.
  • title
    • undefined : Using title of current event sheet. Default behavior.
    • A string, custom string before text message.
  • titleColor : Background color of title block, default value is 'green'
"},{"location":"markedeventsheet/#disable-console-message","title":"Disable console message","text":"
log.disable\n
  • Disable console message of current event sheet.

or

log.disable\n  title=...\n
  • title : Disable console message of event sheet by title.
"},{"location":"markedeventsheet/#enable-console-message","title":"Enable console message","text":"
log.enable\n
  • Enable console message of current event sheet.

or

log.enable\n  title=...\n
  • title : Enable console message of event sheet by title.
"},{"location":"markedeventsheet/#dump-memory","title":"Dump memory","text":"
log.memory\n
  • Dump all key in memory

or

log.memory\n  text=...\n  keys=a,b,c\n
  • keys : Dump part of memory by keys.
  • text : Message with bbcode format.
"},{"location":"markedeventsheet/#game-object","title":"Game object","text":""},{"location":"markedeventsheet/#register-custom-game-object","title":"Register custom game object","text":"
commandExecutor.addGameObjectManager({\nname: GOTYPE,\n\nviewportCoordinate: false,\n// viewportCoordinate: { viewport: new Phaser.Geom.Rectangle() },\n\nfade: 500,\n// fade: {mode: 'tint', time: 500},\n\ndefaultLayer: layerName,\n\nautoClear: true,\n\ncommands: {\ncommandName(gameObject, config, commandExecutor, eventSheetManager, eventSheet) {\n// commandExecutor.waitEvent(eventEmitter, eventName);\n}\n}\n})\n
  • name : A string name of game object's type. Will register command GOTYPE to this command executor.
  • createGameObject : A callback for creating game object
    function(scene, config) {\nreturn gameObject;\n}\n
    • config : Parameters passed from event sheet.
      • id, layer, autoClear, eventSheetManager, eventsheet : These parameters are reserved.
      • eventSheetManager : This event sheet manager.
  • viewportCoordinate : Apply viewportCoordinate behavior to game object.
    • true : Attach vpx, vpy, vp to sprite game object.
      • vpx, vpy : Number between 0~1. Proportion of viewport.
      • vp : Viewport in rectangle
    • false : Do nothing, default behavior.
  • fade :
    • 0 : No fade-in or fade-out when adding or removing a sprite.
    • A number : Duration of fading. Default value is 500.
    • A plain object contains mode, time
      • fade.mode : Fade mode
        • 'tint', or 0 : Fade-in or fade-out via tint property.
        • 'alpha', or 1 : Fade-in or fade-out via alpha property.
        • 'revealUp', or 2 : Reveal up for fade-in.
        • 'revealDown', or 3 : Reveal down for fade-in.
        • 'revealLeft', or 4 : Reveal left for fade-in.
        • 'revealRight', or 5 : Reveal right for fade-in.
      • fade.time : Duration of fading. Default value is 500.
  • defaultLayer : A layer name defined in layers parameter of addCommandExecutor method
  • autoClear :
    • true : Clear game objects when exiting current event sheet. Default behavior.
    • false : Ignore this behavior.
  • commands : Custom commands, each command is a callback indexed by command name
    commandName: function(gameObject, config, commandExecutor, eventSheetManager) {\n// commandExecutor.waitEvent(eventEmitter, eventName);\n}\n
    • commandName : Command name. These command names are reserved : to, yoyo, destroy
    • gameObject : Game object instance.
    • config : Parameters passed from event sheet.
    • commandExecutor : This command executor instance. See also
    • eventSheetManager : This event sheet manager instance.
      • Store variable into blackboard of eventSheetManager : eventSheetManager.setData(key, value)
"},{"location":"markedeventsheet/#create-custom-game-object","title":"Create custom game object","text":"
GOTYPE\n  id=NAME\n  layer=\n  autoClear=\n  param0=value\n  param1=value\n
  • Create custom game object GOTYPE with config {param0, param1}, indexed by id
  • layer : Put this game object at layer.
    • undefined : Put this game object at default layer
  • autoClear : Clear game objects when exiting current event sheet.
    • undefined : Use default value of autoClear

Reserved id : time, click, key, bgm, bgm2, se, se2, camera.

Will store reference of this game object into memory at key @NAME, can see it by log.memory, or get property of game object via #(@NAME.x + 3).

"},{"location":"markedeventsheet/#set-properties-of-custom-game-object","title":"Set properties of custom game object","text":"
  • Set properties of a game object indexing by NAME
    NAME.set\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n
    • vpx, vpy : viewportCoordinate properties injected if viewportCoordinate is true.
    • Add empty line above and below this command block.
  • Set properties of all game objects belong GOTYPE
    GOTYPE.set\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n
  • Set properties of all game objects belong GOTYPE excluding NAME
    !NAME.set\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n
"},{"location":"markedeventsheet/#ease-properties-of-custom-game-object","title":"Ease properties of custom game object","text":"
  • Ease properties of a game object indexing by NAME
    NAME.to\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    NAME.from\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    NAME.yoyo\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    • These properties are reserved : id, duration, delay, ease, repeat, yoyo, wait
    • wait :
      • false : Run next command immediately. Default behavior.
      • true : Run next command after playing sound complete.
    • Add empty line above and below this command block.
  • Ease properties of all game objects belong GOTYPE
    GOTYPE.to\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    GOTYPE.from\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    GOTYPE.yoyo\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
  • Ease properties of all game objects belong GOTYPE excluding NAME
    !NAME.to\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    !NAME.from\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    !NAME.yoyo\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
"},{"location":"markedeventsheet/#invoke-custom-command","title":"Invoke custom command","text":"
  • Invoke custom command of a game object indexing by NAME
    NAME.commandName\n  param0=value\n  param1=value\n
    • Invoke custom command commandName method with these parameters
      • gameObject : Indexed by NAME
      • config : {param0, param1}
    • Add empty line above and below this command block.
    • value :
      • For string value, characters \\n (2 characters) will be replaced by \\n new line character (1 character)
  • Invoke custom command of all game objects belong GOTYPE
    GOTYPE.commandName\n  param0=value\n  param1=value\n
  • Invoke custom command of all game objects belong GOTYPE excluding NAME
    !NAME.commandName\n  param0=value\n  param1=value\n

Do nothing if gameObject or commandName is not found.

"},{"location":"markedeventsheet/#destroy-custom-game-object","title":"Destroy custom game object","text":"
  • Destroy game object indexing by NAME
    NAME.destroy\n
  • Destroy all game objects belong GOTYPE
    GOTYPE.destroy\n
  • Destroy all game objects belong GOTYPE excluding NAME
    !NAME.destroy\n
"},{"location":"markedeventsheet/#methods-used-in-command","title":"Methods used in command","text":"
  • Hold command execution until eventEmitter emits eventName event.
    commandExecutor.waitEvent(eventEmitter, eventName);\n
  • Apply value to property of
    commandExecutor.setGOProperty({\ngoType, id, property, ... });\n
    • goType : GameObject type assigned by commandExecutor.addGameObjectManager({name...}).
    • id : NAME of game object, which will store in gameObject.name.
      • gameObject.name : Apply value to property of this game object.
      • '!' + gameObject.name : Apply value to property of all game objects exclude this game object.
      • undefined : All game objects.
    • propertyName: value : Assign value to property. Can assign one or many properties.
  • Ease value of game object(s)' property
    if (wait) {\ncommandExecutor.setWaitEventFlag();\n}\ncommandExecutor.easeGOProperty({\ngoType, id, duration, ease, repeat, yoyo, wait, property, ... });\n
    • goType : GameObject type assigned by commandExecutor.addGameObjectManager({name...}).
    • id : NAME of game object, which will store in gameObject.name.
      • gameObject.name : Apply value to property of this game object.
      • '!' + gameObject.name : Apply value to property of all game objects exclude this game object.
      • undefined : All game objects.
    • duration : Duration of easing task.
    • ease : Ease function
    • repeat : Repeat times.
    • yoyo : Yoyo flag.
    • wait : Wait until easing task complete.
      • Invoke commandExecutor.setWaitEventFlag().
    • propertyName: value : Ease value of property. Can assign one or many properties.
"},{"location":"markedeventsheet/#wait","title":"Wait","text":""},{"location":"markedeventsheet/#wait-click","title":"Wait click","text":"
click\n
  • Run next command after clicking.
"},{"location":"markedeventsheet/#wait-any","title":"Wait any","text":"

Run next command after...

wait\n  click\n  key=keyName\n  time=\n  GONAME.destroy\n  GONAME.PROPNAME\n  GONAME.DATAKEY\n  GONAME.EVTNAME\n  event=EVENTNAME\n
  • click : Run next command after clicking.
  • key : Run next command after key down
  • time : Run next command after time-out.
  • GONAME.destroy : Run next command after game object has destroyed.
  • GONAME.PROPNAME (ex. GONAME.x) : Run next command after game object's property tween complete
  • GONAME.DATAKEY, GONAME.!DATAKEY (ex. GONAME.!hp) : Run next command after game object's data is true (or > 0) or false (or <= 0). Will check PROPNAME first.
  • GONAME.EVTNAME : Run next command after game object's EVTNAME firing. Will check PROPNAME and DATAKEY first.
  • event : Run next command after eventSheetManager firing EVENTNAME event.

Emit these events from eventSheetManager

  • Wait click or key down
    eventSheetManager.on('pause.input', function(){ });\n
    • Resume (run next command)
      eventSheetManager.on('resume.input', function(){ });\n
  • Wait click only
    eventSheetManager.on('pause.click', function(){ });\n
  • Wait key down only
    eventSheetManager.on('pause.key', function(keyName){ });\n
"},{"location":"markedeventsheet/#sound","title":"Sound","text":"

This command executor provides

  • 2 background music tracks : bgm, bgm2
  • 2 sound effects : se, se2.
"},{"location":"markedeventsheet/#sound-properties","title":"Sound properties","text":"
bgm.set\n  volume\n  mute\n  unmute\n
  • Command name : bgm, bgm2, se, se2
"},{"location":"markedeventsheet/#play-sound","title":"Play sound","text":"
bgm.play\n  key=\n  // volume\n  // detune\n  // rate\n  fadeIn=0\n  // loop\n  wait=false\n
  • Command name : bgm.play, bgm2.play, se.play, se2.play
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after playing sound complete.
"},{"location":"markedeventsheet/#cross-fade-in-sound","title":"Cross fade in sound","text":"
bgm.cross\n  key=\n  duration=500\n  wait=false\n
  • Command name : bgm.cross, bgm2.cross
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after playing sound complete.
"},{"location":"markedeventsheet/#stop-sound","title":"Stop sound","text":"
bgm.stop\n
  • Command name : bgm.stop, bgm2.stop, se.stop, se2.stop
"},{"location":"markedeventsheet/#fade-out-sound","title":"Fade out sound","text":"
bgm.fadeOut\n  duration=500\n  stop=true\n  wait=false\n
  • Command name : bgm.fadeOut, bgm2.fadeOut, se.fadeOut, se2.fadeOut
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after playing sound complete.
"},{"location":"markedeventsheet/#fade-in-sound","title":"Fade in sound","text":"
bgm.fadeIn\n  duration=500\n
  • Command name : bgm.fadeIn, bgm2.fadeIn
"},{"location":"markedeventsheet/#pause-sound","title":"Pause sound","text":"
bgm.pause\n
  • Command name : bgm.pause, bgm2.pause
"},{"location":"markedeventsheet/#resume-sound","title":"Resume sound","text":"
bgm.resume\n
  • Command name : bgm.resume, bgm2.resume
"},{"location":"markedeventsheet/#mute-sound","title":"Mute sound","text":"
bgm.mute\n
  • Command name : bgm.mute, bgm2.mute, se.mute, se2.mute
"},{"location":"markedeventsheet/#unmute-sound","title":"Unmute sound","text":"
bgm.unmute\n
  • Command name : bgm.unmute, bgm2.unmute, se.unmute, se2.unmute
"},{"location":"markedeventsheet/#camera","title":"Camera","text":""},{"location":"markedeventsheet/#camera-properties","title":"Camera properties","text":"
camera.set\n  x=\n  y=\n  rotate=\n  zoom=\n  name\n
  • x, y : Scroll
  • rotate : Rotate in degree
  • zoom : Zoom
  • name : Target camera indexed by name. Default is main camera.

Run next command immediately.

"},{"location":"markedeventsheet/#fade-in","title":"Fade in","text":"
camera.fadeIn\n  duration=1000\n  red\n  green\n  blue\n  name\n  wait=false\n
  • duration, red, green, blue : See fade effect
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#fade-out","title":"Fade out","text":"
camera.fadeOut\n  duration=1000\n  red\n  green\n  blue\n  name\n  wait=false\n
  • duration, red, green, blue : See fade effect
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#flash","title":"Flash","text":"
camera.flash\n  duration=1000\n  red\n  green\n  blue\n  name\n  wait=false\n
  • duration, red, green, blue : See flash effect
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#shake","title":"Shake","text":"
camera.shake\n  duration=1000\n  intensity\n  name\n  wait=false\n
  • duration, intensity : See shake effect
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#zoom","title":"Zoom","text":"
camera.zoomTo\n  duration=1000\n  zoom\n  name\n  wait=false\n
  • duration, zoom : See zoom effect
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#rotate-to","title":"Rotate to","text":"
camera.rotateTo\n  duration=1000\n  rotate\n  ease\n  name\n  wait=false\n
  • duration, rotate, ease : See rotateTo effect
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#scroll-to","title":"Scroll to","text":"
camera.scrollTo\n  duration=1000\n  x\n  y\n  ease\n  name\n  wait=false\n
  • duration, x, y, ease : Scroll to position.
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#add-custom-command","title":"Add custom command","text":"
commandExecutor.addCommand(commandName, function(config, eventSheetManager){\n// var resumeCallback = eventSheetManager.pauseEventSheet();\n// ... \n// resumeCallback()\n}, scope);\n
  • config : Parameters passed from event sheet.
  • eventSheetManager : This event mangager.
    • Pause running of current event sheet
      var resumeCallback = eventSheetManager.pauseEventSheet();\n//  resumeCallback();  // Resume running of current event sheet\n
    • Pause running of current event sheet until another eventName firing from eventEmitter
      eventSheetManager.pauseEventSheetUnitlEvent(eventEmitter, eventName);\n
"},{"location":"mask/","title":"Mask","text":""},{"location":"mask/#introduction","title":"Introduction","text":"

Apply mask on game object. Built-in render of phaser.

  • Author: Richard Davey
"},{"location":"mask/#usage","title":"Usage","text":""},{"location":"mask/#add-mask","title":"Add mask","text":""},{"location":"mask/#create-mask-object","title":"Create mask object","text":""},{"location":"mask/#bitmap-mask","title":"Bitmap mask","text":"
  1. Create image (image, sprite, bitmap text, particles, text),or shader
    var shape = scene.add.image(x, y, key).setVisible(false);\n
  2. Create mask
    var mask = shape.createBitmapMask();\n
    or
    var mask = scene.add.bitmapMask(shape);\n

or

var mask =  scene.add.bitmapMask(undefined, x, y, key, frame);\n
"},{"location":"mask/#geometry-mask","title":"Geometry mask","text":"

The mask is essentially a clipping path which can only make a masked pixel fully visible or fully invisible without changing its alpha (opacity).

  1. Create graphics
    var shape = scene.make.graphics();\n
  2. Create mask
    var mask = shape.createGeometryMask();\n
"},{"location":"mask/#apply-mask-object","title":"Apply mask object","text":"
gameObject.setMask(mask); // image.mask = mask;\n

A mask object could be added to many game objects.

Error

Don't put game object and its mask into a container together. See this testing, enable line 22-24.

Note

Bitmap Mask is WebGL only.

Note

Can combine Geometry Masks and Blend Modes on the same Game Object, but Bitmap Masks can't.

"},{"location":"mask/#clear-mask","title":"Clear mask","text":"
  • Clear mask
    image.clearMask();\n
  • Clear mask and destroy mask object
    image.clearMask(true);\n
"},{"location":"mask/#invert-alpha","title":"Invert alpha","text":"

Only GeometryMask has inverse alpha feature.

  • Inverse alpha
    mask.setInvertAlpha();\n// mask.invertAlpha = true;\n
  • Disable
    mask.setInvertAlpha(false);\n// mask.invertAlpha = false;\n
"},{"location":"mask/#get-shape-game-object","title":"Get shape game object","text":"
  • Bitmap mask
    var shape = mask.bitmapMask;\n
  • Geometry mask
    var shape = mask.geometryMask;\n
"},{"location":"matterjs-attractor/","title":"Attractor","text":""},{"location":"matterjs-attractor/#introduction","title":"Introduction","text":"

Apply continual forces on bodies.

  • Reference
"},{"location":"matterjs-attractor/#usage","title":"Usage","text":""},{"location":"matterjs-attractor/#system-configuration","title":"System configuration","text":"
  • Game config
    var config = {\n// ...\nphysics: {\nmatter: {\n// ...\nplugins: {\nattractors: true,\n// ...\n}\n// ...\n}\n}\n// ...\n}\nvar game = new Phaser.Game(config);\n
  • Runtime
    scene.matter.system.enableAttractorPlugin();\n
"},{"location":"matterjs-attractor/#matter-object-configuration","title":"Matter object configuration","text":"
var options = {\n// ...\nplugin: {\nattractors: [\ncallback,\n// ...\n]\n},\n// ...\n}\n
  • callback :
    • Retuen a force ({x,y}), which will be applied to bodyB
      function(bodyA, bodyB) {\nreturn {x, y}; // Force\n}\n
      • bodyA : Attractor matter object.
      • bodyB : Other matter object.
    • Apply forece to bodies directly.
      function(bodyA, bodyB) {\nbodyA.gameObject.applyForce({x, y});\nbodyB.gameObject.applyForce({x, y});\n}\n
      • bodyA : Attractor matter object.
        • bodyA.gameObject : Game object.
      • bodyB : Other matter object.
        • bodyB.gameObject : Game object.
"},{"location":"matterjs-gameobject/","title":"Game object","text":""},{"location":"matterjs-gameobject/#introduction","title":"Introduction","text":"

Matterjs physics Image/Sprite/Group object.

  • Author: Richard Davey
"},{"location":"matterjs-gameobject/#usage","title":"Usage","text":""},{"location":"matterjs-gameobject/#add-physics-object","title":"Add physics object","text":"

Enable physics world

"},{"location":"matterjs-gameobject/#image-object","title":"Image object","text":"
var image = scene.matter.add.image(x, y, key, frame);\n// var image = scene.matter.add.image(x, y, key, frame, config);\n
  • config : Config object
"},{"location":"matterjs-gameobject/#sprite-object","title":"Sprite object","text":"
var image = scene.matter.add.sprite(x, y, key, frame);\n// var image = scene.matter.add.sprite(x, y, key, frame, config);\n
  • config : Config object
"},{"location":"matterjs-gameobject/#any-game-object","title":"Any game object","text":"
var gameObject = scene.matter.add.gameObject(gameObject);\n// var gameObject = scene.matter.add.gameObject(gameObject, config);\n
  • config : Config object
"},{"location":"matterjs-gameobject/#image-composite","title":"Image composite","text":"

Create a new composite containing Matter Image objects created in a grid arrangement.

var composite = scene.matter.add.imageStack(key, frame, x, y, columns, rows);\n// var composite = scene.matter.add.imageStack(key, frame, x, y, columns, rows, columnGap, rowGap, options);\n
  • key, frame : Texture key and frame name.
  • x, y : Top-left position of these game objects.
  • columns, rows : The number of columns/rows in the grid.
  • columnGap, rowGap : The distance between each column/row.
  • config : Config object
  • composite : Composite matter object.
    • composite.bodies : An array of bodies.
"},{"location":"matterjs-gameobject/#config","title":"Config","text":"
{\nlabel: 'Body',\nshape: 'rectangle',\nchamfer: null,\n\nisStatic: false,\nisSensor: false,\nisSleeping: false,\nignoreGravity: false,\nignorePointer: false,\n\nsleepThreshold: 60,\ndensity: 0.001,\nrestitution: 0,\nfriction: 0.1,\nfrictionStatic: 0.5,\nfrictionAir: 0.01,\n\nforce: { x: 0, y: 0 },\nangle: 0,\ntorque: 0,\n\ncollisionFilter: {\ngroup: 0,\ncategory: 0x0001,\nmask: 0xFFFFFFFF,\n},\n\n// parts: [],\n\n// plugin: {\n//     attractors: [\n//         (function(bodyA, bodyB) { return {x, y}}),\n//     ]\n// },\n\nslop: 0.05,\n\ntimeScale: 1,\n}\n
  • label : An arbitrary String name to help the user identify and manage bodies.
  • shape :
    • A string : 'rectangle', 'circle', 'trapezoid', 'polygon', 'fromVertices', 'fromPhysicsEditor'
    • An object :
      • Rectangle shape
        {\ntype: 'rectangle',\n// width: gameObject.width\n// height: gameObject.height\n}\n
      • Circle shape
        {\ntype: 'circle',\n// radius: (Math.max(gameObject.width, gameObject.height) / 2),\n// maxSides: 25\n}\n
      • Trapezoid shape
        {\ntype: 'trapezoid',\n// slope: 0.5,\n}\n
      • Polygon shape
        {\ntype: 'polygon',\n// radius: (Math.max(gameObject.width, gameObject.height) / 2),\n// sides: 5,\n}\n
      • Vertices
        {\ntype: 'fromVertices',\nverts: points,\n// flagInternal: false,\n// removeCollinear: 0.01,\n// minimumArea: 10,\n}\n
        • points :
          • A string : 'x0 y0 x1 y1 ...'
          • An array of points : [{x:x0, y:y0}, {x:x1, y:y1}, ...]
  • chamfer :
    • null
    • A number
    • {radius: value}
    • {radius: [topLeft, topRight, bottomRight, bottomLeft]}
  • isStatic : A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed.
  • isSensor : A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically.
  • isSleeping : A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken.
  • sleepThreshold : The number of updates in which this body must have near-zero velocity before it is set as sleeping.
  • density : Density of the body, that is its mass per unit area.
  • restitution : The restitution/bounce/elasticity of the body. The value is always positive and is in the range (0, 1).
    • 0 : Collisions may be perfectly inelastic and no bouncing may occur.
    • 0.8 : The body may bounce back with approximately 80% of its kinetic energy.
  • friction : Friction of the body. The value is always positive and is in the range (0, 1).
    • 0 : The body may slide indefinitely.
    • 1 : The body may come to a stop almost instantly after a force is applied.
  • frictionStatic : The static friction of the body (in the Coulomb friction model).
    • 0 : The body will never 'stick' when it is nearly stationary and only dynamic friction is used.
    • 10 : The higher the value, the more force it will take to initially get the body moving when nearly stationary.
  • frictionAir : The air friction of the body (air resistance).
    • 0 : The body will never slow as it moves through space.
    • The higher the value, the faster a body slows when moving through space.
  • force : The force to apply in the current step.
  • angle : Angle of the body, in radians.
  • torque : the torque (turning force) to apply in the current step.
  • collisionFilter : An Object that specifies the collision filtering properties of this body.
    • collisionFilter.group
    • collisionFilter.category : A bit field that specifies the collision category this body belongs to.
    • collisionFilter.mask : A bit mask that specifies the collision categories this body may collide with.
  • slop : A tolerance on how far a body is allowed to 'sink' or rotate into other bodies.
    • The default should generally suffice, although very large bodies may require larger values for stable stacking.
"},{"location":"matterjs-gameobject/#collision","title":"Collision","text":"

Collisions between two bodies will obey the following rules:

  • (grpupA > 0) && (groupB > 0) :
    • Collision = (groupA == groupB)
  • (grpupA == 0) || (groupB == 0) :
    • Collision = ((categoryA & maskB) !== 0) && ((categoryB & maskA) !== 0)
"},{"location":"matterjs-gameobject/#movement","title":"Movement","text":""},{"location":"matterjs-gameobject/#velocity","title":"Velocity","text":"
gameObject.setVelocity(x, y);\n
gameObject.setVelocityX(x);\n
gameObject.setVelocityY(x);\n
"},{"location":"matterjs-gameobject/#acceleration","title":"Acceleration","text":""},{"location":"matterjs-gameobject/#force","title":"Force","text":"
  • Applies a force to a body.
    gameObject.applyForce(force);\n
    • force : {x, y}
  • Applies a force to a body from a given position.
    gameObject.applyForceFrom(position, force); // position, force: {x, y}\n
    • position : {x, y}
    • force : {x, y}
  • Apply thrust to the forward position of the body.
    gameObject.thrust(speed);\n
    • speed : A number.
  • Apply thrust to the left position of the body.
    gameObject.thrustLeft(speed);\n
    • speed : A number.
  • Apply thrust to the right position of the body.
    gameObject.thrustRight(speed);\n
    • speed : A number.
  • Apply thrust to the back position of the body.
    gameObject.thrustBack(speed);\n
    • speed : A number.
  • Apply thrust to the back position of the body.
    gameObject.thrustBack(speed);\n
    • speed : A number.
"},{"location":"matterjs-gameobject/#gravity","title":"Gravity","text":"
  • Ignore world gravity
    gameObject.setIgnoreGravity(ignore);\n
    • ignore : Set to true to ignore the effect of world gravity
"},{"location":"matterjs-gameobject/#friction","title":"Friction","text":"
gameObject.setFriction(value, air, fstatic);\n
gameObject.setFrictionAir(v);\n
gameObject.setFrictionStatic(v);\n
"},{"location":"matterjs-gameobject/#rotation","title":"Rotation","text":""},{"location":"matterjs-gameobject/#fixed-rotation","title":"Fixed rotation","text":"
gameObject.setFixedRotation();\n
"},{"location":"matterjs-gameobject/#angular-velocity","title":"Angular velocity","text":"
gameObject.setAngularVelocity(v);\n
"},{"location":"matterjs-gameobject/#collision_1","title":"Collision","text":""},{"location":"matterjs-gameobject/#enable","title":"Enable","text":"
  • Get
    var isSensor = gameObject.isSensor();\n
  • Set
    gameObject.setSensor(value);\n
    • value : Set true to enable sensor.
"},{"location":"matterjs-gameobject/#collision-group","title":"Collision group","text":"
  • Collision grpup
    gameObject.setCollisionGroup(value);\n
  • Collision category
    1. Get new collision category
      var category = scene.matter.world.nextCategory();\n
      • category : An one-shot number (1, 2, 4, 8, ...., 2147483648 (1<<31))
    2. Set collision category of game object
      gameObject.setCollisionCategory(category);\n
    3. Set category mask
      gameObject.setCollidesWith([categoryA, categoryB, ...]);\n// gameObject.setCollidesWith(categoryA);\n
"},{"location":"matterjs-gameobject/#collision-event","title":"Collision event","text":"
scene.matter.world.on('collisionstart', function (event, bodyA, bodyB) {\n// var pairs = event.pairs;\n});\n
  • event :
    • event.pairs : An array of collision pairs
      • event.pairs[i].bodyA, event.pairs[i].bodyB : Matter body object.
        • body.gameObject : Game object of matter body.
  • bodyA, bodyB : Equal to event.pairs[0].bodyA, event.pairs[0].bodyB.
"},{"location":"matterjs-gameobject/#collision-bound","title":"Collision bound","text":"
  • Rectangle
    gameObject.setRectangle(width, height, options);\n
  • Circle
    gameObject.setCircle(radius, options);\n
  • Polygon
    gameObject.setPolygon(radius, sides, options);\n
  • Trapezoid
    gameObject.setTrapezoid(width, height, slope, options);\n
  • Any
    gameObject.setBody(config, options);\n
    • config :
      • Rectangle shape
        {\ntype: 'rectangle',\n// width: gameObject.width\n// height: gameObject.height\n}\n
      • Circle shape
        {\ntype: 'circle',\n// radius: (Math.max(gameObject.width, gameObject.height) / 2),\n// maxSides: 25\n}\n
      • Trapezoid shape
        {\ntype: 'trapezoid',\n// slope: 0.5,\n}\n
      • Polygon shape
        {\ntype: 'polygon',\n// radius: (Math.max(gameObject.width, gameObject.height) / 2),\n// sides: 5,\n}\n
"},{"location":"matterjs-gameobject/#bounce","title":"Bounce","text":"
gameObject.setBounce(v);\n
  • restitution
"},{"location":"matterjs-gameobject/#mass","title":"Mass","text":"
gameObject.setMass(v);\n
gameObject.setDensity(v);\n
"},{"location":"matterjs-gameobject/#sleep","title":"Sleep","text":""},{"location":"matterjs-gameobject/#enable_1","title":"Enable","text":"
var config = {\n// ...\nphysics: {\nmatter: {\n// ...\nenableSleeping: true\n// ...\n}\n}\n\n}\n
"},{"location":"matterjs-gameobject/#sleep-threshold","title":"Sleep threshold","text":"
gameObject.setSleepThreshold(value);\n
"},{"location":"matterjs-gameobject/#sleep-events","title":"Sleep events","text":"
  • Sleeping start
    scene.matter.world.on('sleepstart', function (event, body) {\n});\n
  • Sleeping end
    scene.matter.world.on('sleepend', function (event, body) {\n});\n
"},{"location":"matterjs-world/","title":"World","text":""},{"location":"matterjs-world/#introduction","title":"Introduction","text":"

Matter physics engine in phaser.

  • Author: Richard Davey
"},{"location":"matterjs-world/#usage","title":"Usage","text":""},{"location":"matterjs-world/#configuration","title":"Configuration","text":"
var config = {\n// ...\nphysics: {\ndefault: 'matter',\nmatter: {\n//    enabled: true,\n//    positionIterations: 6,\n//    velocityIterations: 4,\n//    constraintIterations: 2,\n//    enableSleeping: false,\n//    plugins: {\n//        attractors: false,\n//        wrap: false,\n//    },\n//    gravity: {\n//        x: 0,\n//        y: 0,\n//    }\n//    setBounds: {\n//        x: 0,\n//        y: 0,\n//        width: scene.sys.scale.width,\n//        height: scene.sys.scale.height,\n//        thickness: 64,\n//        left: true,\n//        right: true,\n//        top: true,\n//        bottom: true,\n//    },\n//    timing: {\n//        timestamp: 0,\n//        timeScale: 1,\n//    },\n//    correction: 1,\n//    getDelta: (function() { return 1000 / 60; }),\n//    autoUpdate: true,\n//    debug: false,\n//    debug: {\n//        showAxes: false,\n//        showAngleIndicator: false,\n//        angleColor: 0xe81153,\n//        showBroadphase: false,\n//        broadphaseColor: 0xffb400,\n//        showBounds: false,\n//        boundsColor: 0xffffff,\n//        showVelocity: false,\n//        velocityColor: 0x00aeef,\n//        showCollisions: false,\n//        collisionColor: 0xf5950c,\n//        showSeparations: false,\n//        separationColor: 0xffa500,\n//        showBody: true,\n//        showStaticBody: true,\n//        showInternalEdges: false,\n//        renderFill: false,\n//        renderLine: true,\n//        fillColor: 0x106909,\n//        fillOpacity: 1,\n//        lineColor: 0x28de19,\n//        lineOpacity: 1,\n//        lineThickness: 1,\n//        staticFillColor: 0x0d177b,\n//        staticLineColor: 0x1327e4,\n//        showSleeping: false,\n//        staticBodySleepOpacity: 0.7,\n//        sleepFillColor: 0x464646,\n//        sleepLineColor: 0x999a99,\n//        showSensors: true,\n//        sensorFillColor: 0x0d177b,\n//        sensorLineColor: 0x1327e4,\n//        showPositions: true,\n//        positionSize: 4,\n//        positionColor: 0xe042da,\n//        showJoint: true,\n//        jointColor: 0xe0e042,\n//        jointLineOpacity: 1,\n//        jointLineThickness: 2,\n//        pinSize: 4,\n//        pinColor: 0x42e0e0,\n//        springColor: 0xe042e0,\n//        anchorColor: 0xefefef,\n//        anchorSize: 4,\n//        showConvexHulls: false,\n//        hullColor: 0xd703d0\n//    }\n}\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"matterjs-world/#control","title":"Control","text":""},{"location":"matterjs-world/#pause","title":"Pause","text":"
scene.matter.world.pause();\n
"},{"location":"matterjs-world/#resume","title":"Resume","text":"
scene.matter.world.resume();\n
"},{"location":"matterjs-world/#drag-object","title":"Drag object","text":"
scene.matter.add.mouseSpring();\n// scene.matter.add.mouseSpring(options);\n
  • options
    {\nlength: 0.01,\nstiffness: 0.1,\ndamping: 0,\nangularStiffness: 1,\ncollisionFilter: {\ncategory: 0x0001,\nmask: 0xFFFFFFFF,\ngroup: 0\n}\n}\n
    • collisionFilter : Drag filter, see collision.
"},{"location":"matterjs-world/#world-bounds","title":"World bounds","text":""},{"location":"matterjs-world/#enable","title":"Enable","text":"
  • World :
    • Set bounds
      scene.matter.world.setBounds(x, y, width, height);\n// scene.matter.world.setBounds(x, y, width, height, thickness, left, right, top, bottom);\n
      • thickness : The thickness of each wall, in pixels.
      • left, right, top, bottom : If true will create the left/right/top/bottom bounds wall.
"},{"location":"matterjs-world/#gravity","title":"Gravity","text":"
  • Set
    scene.matter.world.setGravity(x, y);\n// scene.matter.world.setGravity(x, y, scale);\n
  • Disable
    scene.matter.world.disableGravity();\n
"},{"location":"matterjs-world/#constraint","title":"Constraint","text":""},{"location":"matterjs-world/#constraint-of-2-game-objects","title":"Constraint of 2 game objects","text":"
var constraint = scene.matter.add.constraint(gameObjectA, gameObjectB);\n// var constraint = scene.matter.add.constraint(gameObjectA, gameObjectB, length, stiffness, options);\n
  • gameObjectA, gameObjectB : Matter game object, or matter body object.
  • length : The target resting length of the constraint.
    • undefined : Current distance between gameObjectA and gameObjectB. (Default value)
  • stiffness : The stiffness of the constraint.
    • 1 : Very stiff. (Default value)
    • 0.2 : Acts as a soft spring.
  • options :
    {\npointA: {\nx: 0,\ny: 0,\n},\npointB: {\nx: 0,\ny: 0,\n},\ndamping: 0,\nangularStiffness: 0,\n// render: {\n//     visible: true\n// }\n}\n
    • pointA, pointB : Offset position of gameObjectA, gameObjectB.

Alias:

var constraint = scene.matter.add.spring(gameObjectA, gameObjectB, length, stiffness, options);\nvar constraint = scene.matter.add.joint(gameObjectA, gameObjectB, length, stiffness, options);\n
"},{"location":"matterjs-world/#constraint-to-world-position","title":"Constraint to world position","text":"
var constraint = scene.matter.add.worldConstraint(gameObjectB, length, stiffness, options);\n
  • gameObjectB : Matter game object, or matter body object.
  • length : The target resting length of the constraint.
    • undefined : Current distance between gameObjectA and gameObjectB. (Default value)
  • stiffness : The stiffness of the constraint.
    • 1 : Very stiff. (Default value)
    • 0.2 : Acts as a soft spring.
  • options :
    {\npointA: {\nx: 0,\ny: 0,\n},\npointB: {\nx: 0,\ny: 0,\n},\ndamping: 0,\nangularStiffness: 0,\n// render: {\n//     visible: true\n// }\n}\n
    • pointA : World position.
    • pointB : Offset position of gameObjectB.
"},{"location":"matterjs-world/#chain-game-objects","title":"Chain game objects","text":"
var composite = scene.matter.add.chain(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options);\n
  • composite : Image composite
  • xOffsetA, yOffsetA : Offset position of gameObjectA, in scale.
    • xOffset = (Offset distance / width)
    • yOffset = (Offset distance / height)
  • xOffsetB, yOffsetB : Offset position of gameObjectB, in scale.
  • options :
    {\nlength: undefined,\nstiffness: 1,\ndamping: 0,\nangularStiffness: 0,\n// render: {\n//     visible: true\n// }\n}\n
    • length : The target resting length of the constraint.
      • undefined : Current distance between gameObjectA and gameObjectB. (Default value)
    • stiffness : The stiffness of the constraint.
      • 1 : Very stiff. (Default value)
      • 0.2 : Acts as a soft spring.
  • composite
    • composite.bodies : An array of bodies.
    • composite.constraints : An array of constraints
"},{"location":"matterjs-world/#remove-constraint","title":"Remove constraint","text":"
scene.matter.world.removeConstraint(constraint);\n
"},{"location":"matterjs-wrap/","title":"Wrap","text":""},{"location":"matterjs-wrap/#introduction","title":"Introduction","text":"

Automatically wrap the position of bodies and composites such that they always stay within the given bounds.

  • Reference
"},{"location":"matterjs-wrap/#usage","title":"Usage","text":""},{"location":"matterjs-wrap/#system-configuration","title":"System configuration","text":"
  • Game config
    var config = {\n// ...\nphysics: {\nmatter: {\n// ...\nplugins: {\nwrap: true,\n// ...\n}\n// ...\n}\n}\n// ...\n}\nvar game = new Phaser.Game(config);\n
  • Runtime
    scene.matter.system.enableWrapPlugin();\n
"},{"location":"matterjs-wrap/#matter-object-configuration","title":"Matter object configuration","text":"
var options = {\n// ...\nplugin: {\nwrap: {\nmin: {\nx: 0,\ny: 0\n},\nmax: {\nx: 1024,\ny: 1024\n}\n}\n},\n// ...\n}\n
"},{"location":"mesh/","title":"Mesh","text":""},{"location":"mesh/#introduction","title":"Introduction","text":"

Render a group of textured vertices and manipulate the view of those vertices, such as rotation, translation or scaling.

  • Author: Richard Davey

WebGL only

It only works in WebGL render mode.

"},{"location":"mesh/#usage","title":"Usage","text":""},{"location":"mesh/#quad","title":"Quad","text":"

Note

See also Plane

  1. Load texture
    scene.load.image(key, url);\n
  2. Add mesh object
    var mesh = scene.add.mesh(x, y, texture, frame);\n
    or
    var mesh = scene.make.mesh({\nx: 0,\ny: 0,\nadd: true,\n\nkey: null,\nframe: null\n});\n
  3. Set perspective or orthographic projection
    • Perspective projection
      mesh.setPerspective(width, height, fov);\n// mesh.setPerspective(width, height, fov, near, far);\n
      • width, height : The width/height of the projection matrix. Typically the same as the Mesh and/or Renderer.
      • fov : The field of view, in degrees.
      • near, far : The near/far value of the view. Default value are 0.01/1000.
    • Orthographic projection
      mesh.setOrtho(mesh.width/mesh.height, 1);\n// mesh.setOrtho(scaleX, scaleY, near, far);\n
      • scaleX, scaleY : The default horizontal/vertical scale in relation to the Mesh / Renderer dimensions.
      • near, far : The near/far value of the view. Default value are 0.01/1000.
  4. Creates a grid of vertices
    Phaser.Geom.Mesh.GenerateGridVerts({\nmesh: mesh,\ntexture: textureKey,\nframe: frameName,\nwidth: 1,\nheight: 1,\nwidthSegments: 1,\nheightSegments: 1,\n\n// x: 0,\n// y: 0,\n// colors: 0xffffff,\n// alphas: 1,\n// tile: false,\n// isOrtho: false\n})\n
    • mesh : The vertices of the generated grid will be added to this Mesh Game Object.
    • texture : The texture to be used for this Grid.
    • frame : The name or index of the frame within the Texture.
    • width , height : The width/height of the grid in 3D units.
      {\n// ...\nwidth: (frameWidth/frameHeight),\nheight: (frameHeight/frameHeight)\n// ...\n}\n
    • widthSegments, heightSegments : The number of segments to split the grid horizontally/vertically in to.
    • colors : An array of colors, one per vertex, or a single color value applied to all vertices.
    • alphas An array of alpha values, one per vertex, or a single alpha value applied to all vertices.
    • tile :
      • false : Display as a single texture. Default value.
      • true : Texture tile (repeat) across the grid segments.
"},{"location":"mesh/#model","title":"Model","text":"
  1. Load model
    scene.load.obj(key, url, objURL, matURL);\n
    • objURL : URL to load the obj file.
    • matURL : URL to load the material file.
  2. Add mesh object
    var mesh = scene.add.mesh(x, y);\n
    or
    var mesh = scene.make.mesh({\nx: 0,\ny: 0,\nadd: true\n});\n
  3. Add model
    mesh.addVerticesFromObj(key, scale, x, y, z, rotateX, rotateY, rotateZ, zIsUp);\n
    • key : The key of the model data in the OBJ Cache to add to this Mesh.
    • scale : An amount to scale the model data by. Default is 1.
    • x, y, z : Translate the model x/y/z position by this amount.
    • rotateX, rotateY, rotateZ : Rotate the model on the x/y/z axis by this amount, in radians.
    • zIsUp :
      • true : Z axis is up.
      • false : Y axis is up.
"},{"location":"mesh/#custom-mesh-class","title":"Custom mesh class","text":"
  • Define class
    class MyMesh extends Phaser.GameObjects.mesh {\nconstructor(scene, x, y, texture, frame, vertices, uvs, indicies, containsZ, normals, colors, alphas) {\nsuper(scene, x, y, texture, frame, vertices, uvs, indicies, containsZ, normals, colors, alphas);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var mesh = new MyMesh(scene, x, y, texture, frame);\n
"},{"location":"mesh/#control","title":"Control","text":""},{"location":"mesh/#view","title":"View","text":"
  • Translates the view position of this Mesh on the x/y/z axis by the given amount.
    mesh.panX(x);\nmesh.panY(y);\nmesh.panZ(z);\n
"},{"location":"mesh/#model_1","title":"Model","text":"
  • Position
    mesh.modelPosition.x = x;\nmesh.modelPosition.y = y;\nmesh.modelPosition.z = z;\n
    • x, y, z : Offset position.
      • z+ : Near
      • z- : Far
      • x- : Left
      • x+ : Right
      • y+ : Up
      • y- : Down
  • Rotation
    mesh.modelRotation.x = radiansX;\nmesh.modelRotation.y = radiansY;\nmesh.modelRotation.z = radiansZ;\n
    or
    mesh.rotateX = degreesX;\nmesh.rotateY = degreesY;\nmesh.rotateZ = degreesZ;\n
    • radiansX, radiansY, radiansZ : Rotation angle in radians.
    • degreesX, degreesY, degreesZ : Rotation angle in degrees.
  • Scale
    mesh.modelScale.x = scaleX;\nmesh.modelScale.y = scaleY;\nmesh.modelScale.z = scaleZ;\n
    • scaleX, scaleY, scaleZ : Scale value, 1 is origin size.
"},{"location":"mesh/#backward-facing-faces","title":"Backward facing Faces","text":"
  • Hide backward facing Faces. Default behavior.
    mesh.hideCCW = true;\n
  • Show backward facing Faces
    mesh.hideCCW = false;\n
"},{"location":"mesh/#faces","title":"Faces","text":"

Mesh is composed of triangle faces.

var faces = mesh.faces;\n
"},{"location":"mesh/#contains","title":"Contains","text":"
  • Has any face which contains point
    var isHit = mesh.hasFaceAt(worldX, worldY);\n// var isHit = mesh.hasFaceAt(worldX, worldY, camera);\n
  • Get face contains point
    var face = mesh.getFaceAt(worldX, worldY);\n// var face = mesh.getFaceAt(worldX, worldY, camera);\n
"},{"location":"mesh/#properties","title":"Properties","text":"
  • Alpha
    • Get
      var alpha = face.alpha;\n
    • Set
      face.alpha = alpha;\n
  • Angle
    • Rotate
      Phaser.Geom.Mesh.RotateFace(face, radians);\n
  • Center position
    • Get
      var x = face.x;\nvar y = face.y;\n
      • x : 0(left) ~ 1(right)
      • y : 1(top) ~ 0(bottom)
    • Set
      face.x = x;\nface.y = y;\n
      or
      face.translate(x, y);\n
      • x : 0(left) ~ 1(right)
      • y : 1(top) ~ 0(bottom)
"},{"location":"mesh/#vertices","title":"Vertices","text":"

Each face has 3 vertices.

var vertices = mesh.vertices;\n
  • vertices : Array of vertex.
"},{"location":"mesh/#properties_1","title":"Properties","text":"
  • Alpha
    • Get
      var alpha = vertex.alpha;\n
    • Set
      vertex.alpha = alpha;\n
  • Tint
    • Get
      var color = vertex.color;\n
    • Set
      vertex.color = color;\n
"},{"location":"mesh/#update-properties","title":"Update properties","text":"
  • Start updating
    mesh.ignoreDirtyCache = true;\n
  • Stop updating
    mesh.ignoreDirtyCache = false;\n
"},{"location":"mesh/#interactive","title":"Interactive","text":"

To test if pointer is at any face of this mesh game object.

mesh.setInteractive();\n
"},{"location":"mesh/#debug","title":"Debug","text":"
  1. Set debug Graphics
    var debugGraphics = scene.add.graphics();\nmesh.setDebug(debugGraphics);\n
  2. Update Graphics in scene.update() method.
    debugGraphics.clear();\ndebugGraphics.lineStyle(1, 0x00ff00);\n
"},{"location":"mesh/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"mesh/#create-mask","title":"Create mask","text":"
var mask = mesh.createBitmapMask();\n

See mask

"},{"location":"mesh/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"modal-promise/","title":"Modal promise","text":""},{"location":"modal-promise/#introduction","title":"Introduction","text":"

Modal behavior wrapped into promise.

  • Author: Rex
  • Promise
"},{"location":"modal-promise/#live-demos","title":"Live demos","text":"
  • Manual
  • Timeout
  • Modal dialog
"},{"location":"modal-promise/#usage","title":"Usage","text":"

Sample code

"},{"location":"modal-promise/#install-plugin","title":"Install plugin","text":""},{"location":"modal-promise/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexmodalplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexmodalplugin.min.js', true);\n
  • Add modal behavior
    scene.plugins.get('rexmodalplugin').promise(gameObject, config)\n.then(function(closeEventData) {\n})\n
"},{"location":"modal-promise/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add modal behavior
    scene.plugins.get('rexModal').promise(gameObject, config)\n.then(function(closeEventData) {\n})\n
"},{"location":"modal-promise/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ModalPromise } from 'phaser3-rex-plugins/plugins/modal.js';\n
  • Add modal behavior
    ModalPromise(gameObject, config)\n.then(function(closeEventData) {\n})\n
"},{"location":"modal-promise/#promise","title":"Promise","text":"
scene.plugins.get('rexModal').promise(gameObject, config)\n.then(function(closeEventData) {\n})\n
  • config : See Modal behavior
"},{"location":"modal-promise/#close","title":"Close","text":"

scene.plugins.get('rexModal').close(gameObject);\n// scene.plugins.get('rexModal').close(gameObject, closeEventData);\n
or
gameObject.emit('modal.requestClose');\n// gameObject.emit('modal.requestClose', closeEventData);\n

  • Fire 'modal.requestClose' event on game object, which will invoke modal.requestClose() method. After closing dialog, resolve part of promise will be triggered.
graph TB\n\nPromise[\"promose('gameObject, config)\"]\nOnOpen[\"gameObject.on('modal.open')\"]\nRequestCloseEvent[\"gameObject.emit('modal.requestClose', closeEventData)\"]\nTimeOut[\"Timeout<br>Any touch\"]\nOnClose[\"gameObject.on('modal.close')\"]\nResolve[\"then(function(closeEventData) { })\"]\n\nPromise --> |Transition-in| OnOpen\nOnOpen --> |manualClose| RequestCloseEvent\nOnOpen --> |Not manualClose| TimeOut\nRequestCloseEvent --> |Transition-out| OnClose\nTimeOut --> |Transition-out| OnClose\nOnClose --> Resolve
"},{"location":"modal-promise/#events","title":"Events","text":"
  • To invoke modal.requestClose() method
    gameObject.emit('modal.requestClose', closeEventData);\n
  • On opened dialog
    gameObject.on('modal.open', function(modalBehavior) {\n})\n
  • On closed dialog
    gameObject.on('modal.close', function(closeEventData, modalBehavior) {\n})\n
"},{"location":"modal/","title":"Modal behavior","text":""},{"location":"modal/#introduction","title":"Introduction","text":"

Pop-up modal dialog, then scale-down this dialog.

  • Author: Rex
  • Behavior of game object
"},{"location":"modal/#live-demos","title":"Live demos","text":"
  • Manual
  • Timeout
  • Touch outside
  • Custom transit
"},{"location":"modal/#usage","title":"Usage","text":"

Sample code

"},{"location":"modal/#install-plugin","title":"Install plugin","text":""},{"location":"modal/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexmodalplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexmodalplugin.min.js', true);\n
  • Add modal behavior
    var modal = scene.plugins.get('rexmodalplugin').add(gameObject, config);\n
"},{"location":"modal/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add modal behavior
    var modal = scene.plugins.get('rexModal').add(gameObject, config);\n
"},{"location":"modal/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ModalBehavoir } from 'phaser3-rex-plugins/plugins/modal.js';\n
  • Add modal behavior
    var modal = new ModalBehavoir(gameObject, config);\n
"},{"location":"modal/#create-instance","title":"Create instance","text":"
var modal = scene.plugins.get('rexModal').add(gameObject, {\n// cover: {\n//     color: 0x0,\n//     alpha: 0.8,\n//     transitIn: function(gameObject, duration) { },\n//     transitOut: function(gameObject, duration) { },\n// },\n// cover: false, \n\n// When to close modal dialog?\n// touchOutsideClose: false,\n// anyTouchClose: false,\n// timeOutClose: false,\n// manualClose: false,\n\n// duration: {\n//     in: 200,\n//     hold: 2000,\n//     out: 200\n// }\n\n// transitIn: 0,\n// transitOut: 0,\n\n// destroy: true,\n// openOnStart: true\n});\n
  • cover : Configuration of Cover -- A rectangle shape covered full window, and block all touch events.
    • false : Don't create cover game object.
    • cover.transitIn : Custom callback. Default behavior is fade-in.
      function(gameObject, duration) {\n\n}\n
    • cover.transitOut : Custom callback. Default behavior is fade-out.
      function(gameObject, duration) {\n\n}\n
  • touchOutsideClose : Set to true to close modal dialog when clicking out side of gameObject.
    • Default value is false. Will be set to false if anyTouchClose is set to true.
  • anyTouchClose : Set to true to close modal dialog when any clicking.
    • Default value is false.
  • timeOutClose : Set to true to close modal dialog when holding time out (duration.hold).
    • If duration.hold is given, default value is true. Otherwise default value is false.
  • manualClose : Set to true to close modal dialog via modal.requestClose() method.
    • Default value is false. When this parameter is true, other closing methods will be disabled.
    • If touchOutsideClose, anyTouchClose, and timeOutClose are false, it is equal to manualClose.
  • duration : Duration of transition-in, hold, trantion-out.
    • duration.in : Duration of transition-in (open dialog).
      • 0 : No transition, open dialog immediately.
    • duration.out : Duration of transition-out (close dialog).
      • 0 : No transition, close dialog immediately.
    • duration.hold : Duration of hold.
      • -1 : Disable timeOutClose.
  • transitIn : Transition behavior of opening dialog.
    • 0, 'popUp' : Pop up dialog from 0 to current scale.
    • 1, 'fadeIn' : Fade in dialog
    • Custom callback
      function(gameObject, duration) {\n\n}\n
  • transitOut : Tween behavior of closing dialog.
    • 0, 'scaleDown' : Scale down dialog
    • 1, 'fadeOut' : Fade out dialog
    • Custom callback
      function(gameObject, duration) {\n\n}\n
  • destroy
    • true : Destroy dialog game object and this behavior when closing completed. Default behavior.
    • fasle : Keep dialog game object and this behavior when closing completed. Could reuse it later.
  • openOnStart:
    • true : Open dialog game object (modal.requestOpen()) at beginning. Default behavior.
    • false : Open dialog game object manually.
"},{"location":"modal/#open","title":"Open","text":"
  • Will open modal dialog game object (run transition-in callback) when creating this behavior, if openOnStart is set to true.
  • Invoke modal.requestOpen() to open modal dialog game object again, after closing modal dialog.
    • Set destroy to false to reuse dialog game object and this behavior.
"},{"location":"modal/#close","title":"Close","text":"
modal.requestClose();\n// modal.requestClose(closeEventData);\n
  • closeEventData : Emit 'close' event when closed dialog complete, pass closeEventData to callback of this event.
    modal.on('close', function(closeEventData) {\n})\n
"},{"location":"modal/#events","title":"Events","text":"
  • On opened dialog
    modal.on('open', function(gameObject, modal) {\n})\n
  • On closed dialog
    modal.on('close', function(closeEventData) {\n})\n
"},{"location":"mousewheel/","title":"Mouse wheel","text":""},{"location":"mousewheel/#introduction","title":"Introduction","text":"

Mouse wheel events of phaser.

  • Author: Richard Davey
"},{"location":"mousewheel/#usage","title":"Usage","text":""},{"location":"mousewheel/#mouse-wheel-events","title":"Mouse wheel events","text":"
  1. Events on touched Game object
    gameObject.on('wheel', function(pointer, dx, dy, dz, event){ /* ... */ });\n
  2. Event on input plugin for each touched Game object
    scene.input.on('gameobjectwheel', function(pointer, gameObject, dx, dy, dz, event){ /* ... */ });\n
  3. Events to get all touched Game Objects
    scene.input.on('wheel', function(pointer, currentlyOver, dx, dy, dz, event){ /* ... */ });\n
"},{"location":"mousewheel/#mouse-wheel-properties","title":"Mouse wheel properties","text":"
  • pointer.deltaX : The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device.
  • pointer.deltaY : The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device.
  • pointer.deltaZ : The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device.
"},{"location":"mousewheelscroller/","title":"Mouse wheel scroller","text":""},{"location":"mousewheelscroller/#introduction","title":"Introduction","text":"

Emit scroll event when mouse-wheeling.

  • Author: Rex
  • Member of scene
"},{"location":"mousewheelscroller/#live-demos","title":"Live demos","text":"
  • Scroller
"},{"location":"mousewheelscroller/#usage","title":"Usage","text":"

Sample code

"},{"location":"mousewheelscroller/#install-plugin","title":"Install plugin","text":""},{"location":"mousewheelscroller/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexmousewheelscrollerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexmousewheelscrollerplugin.min.js', true);\n
  • Add mouse-wheeling-to-cursor-key object
    var scroller = scene.plugins.get('rexmousewheelscrollerplugin').add(gameObject, config);\n
"},{"location":"mousewheelscroller/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import MouseWheelScrollerPlugin from 'phaser3-rex-plugins/plugins/mousewheelscroller-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexMouseWheelScroller',\nplugin: MouseWheelScrollerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add mouse-wheeling-to-cursor-key object
    var scroller = scene.plugins.get('rexMouseWheelScroller').add(gameObject, config);\n
"},{"location":"mousewheelscroller/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import MouseWheelScroller from 'phaser3-rex-plugins/plugins/mousewheelscroller.js';\n
  • Add mouse-wheeling-to-cursor-key object
    var scroller = new MouseWheelScroller(gameObject, config);\n
"},{"location":"mousewheelscroller/#create-instance","title":"Create instance","text":"
var scroller = scene.plugins.get('rexMouseWheelScroller').add(gameObject, {\n// focus: true,\n// speed: 0.1,\n// enable: true,\n});\n
  • focus : Fire 'scroll' event when mouse-wheeling --
    • false, or 0 : Without checking if cursor is over game object or not.
    • true, or 1 : Cursor is over game object. Default behavior.
    • 2 : Cursor is inside the rectangle bounds of game object.
  • speed : Scrolling speed. Default value is 0.1.
  • enable : Set true to enable 'scroll' event.
"},{"location":"mousewheelscroller/#event","title":"Event","text":"
  • Scroll
    scroller.on('scroll', function(inc, gameObject, scroller) {\n\n}, scope)\n
    • inc : Scroll value,
      • Positive value : Mouse-wheeling down
      • Negative value : Mouse-wheeling up
"},{"location":"mousewheelscroller/#speed","title":"Speed","text":"
  • Set
    scroller.setSpeed(speed);\n// scroller.speed = speed;\n
  • Get
    var speed = scroller.speed;\n
"},{"location":"mousewheelscroller/#enable","title":"Enable","text":"
  • Set
    scroller.setEnable(enable);\n// scroller.enable = enable;\n
  • Get
    var enable = scroller.enable;\n
"},{"location":"mousewheeltoupdown/","title":"Mouse-wheel to up/down","text":""},{"location":"mousewheeltoupdown/#introduction","title":"Introduction","text":"

Map mouse-wheeling to (up/down) cursor key state.

  • Author: Rex
  • Member of scene
"},{"location":"mousewheeltoupdown/#usage","title":"Usage","text":"

Sample code

"},{"location":"mousewheeltoupdown/#install-plugin","title":"Install plugin","text":""},{"location":"mousewheeltoupdown/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexmousewheeltoupdownplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexmousewheeltoupdownplugin.min.js', true);\n
  • Add mouse-wheeling-to-cursor-key object
    var mouseWheelToUpDown = scene.plugins.get('rexmousewheeltoupdownplugin').add(scene);\n
"},{"location":"mousewheeltoupdown/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import MouseWheelToUpDownPlugin from 'phaser3-rex-plugins/plugins/mousewheeltoupdown-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexMouseWheelToUpDown',\nplugin: MouseWheelToUpDownPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add mouse-wheeling-to-cursor-key object
    var mouseWheelToUpDown = scene.plugins.get('rexMouseWheelToUpDown').add(scene);\n
"},{"location":"mousewheeltoupdown/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import MouseWheelToUpDown from 'phaser3-rex-plugins/plugins/mousewheeltoupdown.js';\n
  • Add mouse-wheeling-to-cursor-key object
    var mouseWheelToUpDown = new MouseWheelToUpDown(scene);\n
"},{"location":"mousewheeltoupdown/#create-instance","title":"Create instance","text":"
var mouseWheelToUpDown = scene.plugins.get('rexMouseWheelToUpDown').add(scene);\n
"},{"location":"mousewheeltoupdown/#state-of-cursor-keys","title":"State of cursor keys","text":"
var cursorKeys = mouseWheelToUpDown.createCursorKeys();\n\nvar upKeyDown = cursorKeys.up.isDown;\nvar downKeyDown = cursorKeys.down.isDown;\n

Or

var upKeyDown = mouseWheelToUpDown.up;\nvar downKeyDown = mouseWheelToUpDown.down;\nvar noKeyDown = mouseWheelToUpDown.noKey;\n
"},{"location":"mousewheeltoupdown/#destroy","title":"Destroy","text":"
mouseWheelToUpDown.destroy();\n
"},{"location":"moveto/","title":"Move to","text":""},{"location":"moveto/#introduction","title":"Introduction","text":"

Move game object towards target position with a steady speed.

  • Author: Rex
  • Behavior of game object
"},{"location":"moveto/#live-demos","title":"Live demos","text":"
  • Move-to
"},{"location":"moveto/#usage","title":"Usage","text":"

Sample code

"},{"location":"moveto/#install-plugin","title":"Install plugin","text":""},{"location":"moveto/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexmovetoplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexmovetoplugin.min.js', true);\n
  • Add move-to behavior
    var moveTo = scene.plugins.get('rexmovetoplugin').add(gameObject, config);\n
"},{"location":"moveto/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import MoveToPlugin from 'phaser3-rex-plugins/plugins/moveto-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexMoveTo',\nplugin: MoveToPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add move-to behavior
    var moveTo = scene.plugins.get('rexMoveTo').add(gameObject, config);\n
"},{"location":"moveto/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import MoveTo from 'phaser3-rex-plugins/plugins/moveto.js';\n
  • Add move-to behavior
    var moveTo = new MoveTo(gameObject, config);\n
"},{"location":"moveto/#create-instance","title":"Create instance","text":"
var moveTo = scene.plugins.get('rexMoveTo').add(gameObject, {\n// speed: 400,\n// rotateToTarget: false\n});\n
  • speed : Moving speed, pixels in second.
  • rotateToTarget : Set true to change angle towards path.
"},{"location":"moveto/#start-moving","title":"Start moving","text":"
  • Move to target position
    moveTo.moveTo(x, y);\n
    or
    moveTo.moveTo({\nx: 0,\ny: 0,\n// speed: 0\n});\n
    • x , y : Target position
  • Move from start position to current position
    moveTo.moveFrom(x, y);\n
    or
    moveTo.moveFrom({\nx: 0,\ny: 0,\n// speed: 0\n});\n
    • x , y : Start position
  • Move toward angle
    moveTo.moveToward(angle, distance);\n
    • angle : Angle in radian.
"},{"location":"moveto/#target-position","title":"Target position","text":"
var targetX = moveTo.targetX;\nvar targetY = moveTo.targetY;\n
"},{"location":"moveto/#enable","title":"Enable","text":"
  • Enable (default)
    moveTo.setEnable();\n
    or
    moveTo.enable = true;\n
  • Disable
    moveTo.setEnable(false);\n
    or
    moveTo.enable = false;\n
"},{"location":"moveto/#pause-resume-stop-moving","title":"Pause, Resume, stop moving","text":"
moveTo.pause();\nmoveTo.resume();\nmoveTo.stop();\n
"},{"location":"moveto/#set-speed","title":"Set speed","text":"
moveTo.setSpeed(speed);\n// moveTo.speed = speed;\n
"},{"location":"moveto/#set-rotate-to-target","title":"Set rotate-to-target","text":"
moveTo.setRotateToTarget(rotateToTarget);\n
  • rotateToTarget : Set true to change angle towards target
"},{"location":"moveto/#events","title":"Events","text":"
  • On start moving
    moveTo.on('start', function(gameObject, moveTo){});\n
  • On reached target
    moveTo.on('complete', function(gameObject, moveTo){});\n// moveTo.once('complete', function(gameObject, moveTo){});\n
"},{"location":"moveto/#status","title":"Status","text":"
  • Is moving
    var isRunning = moveTo.isRunning;\n
"},{"location":"mustache/","title":"Mustache","text":""},{"location":"mustache/#introduction","title":"Introduction","text":"

Format string with variables. Reference

"},{"location":"mustache/#usage","title":"Usage","text":"
var template = 'hello, {{name}}';\nvar view = {\nname: 'rex'\n};\nvar result = Mustache.render(template, view);\n
"},{"location":"ninepatch/","title":"Nine patch","text":""},{"location":"ninepatch/#introduction","title":"Introduction","text":"

Stretchable image, extended from RenderTexture game object.

  • Author: Rex
  • Game object
"},{"location":"ninepatch/#live-demos","title":"Live demos","text":"
  • 3x3, 3x3
  • 5x5
  • Custom frame name
  • Custom base frame name
  • Preserve ratio
  • Max-fixed-part-scale
"},{"location":"ninepatch/#usage","title":"Usage","text":"

Sample code

"},{"location":"ninepatch/#install-plugin","title":"Install plugin","text":""},{"location":"ninepatch/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexninepatchplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexninepatchplugin.min.js', true);\n
  • Add nine-patch object
    var ninePatch = scene.add.rexNinePatch(x, y, width, height, key, baseFrame, columns, rows, config);\n
"},{"location":"ninepatch/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import NinePatchPlugin from 'phaser3-rex-plugins/plugins/ninepatch-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexNinePatchPlugin',\nplugin: NinePatchPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add nine-patch object
    var ninePatch = scene.add.rexNinePatch(x, y, width, height, key, baseFrame, columns, rows, config);\n
"},{"location":"ninepatch/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import NinePatch from 'phaser3-rex-plugins/plugins/ninepatch.js';\n
  • Add nine-patch object
    var ninePatch = new NinePatch(scene, x, y, width, height, key, baseFrame, columns, rows, config);\nscene.add.existing(ninePatch);\n
"},{"location":"ninepatch/#create-instance","title":"Create instance","text":"
var ninePatch = scene.add.rexNinePatch(x, y, width, height, key, baseFrame, columns, rows, {\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch(x, y, width, height, key, columns, rows, {\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch(x, y, width, height, key, {\ncolumns: undefined, // leftWidth: undefined, right: undefined,\nrows: undefined,    // topHeight: undefined, bottomHeight: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch(x, y, width, height, {\nkey: undefined,\ncolumns: undefined, // leftWidth: undefined, right: undefined,\nrows: undefined,    // topHeight: undefined, bottomHeight: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch(x, y, {\nwidth: 1, height: 1,\nkey: undefined,\ncolumns: undefined, // leftWidth: undefined, right: undefined,\nrows: undefined,    // topHeight: undefined, bottomHeight: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch({\nx: 0, y: 0,\nwidth: 1, height: 1,\nkey: undefined,\ncolumns: undefined, // leftWidth: undefined, rightWidth: undefined,\nrows: undefined,    // topHeight: undefined, bottomHeight: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,  // frame: undefined,\ngetFrameNameCallback: undefined\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • key : Texture key of source image.
  • baseFrame, or frame : Frame name of base texture.
    • undefined : Use default base frame '__BASE'.
  • columns : Configuration of columns.
    • A number array, like [20, 20, 20], or [20, undefined, 20] : Width of each column. undefined value will be replaced by remainder value from texture width.
      • Width of odd columns (column 0, column 2, ...) will be origin width.
      • Width of even columns (column 1, column 3, ...) will be stretched.
  • leftWidth, rightWidth : Set columns to [leftWidth, undefined, rightWidth], if columns is undefined.
  • rows : Configuration of rows.
    • A number array, like [20, 20, 20], or [20, undefined, 20] : Height of each row. undefined value will be replaced by remainder value from texture width.
      • Height of odd rows (row 0, row 2, ...) will be origin height.
      • Height of odd rows (row 1, row 3, ...) will be stretched.
  • topHeight, bottomHeight : Set rows to [topHeight, undefined, bottomHeight], if rows is undefined.
  • preserveRatio : Preserve ratio of fixed parts (i.e. displaying in origin size). Default is true.
  • maxFixedPartScale : Max scale value of fixed-part.
  • stretchMode : Stretch mode of edges and internal cells.
    • A number (0, or 1), or a string ('scale', or 'repeat'):
      • 0, or 'scale' : Stretch each edge and internal cell by scaled image. Default value.
      • 1, or 'repeat' : Stretch each edge and internal cell by repeated image (tile-sprite).
    • An object :
      {\nedge: 0, // 'scale', or 1, 'repeat'\ninternal: 0, // 'scale', or 1, 'repeat'\n}\n
  • getFrameNameCallback : Callback to get frame name of each cell.
    • undefined : Use default callback.
      • If baseFrame is '__BASE' : return ${colIndex},${rowIndex}
      • Else : return ${baseFrame}_${colIndex},${rowIndex}
    • Function object : Return a string, or undefined.
      function(colIndex, rowIndex, baseFrame) {\nreturn `${colIndex},${rowIndex}`;\n}\n
"},{"location":"ninepatch/#custom-class","title":"Custom class","text":"
  • Define class
    class MyNinePatch extends NinePatch {\nconstructor(scene, x, y, width, height, key, baseFrame, columns, rows, config) {\nsuper(scene, x, y, width, height, key, baseFrame, columns, rows, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var ninePatch = new MyNinePatch(scene, x, y, width, height, key, baseFrame, columns, rows, config);\n
"},{"location":"ninepatch/#resize","title":"Resize","text":"
ninePatch.resize(width, height);\n

Will update texture

"},{"location":"ninepatch/#set-base-texture-of-source-image","title":"Set base texture of source image","text":"
ninePatch.setBaseTexture(key, baseFrame, columns, rows);\n

or

ninePatch.setBaseTexture(key, baseFrame, leftWidth, rightWidth, topHeight, bottomHeight);\n

or

ninePatch.setBaseTexture(key, baseFrame);\n
  • key : Texture key of source image.
  • baseFrame : Frame name of base texture.
    • undefined, or null : Use default base frame '__BASE'. Default value.
  • columns : Configuration of columns.
    • A number array, like [20, 20, 20] : Width of each column.
      • Width of odd columns (column 0, column 2, ...) will be origin width.
      • Width of even columns (column 1, column 3, ...) will be stretched.
    • undefined : If columns and rows are undefined, it will use current configuration of columns and rows.
  • rows : Configuration of rows.
    • A number array, like [20, 20, 20] : Height of each row.
      • Height of odd rows (row 0, row 2, ...) will be origin height.
      • Height of odd rows (row 1, row 3, ...) will be stretched.
    • undefined : If columns and rows are undefined, it will use current configuration of columns and rows.
  • leftWidth, rightWidth : Set columns to [leftWidth, undefined, rightWidth].
  • topHeight, bottomHeight : Set rows to [topHeight, undefined, bottomHeight].

Will update texture

"},{"location":"ninepatch/#set-stretch-mode","title":"Set stretch mode","text":"
ninePatch.setStretchMode(mode);\n
  • mode :
    • A number (0, or 1), or a string ('scale', or 'repeat'):
      • 0, or 'scale' : Stretch each edge and internal cell by scaled image. Default value.
      • 1, or 'repeat' : Stretch each edge and internal cell by repeated image (tile-sprite).
    • An object :
      {\nedge: 0, // 'scale', or 1, 'repeat'\ninternal: 0, // 'scale', or 1, 'repeat'\n}\n
"},{"location":"ninepatch/#set-get-frame-name-callback","title":"Set get-frame-name callback","text":"
ninePatch.setGetFrameNameCallback(callback);\n
  • callback : Return a string, or undefined.
    function(colIndex, rowIndex, baseFrame) {\nreturn `${colIndex},${rowIndex}`\n}\n
"},{"location":"ninepatch/#fixed-part-scale","title":"Fixed-part scale","text":"
  • Fixed-part scale
    • Get
      var scaleX = ninePatch.fixedPartScaleX;\nvar scaleY = ninePatch.fixedPartScaleY;\n
  • Max fixed-part scale
    • Get
      var scaleX = ninePatch.maxFixedPartScaleX;\nvar scaleY = ninePatch.maxFixedPartScaleY;\n
    • Set
      ninePatch.setMaxFixedPartScale(scale);\n// ninePatch.setMaxFixedPartScale(scaleX, scaleY);\n
      or
      ninePatch.maxFixedPartScaleX = scaleX;\nninePatch.maxFixedPartScaleY = scaleY;\n
"},{"location":"ninepatch/#update-texture","title":"Update texture","text":"
ninePatch.updateTexture();\n
"},{"location":"ninepatch/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"ninepatch/#create-mask","title":"Create mask","text":"
var mask = ninePatch.createBitmapMask();\n

See mask

"},{"location":"ninepatch/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"ninepatch/#compare-with-nine-slice","title":"Compare with nine-slice","text":"
  • Nine-slice is a built-in game object.
  • Nine-slice has better render performance.
    • Nine-patch extends from render-texture, which will create a new texture, then draw frames on it.
  • Nine-slice is webgl mode only.
  • Nine-slice does not have flip, crop methods.
"},{"location":"ninepatch2/","title":"Nine patch2","text":""},{"location":"ninepatch2/#introduction","title":"Introduction","text":"

Stretchable image. Has better performance than nine-patch.

  • Author: Rex
  • Game object
"},{"location":"ninepatch2/#live-demos","title":"Live demos","text":"
  • 3x3
  • Performance test
"},{"location":"ninepatch2/#usage","title":"Usage","text":"

Sample code

"},{"location":"ninepatch2/#install-plugin","title":"Install plugin","text":""},{"location":"ninepatch2/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexninepatch2plugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexninepatch2plugin.min.js', true);\n
  • Add nine-patch object
    var ninePatch = scene.add.rexNinePatch2(x, y, width, height, key, baseFrame, columns, rows, config);\n
"},{"location":"ninepatch2/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import NinePatch2Plugin from 'phaser3-rex-plugins/plugins/ninepatch2-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexNinePatch2Plugin',\nplugin: NinePatch2Plugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add nine-patch object
    var ninePatch = scene.add.rexNinePatch2(x, y, width, height, key, baseFrame, columns, rows, config);\n
"},{"location":"ninepatch2/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import NinePatch2 from 'phaser3-rex-plugins/plugins/ninepatch2.js';\n
  • Add nine-patch object
    var ninePatch = new NinePatch2(scene, x, y, width, height, key, baseFrame, columns, rows, config);\nscene.add.existing(ninePatch);\n
"},{"location":"ninepatch2/#create-instance","title":"Create instance","text":"
var ninePatch = scene.add.rexNinePatch2(x, y, width, height, key, baseFrame, columns, rows, {\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch2(x, y, width, height, key, columns, rows, {\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch2(x, y, width, height, key, {\ncolumns: undefined,\nrows: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch2(x, y, width, height, {\nkey: undefined,\ncolumns: undefined,\nrows: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch2(x, y, {\nwidth: 1, height: 1,\nkey: undefined,\ncolumns: undefined,\nrows: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch2({\nx: 0, y: 0,\nwidth: 1, height: 1,\nkey: undefined,\ncolumns: undefined,\nrows: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • key : Texture key of source image.
  • baseFrame : Frame name of base texture.
    • undefined : Use default base frame '__BASE'.
  • columns : Configuration of columns.
    • A number array, like [20, 20, 20], or [20, undefined, 20] : Width of each column. undefined value will be replaced by remainder value from texture width.
      • Width of odd columns (column 0, column 2, ...) will be origin width.
      • Width of even columns (column 1, column 3, ...) will be stretched.
  • rows : Configuration of rows.
    • A number array, like [20, 20, 20], or [20, undefined, 20] : Height of each row. undefined value will be replaced by remainder value from texture width.
      • Height of odd rows (row 0, row 2, ...) will be origin height.
      • Height of odd rows (row 1, row 3, ...) will be stretched.
  • preserveRatio : Preserve ratio of fixed parts (i.e. displaying in origin size). Default is true.
  • maxFixedPartScale : Max scale value of fixed-part.
  • stretchMode : Stretch mode of edges and internal cells.
    • A number (0, or 1), or a string ('scale', or 'repeat'):
      • 0, or 'scale' : Stretch each edge and internal cell by scaled image. Default value.
      • 1, or 'repeat' : Stretch each edge and internal cell by repeated image (tile-sprite).
    • An object :
      {\nedge: 0, // 'scale', or 1, 'repeat'\ninternal: 0, // 'scale', or 1, 'repeat'\n}\n
  • getFrameNameCallback : Callback to get frame name of each cell.
    • undefined : Use default callback.
      • If baseFrame is '__BASE' : return ${colIndex},${rowIndex}
      • Else : return ${baseFrame}:${colIndex},${rowIndex}
    • Function object : Return a string, or undefined.
      function(colIndex, rowIndex, baseFrame) {\nreturn `${colIndex},${rowIndex}`;\n}\n
"},{"location":"ninepatch2/#custom-class","title":"Custom class","text":"
  • Define class
    class MyNinePatch extends NinePatch2 {\nconstructor(scene, x, y, width, height, key, baseFrame, columns, rows, config) {\nsuper(scene, x, y, width, height, key, baseFrame, columns, rows, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var ninePatch = new MyNinePatch(scene, x, y, width, height, key, baseFrame, columns, rows, config);\n
"},{"location":"ninepatch2/#resize","title":"Resize","text":"
ninePatch.resize(width, height);\n

Will update texture

"},{"location":"ninepatch2/#tint","title":"Tint","text":"
  • Set tint
    ninePatch.setTint(tint);\n
  • Clear tint
    ninePatch.clearTint();\n
  • Set tint fill
    ninePatch.setTintFill(tint);\n
  • Get tint
    var tint = ninePatch.tint;\nvar tintFill = ninePatch.tintFill;\n
    • tintFill :
      • false : Solid tint + texture alpha
      • true : Solid tint, no texture
"},{"location":"ninepatch2/#set-texture-of-source-image","title":"Set texture of source image","text":"
ninePatch.setBaseTexture(key, baseFrame, columns, rows);\n// ninePatch.setBaseTexture(key, columns, rows);\n
  • key : Texture key of source image.
  • baseFrame : Frame name of base texture.
    • undefined : Use default base frame '__BASE'. Default value.
  • columns : Configuration of columns.
    • A number array, like [20, 20, 20] : Width of each column.
      • Width of odd columns (column 0, column 2, ...) will be origin width.
      • Width of even columns (column 1, column 3, ...) will be stretched.
  • rows : Configuration of rows.
    • A number array, like [20, 20, 20] : Height of each row.
      • Height of odd rows (row 0, row 2, ...) will be origin height.
      • Height of odd rows (row 1, row 3, ...) will be stretched.

Will update texture

"},{"location":"ninepatch2/#set-stretch-mode","title":"Set stretch mode","text":"
ninePatch.setStretchMode(mode);\n
  • mode :
    • A number (0, or 1), or a string ('scale', or 'repeat'):
      • 0, or 'scale' : Stretch each edge and internal cell by scaled image. Default value.
      • 1, or 'repeat' : Stretch each edge and internal cell by repeated image (tile-sprite).
    • An object :
      {\nedge: 0, // 'scale', or 1, 'repeat'\ninternal: 0, // 'scale', or 1, 'repeat'\n}\n
"},{"location":"ninepatch2/#set-get-frame-name-callback","title":"Set get-frame-name callback","text":"
ninePatch.setGetFrameNameCallback(callback);\n
  • callback : Return a string, or undefined.
    function(colIndex, rowIndex, baseFrame) {\nreturn `${colIndex},${rowIndex}`\n}\n
"},{"location":"ninepatch2/#fixed-part-scale","title":"Fixed-part scale","text":"
  • Fixed-part scale
    • Get
      var scaleX = ninePatch.fixedPartScaleX;\nvar scaleY = ninePatch.fixedPartScaleY;\n
  • Max fixed-part scale
    • Get
      var scaleX = ninePatch.maxFixedPartScaleX;\nvar scaleY = ninePatch.maxFixedPartScaleY;\n
    • Set
      ninePatch.setMaxFixedPartScale(scale);\n// ninePatch.setMaxFixedPartScale(scaleX, scaleY);\n
      or
      ninePatch.maxFixedPartScaleX = scaleX;\nninePatch.maxFixedPartScaleY = scaleY;\n
"},{"location":"ninepatch2/#update-texture","title":"Update texture","text":"
ninePatch.updateTexture();\n
"},{"location":"ninepatch2/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"ninepatch2/#create-mask","title":"Create mask","text":"
var mask = ninePatch.createBitmapMask();\n

See mask

"},{"location":"ninepatch2/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"ninepatch2/#compare-with-nine-patch","title":"Compare with nine-patch","text":"
  • Nine-patch2 has better performance.
    • Nine-patch extends from render-texture, which will create a new texture, then draw frames on it.
    • Nine-patch2 draws frames directly.
  • Nine-patch2 does not have flip, crop methods.
  • Nine-patch2 can't apply custom spriteFx pipeline.
"},{"location":"nineslice/","title":"Nine slice","text":""},{"location":"nineslice/#introduction","title":"Introduction","text":"

Display a texture-based object that can be stretched both horizontally and vertically, but that retains fixed-sized corners, built-in game object of phaser.

  • Author: Richard Davey

WebGL only

Only work in WebGL render mode.

"},{"location":"nineslice/#usage","title":"Usage","text":""},{"location":"nineslice/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"nineslice/#add-nine-slice-object","title":"Add nine slice object","text":"
var nineSlice = scene.add.nineslice(x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight);\n

or

var nineSlice = scene.add.nineslice(x, y, texture, frame, width, height);\n// var nineSlice = scene.add.nineslice(x, y, texture, frame);\n
  • If that frame (indexed by texture, frame) is generated by Texture Packer.

Add nine slice from JSON

var nineSlice = scene.make.nineslice({\nx: 0,\ny: 0,\nkey: '',\n// frame: '',\n\n// width: 256,\n// height: 256,\n// leftWidth: 10,\n// rightWidth: 10,\n// topHeight: 0,\n// bottomHeight: 0,\n\n// angle: 0,\n// alpha: 1,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
"},{"location":"nineslice/#custom-class","title":"Custom class","text":"
  • Define class
    class MyNineSlice extends Phaser.GameObjects.NineSlice {\nconstructor(scene, x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight) {\nsuper(scene, x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var nineSlice = new MyNineSlice(scene, x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight);\n
"},{"location":"nineslice/#resize","title":"Resize","text":"
nineSlice.setSize(width, height);\n
"},{"location":"nineslice/#set-texture-of-source-image","title":"Set texture of source image","text":"
nineSlice.setTexture(texture, frame);\nnineSlice.setSlices(width, height, leftWidth, rightWidth, topHeight, bottomHeight);\n
"},{"location":"nineslice/#texture","title":"Texture","text":"

See game object - texture

"},{"location":"nineslice/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"nineslice/#create-mask","title":"Create mask","text":"
var mask = nineSlice.createBitmapMask();\n

See mask

"},{"location":"nineslice/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"nineslice/#compare-with-nine-patch","title":"Compare with nine-patch","text":"
  • Nine-slice is a built-in game object.
  • Nine-slice has better render performance.
    • Nine-patch extends from render-texture, which will create a new texture, then draw frames on it.
  • Nine-slice is webgl mode only.
  • Nine-slice does not have flip, crop methods.
"},{"location":"orientation/","title":"Orientation","text":""},{"location":"orientation/#introduction","title":"Introduction","text":"

Get oriention, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"orientation/#usage","title":"Usage","text":""},{"location":"orientation/#orientation","title":"Orientation","text":"
var orientation = scene.scale.orientation;\n
"},{"location":"orientation/#events","title":"Events","text":"
  • On orientation change
    scene.scale.on('orientationchange', function(orientation) {\nswitch (orientation) {\ncase Phaser.Scale.PORTRAIT:\ncase Phaser.Scale.PORTRAIT_SECONDARY:\n// ...\nbreak;\n\ndefault:  // Phaser.Scale.LANDSCAPE or Phaser.Scale.LANDSCAPE_SECONDARY\n// ...\nbreak;\n}\n});\n
"},{"location":"orientation/#lock-orientation","title":"Lock orientation","text":"
scene.scale.lockOrientation(orientation)\n
  • orientation :
    • 'portrait'
    • 'landscape'
    • 'portrait-primary'
    • 'portrait-secondary'
    • 'landscape-primary'
    • 'landscape-secondary'
    • 'default'
"},{"location":"pad/","title":"Pad","text":""},{"location":"pad/#introduction","title":"Introduction","text":"

Takes the given string and pads it out, to the length required, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"pad/#usage","title":"Usage","text":"
var result = Phaser.Utils.String.Pad(str, len, pad, dir);\n
  • str : String, or number.
  • len : Length or result string.
  • pad : The string to pad it out.
  • dir :
    • 1 : Left
    • 2 : Right
    • 3 : Both
"},{"location":"particles-along-bounds/","title":"Particles along bounds","text":""},{"location":"particles-along-bounds/#introduction","title":"Introduction","text":"

Emit particles along bounds of game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"particles-along-bounds/#live-demos","title":"Live demos","text":"
  • Particles-along-bounds
"},{"location":"particles-along-bounds/#usage","title":"Usage","text":"

Sample code

"},{"location":"particles-along-bounds/#install-plugin","title":"Install plugin","text":""},{"location":"particles-along-bounds/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexparticlesalongboundsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexparticlesalongboundsplugin.min.js', true);\n
  • Start emit particles along bounds of game object
    var particles = scene.plugins.get('rexparticlesalongboundsplugin').startEffect(gameObject, config);\n
"},{"location":"particles-along-bounds/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import DragPlugin from 'phaser3-rex-plugins/plugins/particlesalongbounds-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexParticlesAlongBounds',\nplugin: ParticlesAlongBoundsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Start emit particles along bounds of game object
    var particles = scene.plugins.get('rexParticlesAlongBounds').startEffect(gameObject, config);\n
"},{"location":"particles-along-bounds/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ParticlesAlongBounds from 'phaser3-rex-plugins/plugins/particlesalongbounds.js';\n
  • Start emit particles along bounds of game object
    var particles = ParticlesAlongBounds(gameObject, config);\n
"},{"location":"particles-along-bounds/#create-instance","title":"Create instance","text":"
var particles = scene.plugins.get('rexParticlesAlongBounds').startEffect(gameObject, {\ntextureKey: key,\n// textureFrames: undefined,\n// padding: 0,\n// blendMode: 'ADD',\n// lifespan: 1000,\n// stepRate: 10,\n// spread: 10,\n\n// scale: undefined,\n// alpha: undefined,\n// tint: undefined,\n\n// repeat: 0,\n// gravityX: 0,\n// gravityY: 0,\n// duration: undefined\n});\n
  • padding : Extra padded space around bounds of game object. Default is 0.
    • A number for left/right/top/bottom bounds,
    • Or a plain object.
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • textureKey : Texture key of particles.
  • textureFrames : : One or more texture frames, or a configuration object.
    • String or number value.
    • Array of string or number value.
    • Configuration object :
      {\nframes: [],\ncycle: false,\nquantity: 1\n}\n
  • blendMode : Blend mode of particles. Default value is ADD.
  • lifespan : Lifespan of particle.
  • stepRate : Step length between each particle's initial position along bounds of game object.
  • spread : Moving speed of particle.
  • scale : Scale changing of particle.
  • alpha : Alpha changing of particle.
  • tint : Tint changing of particle.
  • repeat : Fire particles around bounds repeatly.
    • 0 : Fire particles around bounds one time, default value.
  • gravityX, gravityY : Gravity vector of world axis. This vector will rotate back if game object is rotated.
  • duration : Total duration from firing of 1st particle to destroy last particle.
    • undefined : Use default behavior of particles
    • Less or equal to lifespan : Fires all particles at begining.

Format of spread, scale, alpha, tint parameters :

  • {min, max} : Pick a random value between min and max
  • {start, end} : Pick values incremented continuously across a range. (ease='Linear')
    • {start, end, ease}
  • {start, end, steps} : Pick values incremented by steps across a range.
  • {start, end, random}
    • random: true or false
  • {min, max, steps} : Pick values between min to max, with steps.
  • {onEmit: function(particle, key, t, value) {return value}} : Get return value from a function invoking.
"},{"location":"particles-along-bounds/#is-running","title":"Is running","text":"
var isRunning = particles.isRunning;\n
"},{"location":"particles-along-bounds/#events","title":"Events","text":"
  • On fire completed, i.e. last particle is dead
    particles.on('complete', function(gameObject, particles){\n\n}, scope);\n
"},{"location":"particles/","title":"Particles","text":""},{"location":"particles/#introduction","title":"Introduction","text":"

Particles uses its own lightweight physics system, and can interact only with its Emitter's bounds and zones. Built-in game object of phaser.

  • Author: Richard Davey

Note

API is not compatible with 3.55.x

"},{"location":"particles/#usage","title":"Usage","text":""},{"location":"particles/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"particles/#add-particle","title":"Add particle","text":"
var particles = scene.add.particles(x, y, texture, {\n\n// EmitterOp\naccelerationX: 0,\naccelerationY: 0,\nalpha: 1,\nangle: { min: 0, max: 360 },\nbounce: 0,\ncolor: undefined,\ndelay: 0,\nhold: 0,\nlifespan: 1000,\nmaxVelocityX: 10000,\nmaxVelocityY: 10000,\nmoveToX: 0,\nmoveToY: 0,\nquantity: 1,\nrotate: 0,\nscaleX: 1,\nscaleY: 1,\n// scale:\nspeedX: 0,\nspeedY: 0,\nspeed: tint: 0xffffff,\nx: 0,\ny: 0,\n\n// Emitter properties\nactive:\nadvance:\nblendMode:\ncolorEase:\ndeathCallback:\ndeathCallbackScope:\nduration:\nemitCallback:\nemitCallbackScope:\n// callbackScope    \nfrequency:\ngravityX:\ngravityY:\nmaxAliveParticles:\nmaxParticles:\nname:\nemitting:\nparticleBringToTop:\nparticleClass:\nradial:\nsortCallback:\nsortOrderAsc:\nsortProperty:\nstopAfter:\ntintFill:\ntimeScale:\ntrackVisible:\nvisible:\n\n// Position\n// emitZone : random-zone, edge-zone\n// random-zone\nemitZone: {\ntype: 'random',\nsource: geom,\n},\n\n// edge-zone\nemitZone:{\ntype: 'edge',\nsource: geom,\nquantity: 1,\nstepRate: 0,\ntotal: -1,\nyoyo: false,\nseamless: true\n},\n\ndeathZone: {\ntype: 'onEnter', // 'onEnter', or 'onLeave'\nsource: geom,\n},\n\nbounds:               // {x, y, w, h}, or {x, y, width, height}, or Phaser.Geom.Rectangle\ncollideLeft: true,\ncollideRight: true,\ncollideTop: true,\ncollideBottom: true,\n\nfollow:\nfollowOffset:{\nx: 0,\ny: 0\n},\n\n// Texture\ntexture:\nframe:\nanim: [],  // string, or array of string\n\nreserve: 0,\nadvance: 0\n});\n
  • Parameters of EmitterOp : Number, Random Array, Custom Callback, Stepped start/end, Eased start/end, min/max, Random object, Custom onEmit onUpdate, Interpolation
    • A number
    • {min, max} : Pick a random value between min and max
    • {min, max, int}
    • {start, end} : Pick values incremented continuously across a range. (ease='Linear')
      • {start, end, ease}
      • {start, end, ease, easeParams}
    • {start, end, steps} : Pick values incremented by steps across a range.
    • {start, end, steps, yoyo: true}
    • {start, end, random}
      • random: true or false
    • {random: [start, end]} : Pick a random number between start and and.
    • [a, b, c, d] : Pick a random number from an array.
    • {min, max, steps} : Pick values between min to max, with steps.
    • { values: [ a, b, c, d ], interpolation: 'catmull', ease: 'linear' } : Interpolation (linear, bezier, catmull) in values array.
    • function(particle, key, t, value) { return value; }
    • {onEmit, onUpdate} : Get return value from a function invoking.
      function(particle, key, t, value) {\nreturn value;\n}\n
  • active : Whether this emitter updates itself and its particles.
    • false : Equal to pause.
  • advance : If you wish to fast forward the emitter in time, set this value to a number representing the amount of ms the emitter should advance.
  • blendMode : See blend mode
  • colorEase : The string-based name of the Easing function to use if you have enabled Particle color interpolation via the color property, otherwise has no effect.
  • deathCallback, deathCallbackScope
    function(particle) {\n\n}\n
  • emitCallback, emitCallbackScope
    function(particle, emitter) {\n\n}\n
  • duration : Limit the emitter to emit particles for a maximum of duration ms.
    • 0 : Forever, default behavior.
  • follow : A Game Object whose position is used as the particle origin.
  • followOffset : The offset of the particle origin from thefollow target.
  • frequency
    • 0 : One particle flow cycle for each logic update (the maximum flow frequency).
    • > 0 : The time interval between particle flow cycles in ms.
    • -1 : Exploding emitter.
  • hold : Frozen or 'held in place' after it has finished its lifespan for a set number of ms
  • gravityX, gravityY
  • maxAliveParticles
  • maxParticles
    • 0 : Unlimited.
    • > 0 : Hard limit the amount of particle objects.
  • frames : One or more texture frames, or a configuration object.
    • String or number value
    • Array of string or number value
    • Configuration object :
      {\nframes: [],\ncycle: false,\nquantity: 1\n}\n
  • anim :
    • String
    • Array of string
    • Configuration object :
      {\nanim: [],  // Array of string\ncycle: false,\nquantity: 1\n}\n
  • particleBringToTop :
    • true : Newly emitted particles are added to the top of the particle list, i.e. rendered above those already alive. Default behavior.
  • sortCallback : The callback used to sort the particles.
  • sortProperty : Optionally sort the particles before they render based on this property. The property must exist on the Particle class, such as y, lifeT, scaleX, etc.
  • sortOrderAsc : When sortProperty is defined this controls the sorting order, either ascending or descending.
  • stopAfter : The Particle Emitter will stop emitting particles once this total has been reached. It will then enter a 'stopped' state, firing the STOP event.
  • radial : A radial emitter will emit particles in all directions between angle min and max,
  • emitting : Controls if the emitter is currently emitting a particle flow (when frequency >= 0). Already alive particles will continue to update until they expire.
    • false : Equal to stop
  • tintFill :
  • timeScale : The time rate applied to active particles, affecting lifespan, movement, and tweens. Values larger than 1 are faster than normal.
  • trackVisible : Whether the emitter's visible state will track the follow target's visibility state.
  • emitZone :
    • Emit zone
      {\ntype: 'random',\nsource: geom,\n}            
    • Emit edge
      {\ntype: 'edge',\nsource: curve,\n\nquantity: 1,\nstepRate: 0,\nyoyo: false,\nseamless: true\n}            
  • deathZone
    {\ntype: 'onEnter', // 'onEnter', or 'onLeave'\nsource: geom\n}\n
  • bounds : {x, y, w, h}, or {x, y, width, height}, or Rectangle.
  • collideLeft, collideRight, collideTop, collideBottom : Whether particles interact with the left/right/top/bottom edge of the bounds.
  • name
  • particleClass
"},{"location":"particles/#control","title":"Control","text":"
  • Start
    emitter.start();\n// emitter.start(advance, duration);\n
    • advance : Advance this number of ms in time through the emitter.
    • duration : Limit this emitter to only emit particles for the given number of ms. Setting this parameter will override any duration already set in the Emitter configuration object.
  • Stop
    emitter.stop();\n// emitter.stop(kill);\n
    • kill :
      • true : Kill all particles immediately
      • false : Leave them to die after their lifespan expires. Default behavior.
  • Pause
    emitter.pause();  // set `active` to false\n
  • Resume
    emitter.resume();  // set `active` to true\n
  • Starts (or restarts) a particle flow.
    emitter.flow(frequency, count, stopAfter);\n
    • frequency :
      • >= 0 : The time interval of each flow cycle, in ms
      • -1 : Explosion mode.
    • count : The number of particles to emit at each flow cycle.
    • stopAfter : Stop this emitter from firing any more particles once this value is reached.
      • Setting this parameter will override any stopAfter value already set in the Emitter configuration object.
      • 0 : Unlimited
  • Explode : Puts the emitter in explode mode (frequency = -1), stopping any current particle flow, and emits several particles all at once.
    emitter.explode();\n// emitter.explode(count, x, y);\n
    • count : The number of Particles to emit.
    • x, y : The x, y coordinate to emit the Particles from.
  • Emit : Emits particles at the given position. If no position is given, it will emit from this Emitters current location.
    emitter.emitParticleAt();\n// emitter.emitParticleAt(x, y, count);    \n
    or
    emitter.emitParticle(count, x, y);\n
    • count : The number of Particles to emit.
    • x, y : The x, y coordinate to emit the Particles from.
  • Fast forward
    emitter.fastForward(time, delta);\n
    • time : The number of ms to advance the Particle Emitter by.
    • delta : The amount of delta to use for each step. Defaults to 1000 / 60.
  • Kill all alive particles
    emitter.killAll()\n
"},{"location":"particles/#follow-target","title":"Follow target","text":"
  • Start
    emitter.startFollow(target);\n// emitter.startFollow(target, offsetX, offsetY, trackVisible);\n
    • target : The Game Object to follow.
    • offsetX, offsetY : Horizontal/vertical offset of the particle origin from the Game Object.
    • trackVisible : Whether the emitter's visible state will track the target's visible state.
  • Stop
    emitter.stopFollow();\n
"},{"location":"particles/#frame","title":"Frame","text":"

emitter.setEmitterFrame(frames);\n// emitter.setEmitterFrame(frames, pickRandom, quantity);\n
- frames : One or more texture frames, or a configuration object. - String or number value - Array of string or number value - Configuration object :
{\nframes: [],\ncycle: false,\nquantity: 1\n}\n
- pickRandom : - true : Whether frames should be assigned at random from frames. Default behavior. - quantity : The number of consecutive particles that will receive each frame. Default value is 1.

"},{"location":"particles/#animation","title":"Animation","text":"

emitter.setAnim(anims);\n// emitter.setAnim(anims, pickRandom, quantity);\n
- anims : One or more animations, or a configuration object. - String - Array of string - Configuration object :
{\nanims: [],\ncycle: false,\nquantity: 1\n}\n
- anims : One or more animations names, or Play Animation Config objects. - String - Array of string - Animation config - Array of Animation config - pickRandom : - true : Whether frames should be assigned at random from frames. Default behavior. - quantity : The number of consecutive particles that will receive each frame. Default value is 1.

"},{"location":"particles/#particle","title":"Particle","text":"
  • Speed
    emitter.setParticleSpeed(x, y);\n
    or
    emitter.speedX = x;\nemitter.speedY = y;\n
    • Changes the emitter from radial to a point emitter
  • Bounce
    emitter.bounce = value;\n
    • 0 : No bounce
    • 1 : Full rebound
  • Max velocity
    emitter.maxVelocityX = x;\nemitter.maxVelocityY = y;\n
  • Gravity
    emitter.setParticleGravity(x, y);\n
    or
    emitter.gravityX = x;\nemitter.gravityY = y;\n
  • Acceleration
    emitter.accelerationX = x;\nemitter.accelerationY = y;\n
  • Lifespan : Sets the lifespan of newly emitted particles in milliseconds.
    emitter.setParticleLifespan(time);\n
    or
    emitter.lifespan = time\n
  • The number of milliseconds to wait after emission before the particles start updating.
    emitter.delay = time;\n
  • The number of milliseconds to wait after a particle has finished its life before it will be removed.
    emitter.hold = time;\n
  • Tint
    emitter.setParticleTint(tint);\n
    or
    emitter.particleTint = tint;\n
    • Webgl only
  • Color
    emitter.particleColor = color;   // WebGL only.\nemitter.colorEase = easeName;\n
    • Webgl only
  • Alpha
    emitter.setParticleAlpha(alpha);\n
    or
    emitter.setAlpha(alpha);\n
    or
    emitter.particleAlpha = alpha;\n
  • Scale : Sets the vertical and horizontal scale of the emitted particles.
    emitter.setParticleScale(x, y);\n
    or
    emitter.setScale(x, y);\n
    or
    emitter.particleScaleX = x;\nemitter.particleScaleY = y;\n
  • Position
    emitter.particleX = x;\nemitter.particleY = y;\n
  • Position to move toward
    emitter.moveToX = x;\nemitter.moveToY = y;\n
  • The angle at which the particles are emitted.
    emitter.particleAngle = angle;  // degrees    \n
  • The rotation (or angle) of each particle when it is emitted.
    emitter.particleRotate = rotation; // degrees\n
  • The number of particles that are emitted each time an emission occurs
    emitter.quantity = quantity;\n
  • Hard limit the amount of particle objects
    var count = emitter.maxParticles;\n
    • Whether this emitter is at its limit
      var atLimit = emitter.atLimit();\n
  • Alive (active) particles
    • Amount of alive particles
      var count = emitter.getAliveParticleCount();\n
      or
      var count = emitter.alive.length;\n
    • Add callback for newly emitted particle
      var callback = function(particle, emitter) { /* ... */ }\nemitter.onParticleEmit(callback, context);\n
      • Clear callback
        emitter.onParticleEmit();\n
    • For each alive particle
      var callback = function(particle, emitter) { /* ... */ }\nemitter.forEachAlive(callback, context);\n
  • Dead (inactive) particles
    • Amount of dead particles
      var count = emitter.getDeadParticleCount();\n
      or
      var count = emitter.dead.length;\n
    • Add callback for each particle death
      var callback = function(particle, emitter) { /* ... */ }\nemitter.onParticleDeath(callback, context);\n
      • Clear callback
        emitter.onParticleDeath();\n
    • For each dead particle
      var callback = function(particle, emitter) { /* ... */ }\nemitter.forEachDead(callback, context);\n
    • Add dead particles into pool
      emitter.reserve(count);\n
  • Total (alive + dead) number of particles.
    var count = emitter.getParticleCount();\n
  • Active particles overlaps with a Rectangle Geometry object or an Arcade Physics Body.
    var particles = emitter.overlap(target);\n
    • target :
      • A Rectangle.
      • Arcade Physics Body.
    • particles : An array of Particles that overlap with the given target
  • Gets a bounds Rectangle calculated from the bounds of all currently active Particles
    emitter.getBounds(padding, advance, delta, output);\n
    • padding : The amount of padding, in pixels, to add to the bounds Rectangle.
    • advance, delta : Fast forward in time to try and allow the bounds to be more accurate.
    • output : The Rectangle to store the results in.
  • Gets the bounds of this particle as a Geometry Rectangle
    particle.getBounds();\n
"},{"location":"particles/#render-order","title":"Render order","text":"
  • Sort by property
    emitter.setSortProperty(property, ascending);\n
    • property : The property on the Particle class to sort by.
    • ascending : Should the particles be sorted in ascending or descending order?
  • Sort by callback
    var callback = function(particleA, particleB) {\nreturn 1; // 0,1,-1\n}\nemitter.setSortCallback(callback);\n
"},{"location":"particles/#emitter","title":"Emitter","text":"
  • Frequency
    emitter.setFrequency(frequency);\n// emitter.setFrequency(frequency, quantity);\n
    • frequency :
      • >= 0 : The time interval of each flow cycle, in ms
      • -1 : Explosion mode.
    • quantity : The number of particles to release at each flow cycle or explosion.
  • Quantity
    emitter.setQuantity(quantity);\n
    • quantity : The number of particles to release at each flow cycle or explosion.
"},{"location":"particles/#zone","title":"Zone","text":""},{"location":"particles/#emit-zone","title":"Emit zone","text":""},{"location":"particles/#add-emit-zone","title":"Add emit zone","text":"
var zone = emitter.addEmitZone({\ntype: 'random',\nsource: geom,\n});\n
  • source : Geom like Circle, Ellipse, Rectangle,Triangle, Polygon, BitmapZone, or Path or Curve, which has getRandomPoint(point) method
    • Custom zone
      {\ngetRandomPoint: function(point) {\n// point.x = ...\n// point.y = ...\nreturn point;\n}\n}\n
"},{"location":"particles/#add-emit-edge","title":"Add emit edge","text":"
var zone = emitter.addEmitZone({\ntype: 'edge',\nsource: curve,\n\nquantity: 1,\nstepRate: 0,\nyoyo: false,\nseamless: true,\ntotal: -1\n});\n
  • source : Geom like Circle, Ellipse, Rectangle,Triangle, Polygon, or Path or Curve, which has getPoints(quantity, stepRate) method
    • Custom edge
      {\ngetPoints: function(quantity, stepRate) {\n// output = [point0, point1, ...];  // point: Phaser.Math.Vector2, or {x, y}\nreturn output;\n}\n}\n
  • quantity : The number of particles to place on the source edge. Set to 0 to use stepRate instead.
  • stepRate : The distance between each particle. When set, quantity is implied and should be set to 0.
  • yoyo : Whether particles are placed from start to end and then end to start. Default is false.
  • seamless : Whether one endpoint will be removed if it's identical to the other. Default is true.
  • total : The total number of particles this zone will emit before passing over to the next emission zone in the Emitter.

quantity or stepRate

  • Any geometry like circle, ellipse, kine, polygon, rectangle, triangle source has quantity, or stepRate
  • Curve source has quantity, or stepRate
  • Path source only has quantity
"},{"location":"particles/#set-emit-zone","title":"Set emit zone","text":"
emitter.setEmitZone(zone);\n
  • zone : The Emit Zone to set as the active zone.
    • A zone object
    • A number as index
"},{"location":"particles/#zone-source","title":"Zone source","text":"
  • Get
    // var zone = emitter.emitZones[i];\nvar source = zone.source;    
  • (Edge type only) Update points of curve source
    zone.updateSource();\n
  • (Edge type only) Set source to another curve, also update points
    zone.changeSource(curve);\n
"},{"location":"particles/#remove-emit-zone","title":"Remove emit zone","text":"
emitter.removeEmitZone(zone)\n
"},{"location":"particles/#clear-emit-zone","title":"Clear emit zone","text":"

emitter.clearEmitZones();\n
or
emitter.emitZones.length = 0;\nemitter.zoneIndex = 0;\n

"},{"location":"particles/#death-zone","title":"Death zone","text":"
var zone = emitter.addDeathZone({\ntype: 'onEnter',\nsource: geom\n});\n
  • type : 'onEnter' or 'onLeave'
  • source : Geom like Circle, Ellipse, Rectangle,Triangle, Polygon
    • Custom source :
      {\ncontains: function (x, y) {\n// ...\nreturn bool;\n}\n}\n
"},{"location":"particles/#remove-death-zone","title":"Remove death zone","text":"
emitter.removeDeathZone(zone)\n
"},{"location":"particles/#clear-death-zone","title":"Clear death zone","text":"

emitter.clearDeathZones();\n
or
emitter.deathZones.length = 0;\n

"},{"location":"particles/#update-configuration","title":"Update Configuration","text":"
emitter.updateConfig(config)\n
  • config : See config parameter in constructor.
"},{"location":"particles/#events","title":"Events","text":"
  • Starts emission of particles.
    emitter.on('start', function(emitter) {\n\n})\n
  • Explodes a set of particles.
    emitter.on('explode', function(emitter, particle) {\n\n})\n
  • Death Zone kills a Particle instance.
    emitter.on('deathzone', function(emitter, particle, zone) {\n\n})\n
  • Stops emission
    emitter.on('stop', function(emitter) {\n\n})\n
    • Directly call the ParticleEmitter.stop method.
    • Stop after a set time via the duration property.
    • Stop after a set number of particles via the stopAfter property.
  • Complete Event, no particles are still rendering at this point in time.
    emitter.on('complete', function(emitter) {\n\n})\n
"},{"location":"particles/#bounds","title":"Bounds","text":"
  • Add bounds
    var bounds = emitter.addParticleBounds(x, y, width, height);\n// var bounds = emitter.addParticleBounds(x, y, width, height, collideLeft, collideRight, collideTop, collideBottom);\n
    or
    var bounds = emitter.addParticleBounds(rect);\n
    • x, y, width, height, {x, y, width, height}, or {x, y, w, h}, or Rectangle : Bounds
    • collideLeft, collideRight, collideTop, collideBottom : Whether particles interact with the left/right/top/bottom edge of the bounds.
  • Collide edges
    bounds.collideLeft = enabled;\nbounds.collideRight = enabled;\nbounds.collideTop = enabled;\nbounds.collideBottom = enabled;\n
  • Bound rectangle
    var rect = bounds.bounds;\n
    • rect : Rectangle
"},{"location":"particles/#gravity-well","title":"Gravity well","text":"
  • Create a gravity well
    var well = particles.createGravityWell({\n// x: 0,\n// y: 0,\n// power: 0,\n// epsilon: 100,\n// gravity: 50\n});\n
  • Enable
    • Active
      well.active = true;\n
    • Inactive
      well.active = false;\n
  • Position
    well.x = x;\nwell.y = y;\n
  • Gravity
    well.gravity = value;\n
  • Power
    well.power = value;\n
"},{"location":"particles/#custom-particle-processor","title":"Custom Particle Processor","text":"
  • Declare Particle Processor class
    class MyParticleProcessor extends Phaser.GameObjects.Particles.ParticleProcessor {\nconstructor() {\nsuper(x, y, active);\n// ...\n}\n\nupdate(particle, delta, step, t) {\n// particle : The Particle to update.\n// delta : The delta time in ms.\n// step : The delta value divided by 1000.\n// t : The current normalized lifetime of the particle, between 0 (birth) and 1 (death).\n}\n\ndestroy() {\nsuper.destroy();\n}\n}\n
    • Override update method
  • Add to emitter
    var myParticleProcessor = emitter.addParticleProcessor(new MyParticleProcessor);\n
"},{"location":"particles/#custom-particle-class","title":"Custom particle class","text":"
class MyParticle extends Phaser.GameObjects.Particles.Particle {\nconstructor (emitter) {\nsuper(emitter);\n/* ... */\n}\n\nupdate (delta, step, processors) {\nsuper.update(delta, step, processors);\n/* ... */\n}\n}\n
"},{"location":"particles/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"particles/#create-mask","title":"Create mask","text":"
var mask = emitter.createBitmapMask();\n

See mask

"},{"location":"particles/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"path/","title":"Path","text":""},{"location":"path/#introduction","title":"Introduction","text":"

Path in curves, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"path/#usage","title":"Usage","text":""},{"location":"path/#add-path-object","title":"Add path object","text":"
var path = scene.add.path();\n// var path = scene.add.path(x, y);  // curve start from (x, y)\n

or

var path = new Phaser.Curves.Path();\n// var path = new Phaser.Curves.Path(x, y);  // curve start from (x, y)\n
"},{"location":"path/#add-path-object-with-curves","title":"Add path object with curves","text":"

Curves in JSON

var path = scene.add.path(json);\n
or
var path = new Phaser.Curves.Path(json);\n

"},{"location":"path/#add-curve","title":"Add curve","text":""},{"location":"path/#line","title":"Line","text":"
  • Add line object
    1. Create line object
      var curve = new Phaser.Curves.Line({x: x0, y: y0}, {x: x1, y: y1});\n
      or
      var curve = new Phaser.Curves.Line([x0, y0, x1, y1]);\n
    2. Add to path
      path.add(curve);\n
  • Add line started from previous end point to next point
    path.lineTo(endX, endY);\n
    or
    path.lineTo(new Phaser.Math.Vector2({x, y}));\n

Properties:

  • curve.p0 : The first endpoint.
    • curve.p0.x, curve.p0.y
  • curve.p1 : The second endpoint.
    • curve.p1.x, curve.p1.y
"},{"location":"path/#circleellipsearc","title":"Circle/ellipse/arc","text":"
  • Add circle/ellipse/arc object
    1. Create circle/ellipse/arc object
      • Circle
        var curve = new Phaser.Curves.Ellipse(x, y, radius);\n
      • Ellipse
        var curve = new Phaser.Curves.Ellipse(x, y, xRadius, yRadius);\n
      • Arc
        var curve = new Phaser.Curves.Ellipse(x, y, xRadius, yRadius, startAngle, endAngle, clockwise,     rotation);\n
    2. Add to path
      path.add(curve);\n
  • Add circle/ellipse/arc started from previous end point to next point
    • Circle
      path.circleTo(radius);\n
    • Ellipse
      path.ellipseTo(xRadius, yRadius);\n
    • Arc
      path.ellipseTo(xRadius, yRadius, startAngle, endAngle, clockwise, rotation);\n

Properties:

  • curve.p0 : Center point.
    • curve.p0.x, curve.p0.y
  • curve.xRadius, curve.yRadius : Horizontal/vertical radiuse.
  • curve.startAngle, curve.endAngle : Start/end angle, in degrees.
  • curve.clockwise : true if Clockwise, false if anti-clockwise.
  • curve.angle : Rotation, in degrees.
    • curve.rotation : Rotation, in radians.
"},{"location":"path/#spline","title":"Spline","text":"
  • Add spline object
    1. Create spline object
      var curve = new Phaser.Curves.Spline([\np0,            // {x, y}, or [x, y]\np1,            // {x, y}, or [x, y]\n// ...\n]);\n
      or
      var curve = new Phaser.Curves.Spline([\nx0, y0,\nx1, y1,\n// ...\n]);\n
    2. Add to path
      path.add(curve);\n
  • Add spline started from previous end point to next point
    var points = ;\npath.splineTo([\np0,            // {x, y}, or [x, y]\np1,            // {x, y}, or [x, y]\n// ...\n]);\n
    or
    path.splineTo([\nx0, y0,\nx1, y1,\n// ...\n]);\n
"},{"location":"path/#append-point","title":"Append point","text":"
var point = curve.addPoint(x, y);\n
"},{"location":"path/#quadratic-bezier-curve","title":"Quadratic bezier curve","text":"
  1. Create quadratic bezier curve object
    var curve = new Phaser.Curves.QuadraticBezier(startPoint, controlPoint, endPoint); // point: {x, y}\n
    or
    var points = [\nx0, y0,     // start point\nx1, y1,     // control point\nx2, y2      // end point\n];\nvar curve = new Phaser.Curves.QuadraticBezier(points);\n
  2. Add to path
    path.add(curve);\n

Add quadratic bezier curve started from previous end point to next point

path.quadraticBezierTo(endX, endY, controlX, controlY);\n
or
path.quadraticBezierTo(endPoint, controlPoint);  // point : Phaser.Math.Vector2\n

"},{"location":"path/#cubic-bezier-curve","title":"Cubic bezier curve","text":"
  1. Create quadratic bezier curve object
    var curve = new Phaser.Curves.CubicBezier(startPoint, controlPoint1, controlPoint2, endPoint); // point: {x, y}\n
    or
    var points = [\nx0, y0,     // start point\nx1, y1,     // control point1\nx2, y2,     // control point2\nx3, y3      // end point\n];\nvar curve = new Phaser.Curves.CubicBezier(points);\n
  2. Add to path
    path.add(curve);\n

Add cubic bezier curve started from previous end point to next point

path.cubicBezierTo(endX, endY, control1X, control1Y, control2X, control2Y);\n
or
path.cubicBezierTo(endPoint, controlPoint1, controlPoint2);  // point : Phaser.Math.Vector2\n

"},{"location":"path/#move-to-point","title":"Move to point","text":"
path.moveTo(x, y);\n
"},{"location":"path/#add-curves-from-json","title":"Add curves from JSON","text":"
path.fromJSON(json);\n
"},{"location":"path/#get-curves","title":"Get curves","text":"
var curves = path.curves;\n
"},{"location":"path/#get-curve-at-t","title":"Get curve at t","text":"
var curve = path.getCurveAt(t);\n
  • t : The normalized location on the Path. Between 0 and 1
"},{"location":"path/#draw-on-graphics","title":"Draw on graphics","text":"
path.draw(graphics);\n// path.draw(graphics, pointsTotal);\n
  • pointsTotal : The number of points to draw for each Curve.

or

curve.draw(graphics);\n// curve.draw(graphics, pointsTotal);\n
  • pointsTotal : The resolution of the curve.
"},{"location":"path/#point","title":"Point","text":"
  • Get point
    var out = path.getPoint(t);  // t: 0 ~ 1\n// var out = path.getPoint(t, out);  // modify out\n
    or
    var out = curve.getPoint(t);  // t: 0 ~ 1\n// var out = curve.getPoint(t, out);  // modify out\n
    Distance of path from start point to target point (out) might not linear with t.
  • Get random point
    var out = path.getRandomPoint();\n// var out = path.getRandomPoint(out);  // modify out\n
    or
    var out = curve.getRandomPoint();\n// var out = curve.getRandomPoint(out);  // modify out\n
  • Get n points
    • Path
      var points = path.getPoints(divisions);\n
      • divisions : The number of divisions per resolution per curve.
    • Curve
      var points = curve.getPoints(divisions);\n// var points = curve.getPoints(divisions, undefined, out);\n
      or
      var points = curve.getPoints(undefined, stepRate);\n// var points = curve.getPoints(undefined, stepRate, out);\n
      • divisions : The number of divisions in this curve.
        1. divisions, if divisions > 0, else
        2. this.getLength / stepRate, if stepRate > 0, else
        3. defaultDivisions
      • points : Return 1 + divisions points.
  • Get (n+1) points equally spaced out along the curve
    var points = path.getSpacedPoints(n);\n
    or
    var points = curve.getSpacedPoints(n);\n// var points = curve.getSpacedPoints(undefined, stepRate);\n// var points = curve.getSpacedPoints(divisions, stepRate, out);\n
  • Get points spaced out n distance pixels apart
    var points = curve.getDistancePoints(n)\n
    The smaller the distance, the larger the array will be. Path object does NOT support this feature yet.
  • Get start point
    var out = path.getStartPoint();\n// var out = path.getStartPoint(out);  // modify out\n
    or
    var out = curve.getStartPoint();\n// var out = curve.getStartPoint(out);  // modify out\n
  • Get end point
    var out = path.getEndPoint();\n// var out = path.getEndPoint(out);  // modify out\n
    or
    var out = curve.getEndPoint();\n// var out = curve.getEndPoint(out);  // modify out\n
  • Get t (0~1) from distance
    var t = curve.getTFromDistance(d);\n
    Path object does NOT support this feature yet.
  • Get tangent
    var out = path.getTangent(t);  // t: 0~1\n// var out = path.getTangent(t, out);  // modify out\n
    or
    var out = curve.getTangent(t);  // t: 0~1\n// var out = curve.getTangent(t, out);  // modify out\n
"},{"location":"path/#length-of-path","title":"Length of path","text":"

var l = path.getLength();\n
or
var l = curve.getLength();\n

Length of path/curve will be cached.

"},{"location":"path/#update-length","title":"Update length","text":"

path.updateArcLengths();\n
or
curve.updateArcLengths();\n

"},{"location":"path/#curves-to-json","title":"Curves to JSON","text":"

var json = path.toJSON();\n
or
var json = curve.toJSON();\n

"},{"location":"path/#bounds","title":"Bounds","text":"

Get bounds

var out = path.getBounds();    // accuracy = 16\n// var out = path.getBounds(out);\n// var out = path.getBounds(out, accuracy);\n
or
var out = curve.getBounds();    // accuracy = 16\n// var out = curve.getBounds(out);\n// var out = curve.getBounds(out, accuracy);\n

  • out : A rectangle object
"},{"location":"path/#destroy","title":"Destroy","text":"
path.destroy();\n
"},{"location":"pathfollower/","title":"Path follower","text":""},{"location":"pathfollower/#introduction","title":"Introduction","text":"

Set position of game object on a path.

  • Author: Rex
  • Behavior of game object
"},{"location":"pathfollower/#live-demos","title":"Live demos","text":"
  • Path follower
  • Spaced points
"},{"location":"pathfollower/#usage","title":"Usage","text":"

Sample code

"},{"location":"pathfollower/#install-plugin","title":"Install plugin","text":""},{"location":"pathfollower/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexpathfollowerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexpathfollowerplugin.min.js', true);\n
  • Add path-follower behavior
    var pathFollower = scene.plugins.get('rexpathfollowerplugin').add(gameObject, config);\n
"},{"location":"pathfollower/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PathFollowerPlugin from 'phaser3-rex-plugins/plugins/pathfollower-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPathFollower',\nplugin: PathFollowerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add path-follower behavior
    var pathFollower = scene.plugins.get('rexPathFollower').add(gameObject, config);\n
"},{"location":"pathfollower/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import PathFollower from 'phaser3-rex-plugins/plugins/pathfollower.js';\n
  • Add path-follower behavior
    var pathFollower = new PathFollower(gameObject, config);\n
"},{"location":"pathfollower/#create-instance","title":"Create instance","text":"
// var path = scene.add.path();\nvar pathFollower = scene.plugins.get('rexPathFollower').add(gameObject, {\n// path: path,          // path object\n// t: 0,                // t: 0~1\n// rotateToPath: false,\n// rotationOffset: 0,\n// angleOffset: 0,\n\n// spacedPoints: false,\n// spacedPoints: {\n//     divisions: undefined,\n//     stepRate: 10,\n// }\n\n});\n
  • path : Path object
  • t : Initial value of property t (0~1)
  • rotateToPath: Set true to change angle towards path
  • rotationOffset : Rotation offset in radian, or angleOffset in degrees
  • spacedPoints :
    • false, or undefined : Get point by path.getPoint(t)
    • spacedPoints.divisions, spacedPoints.stepRate :
      1. Get points by path.getSpacedPoints(divisions, stepRate)
      2. Get point from linear interpolation of points in step1.
"},{"location":"pathfollower/#move-along-path","title":"Move along path","text":"

Set pathFollower.t (0~1) to move along path

pathFollower.t = t;  // t: 0~1\n// pathFollower.setT(t);\n

or tween pathFollower.t

var tween = scene.tweens.add({\ntargets: pathFollower,\nt: 1,\nease: 'Linear', // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\nrepeat: 0,\nyoyo: false\n});\n
"},{"location":"pathfollower/#set-path","title":"Set path","text":"
pathFollower.setPath(path);\n
"},{"location":"pathfollower/#set-rotate-to-path","title":"Set rotate-to-path","text":"
pathFollower.setRotateToPath(rotateToPath, rotationOffset);\n
  • rotateToPath : Set true to change angle towards path
  • rotationOffset : Rotation offset in radian
"},{"location":"percentage/","title":"Percentage","text":""},{"location":"percentage/#introduction","title":"Introduction","text":"

Work out what percentage value is of the range between min and max, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"percentage/#usage","title":"Usage","text":"
var result = Phaser.Math.Percent(value, min, max);\n
  • result: Percentage/t (0~1).
  • value : The value to determine the percentage of.
"},{"location":"perlin/","title":"Perlin","text":""},{"location":"perlin/#introduction","title":"Introduction","text":"

Perlin2/Perlin3 noise and simplex2/simplex3 noise. (Reference)

  • Author: Rex
  • Method only
"},{"location":"perlin/#live-demos","title":"Live demos","text":"
  • Perlin2
  • Terrain generator
"},{"location":"perlin/#usage","title":"Usage","text":"

Sample code

"},{"location":"perlin/#install-plugin","title":"Install plugin","text":""},{"location":"perlin/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperlinplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperlinplugin.min.js', true);\n
  • Add perlin noise object
    var noise = scene.plugins.get('rexperlinplugin').add(seed);\n
"},{"location":"perlin/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerlinPlugin from 'phaser3-rex-plugins/plugins/perlin-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerlin',\nplugin: PerlinPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add perlin noise object
    var noise = scene.plugins.get('rexPerlin').add(seed);\n
"},{"location":"perlin/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Perlin from 'phaser3-rex-plugins/plugins/perlin.js';\n
  • Add perlin noise object
    var noise = new Perlin(seed);\n
"},{"location":"perlin/#create-noise-instance","title":"Create noise instance","text":"
var noise = scene.plugins.get('rexPerlin').add(seed);\n
  • seed : A seed for this noise, like Math.random()
"},{"location":"perlin/#perlin","title":"Perlin","text":"
  • Perlin2
    var value = noise.perlin2(x, y);\n
    • value : -1 ~ 1
  • Perlin3
    var value = noise.perlin3(x, y, z);\n
    • value : -1 ~ 1
"},{"location":"perlin/#simplex","title":"Simplex","text":"
  • Simplex2
    var value = noise.simplex2(x, y);\n
    • value : -1 ~ 1
  • Simplex3
    var value = noise.simplex3(x, y, z);\n
    • value : -1 ~ 1
"},{"location":"perlin/#set-seed","title":"Set seed","text":"
noise.setSeed(seed);\n
"},{"location":"perspective-card/","title":"Card","text":""},{"location":"perspective-card/#introduction","title":"Introduction","text":"

A container with two perspective-images.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"perspective-card/#live-demos","title":"Live demos","text":"
  • Flip card
  • Label front face
  • Change texture
"},{"location":"perspective-card/#usage","title":"Usage","text":"

Sample code

"},{"location":"perspective-card/#install-plugin","title":"Install plugin","text":""},{"location":"perspective-card/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add card object
    var card = scene.add.rexPerspectiveCard(config);\n
"},{"location":"perspective-card/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add card object
    var card = scene.add.rexPerspectiveCard(config);\n
"},{"location":"perspective-card/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveCard } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add card object
    var card = new PerspectiveCard(scene, config);\nscene.add.existing(card);\n
"},{"location":"perspective-card/#create-instance","title":"Create instance","text":"
var card = scene.add.rexPerspectiveCard({\nx: 0, y: 0,\n\nback: {key, frame},\nfront: {key, frame},\nface: 0,\n\norientation: 0,\n\n// width,\n// height,\n\n// flip : {\n//     frontToBack: 0,\n//     backToFront: 1,\n//     duration: 1000,\n//     ease: 'Cubic',\n//     delay: 0,\n// }\n// flip: false\n});\n
  • front, back : Perspective image game object for front and back face.
    • {key, frame} : Texture key and frame name, to create perspective image
    • {width, height} : Width and height, to create perspective render texture.
    • Perspective image
    • Perspective render texture
  • face : Show front or back face.
    • 'front', or 0 : Show front face.
    • 'back', or 1 : Show back face.
  • orientation : Flipping orientation.
    • 'horizontal','h', 'x', or 0 : Flipping left-to-right, or right-to-left.
    • 'vertical','v', 'y', or 1 : Flipping top-to-bottom, or bottom-to-top.
  • width, height : Specific width and height of this card container.
    • undefined : Use width and height of front and back face.
  • flip : Configuration of flipping behavior.
    • flip.frontToBack, flip.backToFront : Flipping direction.
      • 'right', 'left-to-right', or 0 : Flipping from right to left.
      • 'left', 'right-to-left', or 1 : Flipping from left to right.
    • flip.duration : Duration of flipping, in millisecond.
    • flip.delay : Initial delay.
    • flip.ease : Ease function. Default value is 'Cubic'.
    • false : Don't add flipping behavior.

Add card from JSON

var card = scene.make.rexPerspectiveCard({\nx: 0,\ny: 0,\n\nfront,\nback,\nface: 0,\n\norientation: 0,\n\nwidth,\nheight,\n\nflip,\n\nadd: true\n});\n
"},{"location":"perspective-card/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveCard extends PerspectiveCard {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var card = new MyPerspectiveCard(scene, config);\n
"},{"location":"perspective-card/#face","title":"Face","text":"
  • Get
    var face = card.face;\n
    • face:
      • 0 : Show front face.
      • 1 : Show back face.
  • Set
    card.setFace(face)\n
    • face
      • 'front', or 0 : Show front face.
      • 'back', or 1 : Show back face.
  • Toggle
    card.toggleFace()\n
"},{"location":"perspective-card/#face-instances","title":"Face instances","text":"
  • Front face
    var frontFace = card.frontFace;\n// var frontFace = card.faces.front;\n
  • Back face
    var backFace = card.backFace;\n// var backFace = card.faces.back;\n
"},{"location":"perspective-card/#face-texture","title":"Face texture","text":"
  • Set texture of front face, assume that front face is a perspective image
    card.frontFace.setTexture(key);\n// card.frontFace.setTexture(key, frame);\n
  • Set texture of back face, assume that back face is a perspective image
    card.backFace.setTexture(key);\n// card.backFace.setTexture(key, frame);\n
"},{"location":"perspective-card/#flip-behavior","title":"Flip behavior","text":""},{"location":"perspective-card/#start-flipping","title":"Start flipping","text":"
card.flip.flip();\n// card.flip.flip(duration, repeat);\n
  • duration : Overwrite default duration value.
  • repeat : Number of flipping time (repeat + 1) during duration. Default value is 0.

or

  • Flip-right
    card.flip.flipRight();\n// card.flip.flipRight(duration, repeat);\n
  • Flip-left
    card.flip.flipLeft();\n// card.flip.flipLeft(duration, repeat);\n
"},{"location":"perspective-card/#stop-flipping","title":"Stop flipping","text":"
card.flip.stop();\n
"},{"location":"perspective-card/#set-duration","title":"Set duration","text":"
card.flip.setDuration(duration);\n// card.flip.duration = duration;\n
"},{"location":"perspective-card/#set-ease","title":"Set ease","text":"
card.flip.setEase(ease);\n// card.flip.ease = ease;\n
"},{"location":"perspective-card/#events","title":"Events","text":"
  • On flipping start
    card.flip.on('start', function(flip, card){\n// ...\n});\n
  • On flipping complete
    card.flip.on('complete', function(flip, card){\n// ...\n});\n
"},{"location":"perspective-card/#status","title":"Status","text":"
  • Is flipping
    var isRunning = card.flip.isRunning;\n
"},{"location":"perspective-card/#rotation","title":"Rotation","text":"
  • Get rotation angle
    var angleX = card.angleX; // Angle in degrees\nvar angleY = card.angleY; // Angle in degrees\nvar angleZ = card.angleZ; // Angle in degrees\n
    or
    var rotationX = card.rotationX; // Angle in radians\nvar rotationY = card.rotationY; // Angle in radians\nvar rotationZ = card.rotationZ; // Angle in radians\n
  • Set rotation angle
    card.angleX = angleX; // Angle in degrees\ncard.angleY = angleY; // Angle in degrees\ncard.angleZ = angleZ; // Angle in degrees\n
    or
    card.rotationX = rotationX; // Angle in radians\ncard.rotationY = rotationY; // Angle in radians\ncard.rotationZ = rotationZ; // Angle in radians\n
"},{"location":"perspective-card/#debug","title":"Debug","text":"
  1. Set debug Graphics
    var debugGraphics = scene.add.graphics();\ncard.setDebug(debugGraphics);\n
  2. Update Graphics in scene.update() method.
    debugGraphics.clear();\ndebugGraphics.lineStyle(1, 0x00ff00);\n
"},{"location":"perspective-card/#other-properties","title":"Other properties","text":"

See container, Mesh game object, game object

"},{"location":"perspective-card/#create-mask","title":"Create mask","text":"
var mask = card.createBitmapMask();\n

See mask

"},{"location":"perspective-card/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"perspective-carousel/","title":"Carousel","text":""},{"location":"perspective-carousel/#introduction","title":"Introduction","text":"

A container with cards.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"perspective-carousel/#live-demos","title":"Live demos","text":"
  • Carousel
  • List
  • UI cards
"},{"location":"perspective-carousel/#usage","title":"Usage","text":"

Sample code

"},{"location":"perspective-carousel/#install-plugin","title":"Install plugin","text":""},{"location":"perspective-carousel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add carousel object
    var carousel = scene.add.rexPerspectiveCarousel(config);\n
"},{"location":"perspective-carousel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add carousel object
    var carousel = scene.add.rexPerspectiveCarousel(config);\n
"},{"location":"perspective-carousel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveCarousel } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add carousel object
    var carousel = new PerspectiveCarousel(scene, config);\nscene.add.existing(carousel);\n
"},{"location":"perspective-carousel/#create-instance","title":"Create instance","text":"
var carousel = scene.add.rexPerspectiveCarousel({\nx: 0, y: 0,\n\nfaces: [],\n// face: 0,\n// rtl: false,\n\n// width,\n// height,\n\n// faceWidth,\n// faceSpace: 0,\n\n// z: 1,\n// zEnd: 0,\n\n// roll : {\n//     duration: 1000,\n//     ease: 'Cubic',\n//     delay: 0,\n// }\n});\n
  • faces : Array of perspective-card, perspective-rendertexture, perspective-image, or null.
    • Assume that all faces have the same size
  • face : Index or name of current face (face at angle 0).
  • rtl
    • false : Place faces from left to right. Default behavior.
    • true : Place faces from right to left.
  • width, height : Specific width and height of this carousel container.
    • undefined : Use width and height of first face.
  • faceWidth : Width of face.
    • undefined : Use width of face. Assume that all faces have the same size.
  • faceSpace : Extra space of face width. Used when faceWidth is undefined.
  • z, zEnd : Range of faces' z-index. Default value is 1/0.
  • roll : Configuration of rolling behavior.
    • roll.duration : Duration of rolling, in millisecond.
    • roll.delay : Initial delay.
    • roll.ease : Ease function. Default value is 'Cubic'.
    • false : Don't add rolling behavior.

Add carousel from JSON

var carousel = scene.make.rexPerspectiveCarousel({\nx: 0,\ny: 0,\n\nfaces: [],\n\n// width,\n// height,\n\n// faceWidth,\n// faceSpace: 0,\n\n// z: 1,\n// zEnd: 0,\n\nadd: true\n});\n
"},{"location":"perspective-carousel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveCarousel extends PerspectiveCarousel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var carousel = new MyPerspectiveCarousel(scene, config);\n
"},{"location":"perspective-carousel/#face-instances","title":"Face instances","text":"
var faces = carousel.faces;\n
  • faces : Array of face instances.
"},{"location":"perspective-carousel/#face","title":"Face","text":"
  • Get
    var face = carousel.face;\n
    • face: Index of carousel.faces.
  • Set
    carousel.setFace(face)\n
    • face : Index or name of current face (face at angle 0).
"},{"location":"perspective-carousel/#roll-behavior","title":"Roll behavior","text":""},{"location":"perspective-carousel/#start-rolling","title":"Start rolling","text":"
  • Roll to next face
    carousel.roll.toNext(duration);\n
    • duration : Overwrite default duration value.
  • Roll to previous face
    carousel.roll.toPrevious(duration);\n
    • duration : Overwrite default duration value.
  • Roll to right face
    carousel.roll.toRight(duration);\n
    • duration : Overwrite default duration value.
  • Roll to left face
    carousel.roll.toLeft(duration);\n
    • duration : Overwrite default duration value.
  • Roll to face
    carousel.roll.to(faceIndex, duration);\n
    • faceIndex :
      • A number : Index of face in carousel.faces
      • A string : Name of face (face.setName(name))
    • duration : Overwrite default duration value.
"},{"location":"perspective-carousel/#stop-flipping","title":"Stop flipping","text":"
carousel.roll.stop();\n
"},{"location":"perspective-carousel/#set-duration","title":"Set duration","text":"
carousel.roll.setDuration(duration);\n// carousel.roll.duration = duration;\n
"},{"location":"perspective-carousel/#set-ease","title":"Set ease","text":"
carousel.roll.setEase(ease);\n// carousel.roll.ease = ease;\n
"},{"location":"perspective-carousel/#events","title":"Events","text":"
  • On rolling complete
    carousel.roll.on('complete', function(){\n// ...\n});\n
"},{"location":"perspective-carousel/#status","title":"Status","text":"
  • Is rolling
    var isRunning = carousel.roll.isRunning;\n
"},{"location":"perspective-carousel/#rotation","title":"Rotation","text":"
  • Get rotation angle
    var angleY = carousel.angleY; // Angle in degrees\n
    or
    var rotationY = carousel.rotationY; // Angle in radians\n
  • Set rotation angle
    carousel.angleY = angleY; // Angle in degrees\n
    or
    carousel.rotationY = rotationY; // Angle in radians\n
"},{"location":"perspective-carousel/#other-properties","title":"Other properties","text":"

See container, Mesh game object, game object

"},{"location":"perspective-carousel/#create-mask","title":"Create mask","text":"
var mask = carousel.createBitmapMask();\n

See mask

"},{"location":"perspective-carousel/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"perspective-image/","title":"Image","text":""},{"location":"perspective-image/#introduction","title":"Introduction","text":"

Image with perspective rotation.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"perspective-image/#live-demos","title":"Live demos","text":"
  • Flip image
"},{"location":"perspective-image/#usage","title":"Usage","text":"

Sample code

"},{"location":"perspective-image/#install-plugin","title":"Install plugin","text":""},{"location":"perspective-image/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexPerspectiveImage(x, y, texture, frame, config);\n
"},{"location":"perspective-image/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexPerspectiveImage(x, y, texture, frame, config);\n
"},{"location":"perspective-image/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveImage } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add image object
    var image = new PerspectiveImage(scene, x, y, texture, frame, config);\nscene.add.existing(image);\n
"},{"location":"perspective-image/#create-instance","title":"Create instance","text":"
var image = scene.add.rexPerspectiveImage(x, y, texture, frame, {\n// hideCCW: true,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

or

var image = scene.add.rexPerspectiveImage({\n// x: 0,\n// y: 0,\nkey,\n// frame: null,\n// hideCCW: true,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

Add perspectiveimage from JSON

var perspectiveimage = scene.make.rexPerspectiveImage({\nx: 0,\ny: 0,\n\nkey: null,\nframe: null,\n\n// hideCCW: false,\n// gridWidth: 32,\n// girdHeight: 32,\n\nadd: true\n});\n
"},{"location":"perspective-image/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveImage extends PerspectiveImage {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyPerspectiveImage(scene, x, y, texture, frame, config);\n
"},{"location":"perspective-image/#transform-vertices","title":"Transform vertices","text":"

Offset then rotate all vertices.

image.transformVerts(x, y, z, rotateX, rotateY, rotateZ);\n
  • x, y, z : Offset vertices
    • z+ : Near
    • z- : Far
    • x- : Left
    • x+ : Right
    • y+ : Up
    • y- : Down
  • rotateX, rotateY, rotateZ : Rotate vertices
"},{"location":"perspective-image/#rotation","title":"Rotation","text":"
  • Get rotation angle
    var angleX = image.angleX; // Angle in degrees\nvar angleY = image.angleY; // Angle in degrees\nvar angleZ = image.angleZ; // Angle in degrees\n
    or
    var rotationX = image.rotationX; // Angle in radians\nvar rotationY = image.rotationY; // Angle in radians\nvar rotationZ = image.rotationZ; // Angle in radians\n
  • Set rotation angle
    image.angleX = angleX; // Angle in degrees\nimage.angleY = angleY; // Angle in degrees\nimage.angleZ = angleZ; // Angle in degrees\n
    or
    image.rotationX = rotationX; // Angle in radians\nimage.rotationY = rotationY; // Angle in radians\nimage.rotationZ = rotationZ; // Angle in radians\n
"},{"location":"perspective-image/#flip","title":"Flip","text":"
scene.tweens.add({\ntargets: image,\nangleY: { start: 0, to: -180}\n})\n
"},{"location":"perspective-image/#tint-color","title":"Tint color","text":"
  • Get
    var color = image.tint;\n
  • Set
    image.tint = color;\n
    or
    image.setTint(color);\n
"},{"location":"perspective-image/#texture","title":"Texture","text":"
image.setTexture(key);\n// image.setTexture(key, frame);\n
"},{"location":"perspective-image/#other-properties","title":"Other properties","text":"

See Mesh game object, game object

"},{"location":"perspective-image/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"perspective-image/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"perspective-imagecarousel/","title":"Image carousel","text":""},{"location":"perspective-imagecarousel/#introduction","title":"Introduction","text":"

Display list of images.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"perspective-imagecarousel/#live-demos","title":"Live demos","text":"
  • List
"},{"location":"perspective-imagecarousel/#usage","title":"Usage","text":"

Sample code

"},{"location":"perspective-imagecarousel/#install-plugin","title":"Install plugin","text":""},{"location":"perspective-imagecarousel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add carousel object
    var carousel = scene.add.rexPerspectiveImageCarousel(config);\n
"},{"location":"perspective-imagecarousel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add carousel object
    var carousel = scene.add.rexPerspectiveImageCarousel(config);\n
"},{"location":"perspective-imagecarousel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveImageCarousel } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add carousel object
    var carousel = new PerspectiveImageCarousel(scene, config);\nscene.add.existing(carousel);\n
"},{"location":"perspective-imagecarousel/#create-instance","title":"Create instance","text":"
var carousel = scene.add.rexPerspectiveImageCarousel({\nx: 0, y: 0,\n\nimages: [],  // Array of {key, frame}\n// index: 0,\n// rtl: false,\n// repeat: true,\n\n// width,\n// height,\n// faceCount: 4,\n\n// z: 1,\n// zEnd: 0,\n\n// roll : {\n//     duration: 1000,\n//     ease: 'Cubic',\n//     delay: 0,\n// }\n});\n
  • images : Array of textures {key, frame}
    • Assume that all textures have the same size
  • index : Index of current image.
  • rtl
    • false : Place images from left to right. Default behavior.
    • true : Place images from right to left.
  • repeat : Set true to roll to first image from last, or last to first.
  • width, height : Specific width and height of this carousel container.
    • undefined : Use width and height of first image.
  • faceCount : Faces count of this carousel. A integer which >=3.
  • z, zEnd : Range of faces' z-index. Default value is 1/0.
  • roll : Configuration of rolling behavior.
    • roll.duration : Duration of rolling, in millisecond.
    • roll.delay : Initial delay.
    • roll.ease : Ease function. Default value is 'Cubic'.
    • false : Don't add rolling behavior.

Add perspectiveimage from JSON

var perspectiveimage = scene.make.rexPerspectiveImageCarousel({\nx: 0,\ny: 0,\n\nimages: [],  // Array of {key, frame}\n// index: 0,\n// rtl: false,\n// repeat: true,\n\n// width,\n// height,\n// faceCount: 4,\n\n// z: 1,\n// zEnd: 0,\n\n// roll : {\n//     duration: 1000,\n//     ease: 'Cubic',\n//     delay: 0,\n// }\n\nadd: true\n});\n
"},{"location":"perspective-imagecarousel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveImageCarousel extends PerspectiveImageCarousel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var carousel = new MyPerspectiveImageCarousel(scene, config);\n
"},{"location":"perspective-imagecarousel/#roll-behavior","title":"Roll behavior","text":""},{"location":"perspective-imagecarousel/#start-rolling","title":"Start rolling","text":"
  • Roll to next image
    carousel.roll.toNext(duration);\n
    • duration : Overwrite default duration value.
  • Roll to previous image
    carousel.roll.toPrevious(duration);\n
    • duration : Overwrite default duration value.
  • Roll to right image
    carousel.roll.toRight(duration);\n
    • duration : Overwrite default duration value.
  • Roll to left image
    carousel.roll.toLeft(duration);\n
    • duration : Overwrite default duration value.
  • Roll to image
    carousel.roll.to(faceIndex, duration);\n
    • faceIndex :
      • A number : Index of image.
    • duration : Overwrite default duration value.
"},{"location":"perspective-imagecarousel/#set-duration","title":"Set duration","text":"
carousel.roll.setDuration(duration);\n// carousel.roll.duration = duration;\n
"},{"location":"perspective-imagecarousel/#set-ease","title":"Set ease","text":"
carousel.roll.setEase(ease);\n// carousel.roll.ease = ease;\n
"},{"location":"perspective-imagecarousel/#events","title":"Events","text":"
  • On rolling complete
    carousel.roll.on('complete', function(){\n// ...\n});\n
"},{"location":"perspective-imagecarousel/#status","title":"Status","text":"
  • Is rolling
    var isRunning = carousel.roll.isRunning;\n
"},{"location":"perspective-imagecarousel/#other-properties","title":"Other properties","text":"

See container, Mesh game object, game object

"},{"location":"perspective-imagecarousel/#create-mask","title":"Create mask","text":"
var mask = carousel.createBitmapMask();\n

See mask

"},{"location":"perspective-imagecarousel/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"perspective-imagecarousel/#compare-with-plane-game-object","title":"Compare with Plane game object","text":"
  • Size
    • Size of Plane is equal to current render size.
    • Size of PerspectiveImage is equak to texture size, like normal Image game object.
  • Animation
    • Plane hae animation feature.
    • Useing PerspectiveSprite for animation feature, PerspectiveImage does not have this feature.
  • Checkerboard
    • Plane hae checkerboard feature.
    • PerspectiveImage does not have this feature.
"},{"location":"perspective-rendertexture/","title":"Render texture","text":""},{"location":"perspective-rendertexture/#introduction","title":"Introduction","text":"

Render texture with perspective rotation.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"perspective-rendertexture/#live-demos","title":"Live demos","text":"
  • RenderTexture
"},{"location":"perspective-rendertexture/#usage","title":"Usage","text":"

Sample code

"},{"location":"perspective-rendertexture/#install-plugin","title":"Install plugin","text":""},{"location":"perspective-rendertexture/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add render texture object
    var image = scene.add.rexPerspectiveRenderTexture(x, y, width, height, config);\n
"},{"location":"perspective-rendertexture/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add render texture object
    var image = scene.add.rexPerspectiveRenderTexturege(x, y, width, height, config);\n
"},{"location":"perspective-rendertexture/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveRenderTexture } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add render texture object
    var image = new PerspectiveRenderTexture(scene, x, y, width, height, config);\nscene.add.existing(image);\n
"},{"location":"perspective-rendertexture/#create-instance","title":"Create instance","text":"
var image = scene.add.rexPerspectiveRenderTexturege(x, y, width, height, {\n// hideCCW: true,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

or

var image = scene.add.rexPerspectiveRenderTexturege({\n// x: 0,\n// y: 0,\n// width: 32,\n// height: 32,\n// hideCCW: true,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

Add prespective render texture from JSON

var image = scene.make.rexPerspectiveRenderTexturege({\nx: 0,\ny: 0,    width: 32,\nheight: 32,\n\n// hideCCW: false,\n// gridWidth: 32,\n// girdHeight: 32,\n\nadd: true\n});\n
"},{"location":"perspective-rendertexture/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveRenderTexturege extends PerspectiveRenderTexturege {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyPerspectiveRenderTexturege(scene, x, y, width, height, config);\n
"},{"location":"perspective-rendertexture/#internal-render-texture","title":"Internal render texture","text":"
var rt = image.rt;\n
  • rt : Render texture
"},{"location":"perspective-rendertexture/#paste-texture","title":"Paste texture","text":"
  • Paste game object
    image.rt.draw(gameObject, x, y);\n// image.rt.draw(gameObject, x, y, alpha, tint);\n
  • gameObject : a game object, or an array of game objects
  • Paste game objects in a group
    image.rt.draw(group, x, y);\n// image.rt.draw(group, x, y, alpha, tint);\n
  • Paste game objects in a scene
    image.rt.draw(scene.children, x, y);\n// image.rt.draw(scene.children, x, y, alpha, tint);\n
  • Paste texture
    image.rt.draw(key, x, y);\n// image.rt.draw(key, x, y, alpha, tint);\n
    or
    image.rt.drawFrame(key, frame, x, y);\n// image.rt.drawFrame(key, frame, x, y, alpha, tint);\n
    • key : The key of the texture to be used, as stored in the Texture Manager.
  • Snapshop game objects
    image.snapshot(gameObjects);\n
    • gameObjects : Array of game objects.
"},{"location":"perspective-rendertexture/#erase","title":"Erase","text":"
image.rt.erase(gameObject, x, y);\n
  • gameObject : a game object, or an array of game objects
"},{"location":"perspective-rendertexture/#clear","title":"Clear","text":"
image.rt.clear();\n
"},{"location":"perspective-rendertexture/#fill","title":"Fill","text":"
image.rt.fill(rgb, alpha);\n// image.rt.fill(rgb, alpha, x, y, width, height);\n
"},{"location":"perspective-rendertexture/#other-properties","title":"Other properties","text":"

See Perspective image game object, Mesh game object, game object

"},{"location":"perspective-rendertexture/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"perspective-rendertexture/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"perspective-sprite/","title":"Sprite","text":""},{"location":"perspective-sprite/#introduction","title":"Introduction","text":"

Play animation on perspective-image.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"perspective-sprite/#live-demos","title":"Live demos","text":"
  • Play animation
"},{"location":"perspective-sprite/#usage","title":"Usage","text":"

Sample code

"},{"location":"perspective-sprite/#install-plugin","title":"Install plugin","text":""},{"location":"perspective-sprite/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add sprite object
    var sprite = scene.add.rexPerspectiveSprite(x, y, texture, frame, config);\n
"},{"location":"perspective-sprite/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add sprite object
    var sprite = scene.add.rexPerspectiveSprite(x, y, texture, frame, config);\n
"},{"location":"perspective-sprite/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveSprite } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add sprite object
    var sprite = new PerspectiveSprite(scene, x, y, texture, frame, config);\nscene.add.existing(sprite);\n
"},{"location":"perspective-sprite/#create-instance","title":"Create instance","text":"
var sprite = scene.add.rexPerspectiveSprite(x, y, texture, frame, {\n// width: undefined,\n// height: undefined,\n// hideCCW: true,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

or

var sprite = scene.add.rexPerspectiveImage({\n// x: 0,\n// y: 0,\nkey,\n// frame: null,\n// width: undefined,\n// height: undefined,\n// hideCCW: true,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

Add perspectiveimage from JSON

var perspectiveimage = scene.make.rexPerspectiveImage({\nx: 0,\ny: 0,\n\nkey: null,\nframe: null,\n\n// width: undefined,\n// height: undefined,\n// hideCCW: false,\n// gridWidth: 32,\n// girdHeight: 32,\n\nadd: true\n});\n
"},{"location":"perspective-sprite/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveSprite extends PerspectiveSprite {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var sprite = new MyPerspectiveSprite(scene, x, y, texture, frame, config);\n
"},{"location":"perspective-sprite/#play-animation","title":"Play animation","text":"
  • Play
    sprite.play(key);\n// sprite.play(key, ignoreIfPlaying);\n
    • key : Animation key string, or animation config
      • String key of animation
      • Animation config, to override default config
        {\nkey,\nframeRate,\nduration,\ndelay,\nrepeat,\nrepeatDelay,\nyoyo,\nshowOnStart,\nhideOnComplete,\nstartFrame,\ntimeScale\n}\n
  • Play in reverse
    sprite.playReverse(key);\n// sprite.playReverse(key, ignoreIfPlaying);\n
    • key : Animation key string, or animation config
  • Play after delay
    sprite.playAfterDelay(key, delay);\n
    • key : Animation key string, or animation config
  • Play after repeat
    sprite.playAfterRepeat(key, repeatCount);\n
    • key : Animation key string, or animation config
"},{"location":"perspective-sprite/#chain","title":"Chain","text":"
  • Chain next animation
    sprite.chain(key);\n
    • key : Animation key string, or animation config
  • Chain next and next animation
    sprite.chain(key0).chain(key1);\n
    • key0, key1 : Animation key string, or animation config
"},{"location":"perspective-sprite/#stop","title":"Stop","text":"
  • Immediately stop
    sprite.stop();\n
  • Stop after delay
    sprite.stopAfterDelay(delay);\n
  • Stop at frame
    sprite.stopOnFrame(frame);\n
    • frame : Frame object in current animation.
      var currentAnim = sprite.anims.currentAnim;\nvar frame = currentAnim.getFrameAt(index);\n
  • Stop after repeat
    sprite.stopAfterRepeat(repeatCount);\n
"},{"location":"perspective-sprite/#restart","title":"Restart","text":"
sprite.anims.restart();\n// sprite.anims.restart(includeDelay, resetRepeats);\n
"},{"location":"perspective-sprite/#other-properties","title":"Other properties","text":"

See Perspective image game object, Mesh game object, game object

"},{"location":"perspective-sprite/#create-mask","title":"Create mask","text":"
var mask = sprite.createBitmapMask();\n

See mask

"},{"location":"perspective-sprite/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"plane/","title":"Plane","text":""},{"location":"plane/#introduction","title":"Introduction","text":"

A Plane is a kind of Mesh game object with one-sided grid of cells. which can have a texture that is either repeated (tiled) across each cell, or applied to the full Plane.

  • Author: Richard Davey

WebGL only

It only works in WebGL render mode.

"},{"location":"plane/#usage","title":"Usage","text":""},{"location":"plane/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"plane/#add-plane-object","title":"Add plane object","text":"
var plane = scene.add.plane(x, y, key);\n// var plane = scene.add.plane(x, y, key, frame);\n// var plane = scene.add.plane(x, y, texture, frame, width, height, tile);\n
  • x, y : Position
  • key, frame : Texture key of
  • width, height : The width/height of this Plane, in cells, not pixels.
  • tile : Is the texture tiled? I.e. repeated across each cell.

Add plane from JSON

var plane = scene.make.plane({\nx: 0,\ny: 0,\nkey: '',\n// frame: '',\n// width: 8,\n// height: 8,\n// tile: false,\n// checkerboard: null,\n// checkerboard: { color1, color2, alpha1, alpha2, height }\n\n// angle: 0,\n// alpha: 1,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
"},{"location":"plane/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPlane extends Phaser.GameObjects.Plane {\nconstructor(scene, x, y, texture, frame, width, height, tile) {\nsuper(scene, x, y, texture, frame, width, height, tile);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var plane = new MyPlane(scene, x, y, texture, frame, width, height, tile);\n
"},{"location":"plane/#texture","title":"Texture","text":"

See game object - texture

"},{"location":"plane/#animation","title":"Animation","text":"

See Sprite's animation section.

"},{"location":"plane/#play-animation","title":"Play animation","text":"
  • Play
    plane.play(key);\n// plane.play(key, ignoreIfPlaying);\n
    • key : Animation key string, or animation config
      • String key of animation
      • Animation config, to override default config
        {\nkey,\nframeRate,\nduration,\ndelay,\nrepeat,\nrepeatDelay,\nyoyo,\nshowOnStart,\nhideOnComplete,\nstartFrame,\ntimeScale\n}\n
  • Play in reverse
    plane.playReverse(key);\n// plane.playReverse(key, ignoreIfPlaying);\n
    • key : Animation key string, or animation config
  • Play after delay
    plane.playAfterDelay(key, delay);\n
    • key : Animation key string, or animation config
  • Play after repeat
    plane.playAfterRepeat(key, repeatCount);\n
    • key : Animation key string, or animation config
"},{"location":"plane/#stop","title":"Stop","text":"
  • Immediately stop
    plane.stop();\n
  • Stop after delay
    plane.stopAfterDelay(delay);\n
  • Stop at frame
    plane.stopOnFrame(frame);\n
    • frame : Frame object in current animation.
      var currentAnim = plane.anims.currentAnim;\nvar frame = currentAnim.getFrameAt(index);\n
  • Stop after repeat
    plane.stopAfterRepeat(repeatCount);\n
"},{"location":"plane/#properties","title":"Properties","text":"
  • Has started
    var hasStarted = plane.anims.hasStarted;\n
  • Is playing
    var isPlaying = plane.anims.isPlaying;\n
  • Is paused
    var isPaused = plane.anims.isPaused;\n
  • Total frames count
    var frameCount = plane.anims.getTotalFrames();\n
  • Delay
    var delay = plane.anims.delay;\n
  • Repeat
    • Total repeat count
      var repeatCount = plane.anims.repeat;\n
    • Repeat counter
      var repeatCount = plane.anims.repeatCounter;\n
    • Repeat delay
      var repeatDelay = plane.anims.repeatDelay;\n
    • Yoyo
      var repeatDelay = plane.anims.yoyo;\n
  • Current animation key
    var key = plane.anims.getName();\n
    • key : Return '' if not playing any animation.
  • Current frame name
    var frameName = plane.anims.getFrameName();\n
    • frameName : Return '' if not playing any animation.
  • Current animation
    var currentAnim = plane.anims.currentAnim;\n
  • Current frame
    var currentFrame = plane.anims.currentFrame;\n
"},{"location":"plane/#interactive","title":"Interactive","text":"

To test if pointer is at any face of this mesh game object.

plane.setInteractive();\n
"},{"location":"plane/#other-properties","title":"Other properties","text":"

See Mesh game object, game object

"},{"location":"plane/#checkerboard","title":"Checkerboard","text":"

Creates a checkerboard style texture, based on the given colors and alpha values and applies it to this Plane, replacing any current texture it may have.

  • Create
    plane.createCheckerboard(color1, color2, alpha1, alpha2, height)\n
  • Remove
    plane.removeCheckerboard();\n
"},{"location":"plane/#other-properties_1","title":"Other properties","text":"

See Mesh game object, game object

"},{"location":"plane/#create-mask","title":"Create mask","text":"
var mask = plane.createBitmapMask();\n

See mask

"},{"location":"plane/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"plugin-list/","title":"Plugin list","text":""},{"location":"plugin-list/#list-of-my-plugins","title":"List of my plugins","text":"

Version of phaser3

Please upgrade your phaser3 to version >= 3.80.0.

  1. Achievements: Achievements in a csv table.
  2. Alpha mask image: Load a texture, then apply an alpha mask from another texture.
  3. Anchor: Set size and position based on visible window.
  4. Arcade-TCRP/Player: Run commands on step of Arcade.
  5. Arcade-TCRP/Recorder: Store commands with step of Arcade.
  6. AwaitLoader: Await custom task in preload stage.
  7. Away time: Get time from previous closing application to now.
  8. BBCode-text: Drawing text with BBCode protocol.
  9. Board: Core object of Board system.
  10. Board/Image: Image chess object.
  11. Board/Field of view: Visible testing, to find field of view.
  12. Board/Hexagon map: Create tile positions in hexagon/triangle/parallelogram geometry in hexagon grid.
  13. Board/Match: Get matched chess.
  14. Board/Mini board: Chess Container, to rotate/mirror/drag chess together.
  15. Board/Monopoly: Move through path tiles.
  16. Board/Move To: Move chess towards target position with a steady speed.
  17. Board/Path finder: Find moveable area or moving path.
  18. Board/Shape: Grid (polygon) shape chess object.
  19. Board/Sprite: Sprite chess object.
  20. Board/Tilemap: Create board from tilemap.
  21. Board/Tile texture: Create canvas-texture of tile.
  22. Bounds: Clamp or wrap position of game object inside target bounds.
  23. Bracket parser: A lite-weight bracket parser.
  24. Bracket parser2: A lite-weight bracket parser.
  25. Buff data: Data manager with buffs.
  26. Build arcade object: Create arcade body, and inject arcade object methods.
  27. Bullet: Move game object toward current angle of game object, with a constant speed.
  28. Button: Fires 'click' event when touch releasd after pressed.
  29. Camera controller: Control camera's scroll by pan/cursor-at-bounds(scroll), and zoom by pinch/mouse-wheel.
  30. Canvas: Drawing on canvas.
  31. CanvasInput: An invisible Input DOM element to receive character input and display on DynamicText.
  32. Canvas/Circular progress: Circular progress bar on canvas.
  33. Canvas/Line progress: Horizontal line progress bar filled with gradient color on canvas.
  34. Canvas/Round rectangle: Round rectangle on canvas.
  35. Canvas image data: Get image data from texture, or text object.
  36. Circle mask image: Load a texture, then apply a circle mask.
  37. Click outside: Fires 'clickoutside' event when pointer-down or pointer-up outside of game object.
  38. Clock: A clock to count elapsed time.
  39. Character cache: Generate bitmapfont from text game object, or bbcode text game object.
  40. Color/TintRGB: Attach tintR, tintG, tintB, and tintGray properties to a game object.
  41. Conditions table: Check conditions to find passed tests listed in a csv table.
  42. ContainerLite: Control the position and angle of children game objects.
  43. Containerlite-perspective: Snapshot children of containerlite, to a perspective render texture.
  44. Containerlite-skew: Snapshot children of containerlite, to a skew render texture.
  45. CSV-scenario: Run script in csv format.
  46. CSV-to-hash-table: Hash table indexed by (col-key, row-key) from csv string.
  47. Cursor at bound: Map position pf cursor to cursor key state.
  48. Curve/Spiral: Spiral curve.
  49. Cut Jigsaw Image: Cut image into pieces for jigsaw application.
  50. Drag: Drag game object.
  51. Drag-rotate: Get dragging angle around a specific point.
  52. Drop down: Drop down game object below another target game object.
  53. Dynamic text: Control position, angle of each character drawn on a canvas.
  54. Ease-data: Easing data value of game object's data-manager.
  55. Ease-move: Ease-move game object.
  56. Effect properties: Attach properties to a game object or camera, to add/remove/control builtin preFX or postFX effects.
  57. Eight direction: Move game object by cursor keys, with a constant speed.
  58. Event promise: Return a promise of an event.
  59. Expression parser: Parse expression string into function.
  60. Fade-out-destroy: Fade out game object then destroy it.
  61. Fade-volume: Fade-in/fade-out volume of sound.
  62. File chooser: Create a transparent file chooser button.
  63. File drop zone: Create a div element for dropping file(s).
  64. Firebase/Broadcast: Broadcast real-time messages, using firebase-database.
  65. Firebase/Files: Save JSON data, using firebase-firestore.
  66. Firebase/ID-alias: Map an unique ID to another unique ID, using firebase-firestore.
  67. Firebase/Item-table: 1d/2d/3d table, using firebase-database.
  68. Firebase/Leaderboard: Descending sort scores, using firebase-firestore.
  69. Firebase/Messages: Store messages in firebase-firestore.
  70. Firebase/Online-user-list: Online user list, using firebase-database.
  71. Firebase/Single-room: Chat room, using firebase-database.
  72. Flash: Flashing (set invisible then visible) game object.
  73. Flip: Flipping game object to another face by scaling width/height.
  74. Frame manager: Draw frames on canvas texture, or dynamic texture.
  75. FSM: Finite state machine.
  76. Fuzzy: A wrap of fuzzy logic.
  77. Gashapon: Pick random item from box.
  78. Geom/Hexagon: Hexagon geometry object.
  79. Geom/Rhombus: Rhombus shape and methods.
  80. Gesture/Pan: Get pan events of a game object.
  81. Gesture/Pinch: Get scale factor from 2 dragging touch pointers.
  82. Gesture/Press: Get press events of a game object.
  83. Gesture/Rotate: Get spin angle from 2 dragging touch pointers.
  84. Gesture/Swipe: Get swipe events of a game object.
  85. Gesture/Tap: Get tap/multi-taps events of a game object.
  86. Grid align: Align objects on quadrilateral or hexagon grid.
  87. Grid cut image: Grid cut image texture to frames, then create image game objects from these frames.
  88. Grid table: Viewer of grid table, to manipulate game object of each visible cell.
  89. Group navigator: Navigate between existing game objects, focus on next/previous/next-row/previous row game object.
  90. Hidden input text: An invisible Input DOM element to receive character input and display on text game object.
  91. Image box: Keep aspect ratio of image game object after scale-down resizing.
  92. Input text: Input DOM element.
  93. Interception: Predict the intersection position of two game objects with constant moving speed.
  94. In touching: Fires 'intouch' event every tick when pressing on a game object.
  95. Keys hub: Key object interface mapping from multiple source of key objects.
  96. Layer manager: A container of Layer game objects.
  97. Level counter: Map level value from experience value, by callback or a number array.
  98. Life time: Destroy game object when time-out.
  99. Line: Draw a line with start/end/body textures.
  100. Live2d: Display live2d model.
  101. Loading animation scene: Start loading animation scene, stop this scene when loading complete.
  102. Loading-progress: Pop-up dialog for loading-progress, then scale-down this dialog.
  103. LocalForage/Files: Save JSON data, using localforage.
  104. LocalStorage/Data: Sync data from data manager to local-storage.
  105. LZ-string: Compress string using LZ-based compression algorithm.
  106. Markdown event sheets: Event sheets contains main condition(s) and actions, in simple markdown format (headings, code block).
  107. Modal promise: Modal behavior wrapped into promise.
  108. Mouse-wheel to up/down: Map mouse-wheeling to (up/down) cursor key state.
  109. Mouse-wheel scroller: Emit scroll event when mouse-wheeling.
  110. Move to: Move game object towards target position with a steady speed.
  111. Nine patch: Stretchable image.
  112. Nine patch2: Stretchable image. Has better performance than nine-patch.
  113. Particles-along-bounds: Emit particles along bounds of game object.
  114. Particles/Bitmap-zone: Particles' emitter zone from canvas bitmap of text/canvas game object.
  115. Path follower: Set position of game object on a path.
  116. Perlin: Perlin2/Perlin3 noise and simplex2/simplex3 noise.
  117. Perspective/Card: A container with two perspective-images.
  118. Perspective/Carousel: A container with cards.
  119. Perspective/Image: Image with perspective rotation.
  120. Perspective/ImageCarousel: Display list of images.
  121. Perspective/Render texture: Render texture with perspective rotation.
  122. Perspective/Sprite: Play animation on perspective-image..
  123. PNG appender: Append user data below tail of PNG data, or extract this user data from PNG data.
  124. polar-coordinate: Attach polarOX, polarOY, polarRotation, polarAngle, and polarRadius properties to a game object.
  125. Pop up: Scale up game object.
  126. Quad/Image: Image with 4 or 9 vertex control points.
  127. Quad/Render texture: Render texture with 4 or 9 vertex control points.
  128. Quest: Question manager.
  129. Raycaster: Raycaster between obstacles.
  130. Random place: Place objects randomly inside an area without overlapping.
  131. Real-time timers: Start and counting timer by real-time timestamp.
  132. Repeat Image: Stamp image repeatly on canvas.
  133. Restorable data: Restorable data manager.
  134. RotateTo: Rotate game object towards target position with a steady speed.
  135. Rotate: Rotate game object continually with a steady speed.
  136. Run-commands: Run commands in array.
  137. Scale-down-destroy: Scale down game object then destroy it.
  138. Scale outer: Scroll and zoom camera to make default game window fit the display area, in RESIZE scale mode.
  139. Script-tag loader: Load script tag in preload stage.
  140. Scroller: Drag content. Slow down when dragging released, pull back when out of bounds.
  141. Sequence: Run sequence commands in array.
  142. Shader/Barrel: Barrel post processing filter.
  143. Shader/Color-replace: Replace color post processing filter.
  144. Shader/Cross-stitching: Cross-stitching post processing filter.
  145. Shader/CRT: CRT post processing filter.
  146. Shader/Dissolve: Dissolve transition post processing filter.
  147. Shader/Drop-shadow: Drop-shadow post processing filter.
  148. Shader/Fish-eye: Fish-eye post processing filter.
  149. Shader/Glow-filter: Glow post processing filter.
  150. Shader/Glow-filter: Glow post processing filter, ported from pixi.
  151. Shader/Gray-scale: Gray scale post processing filter.
  152. Shader/Horri-fi: 6-in-1 post processing filter.
  153. Shader/Hsl-adjust: Adjust color in HSL domain, post processing filter.
  154. Shader/Inverse: Inverse color post processing filter.
  155. Shader/Kawaseblur: Kawase-blur post processing filter.
  156. Shader/Outline: Outline post processing filter, ported from pixi.
  157. Shader/Pixelation: Pixelation post processing filter.
  158. Shader/Shockwave: Shockwave post processing filter.
  159. Shader/Split: Split image into 4 parts.
  160. Shader/Swirl: Swirl post processing filter.
  161. Shader/Toonify: Draw outlines and quantize color in HSV domain, post processing filter.
  162. Shader/Warp: Warp post processing filter.
  163. Shake-position: Shake position of game object.
  164. Shape/Checkbox: Checkbox input with drawing checker path animation.
  165. Shape/Circular progress: Circular progress bar shape.
  166. Shape/Cover: Rectangle shape covered full window, and block all touch events.
  167. Shape/Custom progress: Custom progress bar shape.
  168. Shape/Custom shapes: Custom shapes on shape.
  169. Shape/Full window rectangle: Rectangle shape covered full window.
  170. Shape/Line progress: Horizontal line progress bar shape.
  171. Shape/Quad: Quad shape, offsets can be given on four vertices, and additional points can be added on the four sides.
  172. Shape/Round-Rectangle: Round rectangle shape.
  173. Shape/Spinner: Loading animations on shape.
  174. Shape/Toggle-switch: Toggle-switch input.
  175. Shape/Triangle: Trangle shape inside a rectangle bounds.
  176. Shatter/Image: Shatter image to triangle faces.
  177. Shatter/Render texture: Shatter render texture to triangle faces.
  178. Ship: Move game object as a space ship by cursor keys.
  179. Skew/Image: Skewable Image.
  180. Skew/RenderTexture: Skewable render texture.
  181. Slider: Drag thumb on a slider bar.
  182. State manager: Another version of Finite state machine.
  183. Step: Interpolate points between previous position and current position with fixed step length.
  184. Tag-player: Text commands to control sprites, texts, sound effect or backgroun music.
  185. Tag-text: Displays text with multi-color, font face, or font size with tags.
  186. TCRP/Player: Run commands on time.
  187. TCRP/Recorder: Store commands with time.
  188. Text/Edit: Create an input text object above a text object to edit string content.
  189. Text/Typing: Typing text on text object.
  190. Text/Page: Display text page by page on text object.
  191. Text/Translation: Apply translated string (i18next) to text object.
  192. Text/Truncator: Constraints text game object size by truncating text with padding symbol on text object.
  193. Text player: Typing characters on dynamic text, waiting click or key enter, play sound effect or backgroun music.
  194. Touch event stop: Stop touch events propagation.
  195. Touch state: Store current touch input properties.
  196. Transition image: Transit texture to another one.
  197. Transition image pack: Transit texture to another one, with some pre-build effects.
  198. UI/Badge label: A container with badges above a main item.
  199. UI/Buttons: A container with a group of buttons.
  200. UI/Chart: Draw chart on canvas.
  201. UI/Color components: Edit color value by RGB, or HSV input fields.
  202. UI/Color input: Color value input field.
  203. UI/Color picker: Pick color value from H and SV palettes.
  204. UI/Confirm action: Create a modal confirm dialog temporary, invoke callback after clicking button.
  205. UI/Confirm action button: Create a modal confirm dialog temporary, invoke callback after clicking button.
  206. UI/Confrim dialog: Using json style to create confirm dialog.
  207. UI/Dialog: A container with a title, content, buttons and backgrounds.
  208. UI/Drop down list: A label can open a drop-down list panel.
  209. UI/Exp bar: Disply experience bar on NameValueLabel.
  210. UI/File selector button: A transparent file chooser button above a Label.
  211. UI/Fixwidthbuttons: A container with a group of fix-width buttons.
  212. UI/Fixwidthsizer: Layout children game objects into lines.
  213. UI/Folder: A container with a title, foldable child, and background.
  214. UI/Grid buttons: A container with a group of buttons in grids.
  215. UI/Grid sizer: Layout children game objects in grids.
  216. UI/Gird table: A container with a grid table, slider, and scroller.
  217. UI/Holy grail: Layout elements in Holy grail style.
  218. UI/Image input label: A container with a canvas icon, text, and background. Click icon to popup a (image) file chooser dialog, display selected image on canvas.
  219. UI/Knob: A knob button based on circular progress.
  220. UI/Label: A game object container with an icon, text, and background.
  221. UI/Menu: A container with buttons and sub-menu.
  222. UI/Name-input dialog: Enter first name and last name via a dialog.
  223. UI/Name-value label: A container with name text, value text in a row, with a horizontal line progress bar, 1d an icon, background.
  224. UI/Number bar: A container with an icon, slider, text, and background.
  225. UI/Overlap sizer: Layout children game objects overlapped.
  226. UI/Pages: A container with pages, only current page is visible.
  227. UI/Perspective card: A container with front and back faces.
  228. UI/Scroll-able panel: A container with a panel, slider, and scroller.
  229. UI/Scroll bar: A container with slider, two buttons, and background.
  230. UI/Simple drop down list: Using plain object to create drop down list.
  231. UI/Simple label: Using json style to create label.
  232. UI/Simple title label: Using json style to create title label.
  233. UI/Simple text box: Using json style to create text box.
  234. UI/Sizer: Layout children game objects.
  235. UI/Slider: A container with a track, indicator, thumb and background.
  236. UI/Split panels: A container with left(top) panel, right(bottom) panel, splitter, and background. Drag splitter to resize with left(top) panel, right(bottom) panel.
  237. UI/Tab-pages: A container with tabs and pages, only current page is visible.
  238. UI/Tabs: A container with 4 groups of buttons around a center panel.
  239. UI/Text area: A container with a text, slider, and scroller.
  240. UI/Text area input: A container with a canvasInput, and slider.
  241. UI/Text box: A container with an icon, (typing and paging) text, and background.
  242. UI/Title label: A container with title, text in two rows, and an icon, background.
  243. UI/Toast: Show text message for a short while.
  244. UI/Toast queue: Queue messages for a short while.
  245. UI/Trees: A container with trees and leaf-nodes.
  246. UI/Tweaker: Fine-tuning properties of target object.
  247. Unique item list: List of unique items. Support array and set methods.
  248. Viewport-coordinate: Attach vpx, vpy properties to a game object, to set position according to proportion of viewport.
  249. Virtual joystick: Simulate cursor keys according to touch events.
  250. Wait events: Wait fired events or callbacks.
  251. Webfont-loader: Load web font by google webfont loader in preload stage.
  252. XOR: Encrypt or decrypt string by XOR algorithm.
  253. YML-Achievements: Achievements in a YAML table.
  254. YML-Conditions table: Check conditions to find passed tests listed in a YAML table.
  255. Youtube player: Play youtube video on iframe.
"},{"location":"pluginsystem/","title":"Plugin system","text":""},{"location":"pluginsystem/#introduction","title":"Introduction","text":"

Plugin system, built-in system of phaser.

  • Author: Richard Davey
"},{"location":"pluginsystem/#usage","title":"Usage","text":""},{"location":"pluginsystem/#global-plugin","title":"Global plugin","text":""},{"location":"pluginsystem/#load-plugin","title":"Load plugin","text":"
  • Load plugin before any scene start In game configuration
    // import pluginKlass from '...';\nvar config = {\n// ...\nplugins: {\nglobal: [\n{\nkey: key,\nplugin: pluginKlass,\nstart: true\n// mapping: memberName  // member name in each scene instance, optional\n// data: undefined\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • pluginKlass : Class instance
    • start : Whether the plugin should be started automatically.
    • mapping : If this plugin is to be injected into the Scene Systems, this is the property key map used.
    • data : Arbitrary data passed to the plugin's init() method.
  • Load plugin in scene
    scene.load.plugin(key, url, true);\n// scene.load.plugin(key, url, true, mapping);\n
    • url : File url or class instance.
"},{"location":"pluginsystem/#get-instance","title":"Get instance","text":"
var pluginInst = scene.plugins.get(key);\n
"},{"location":"pluginsystem/#scene-plugin","title":"Scene plugin","text":""},{"location":"pluginsystem/#load-plugin_1","title":"Load plugin","text":"
  • Load plugin before any scene start In game configuration
    // import pluginKlass from '...';\nvar config = {\n// ...\nplugins: {\nscene: [\n{\nkey: key,\nplugin: pluginKlass,\nmapping: sceneKey,    // member name in each scene instance\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • pluginKlass : Class instance
  • Load plugin in scene
    scene.load.scenePlugin(key, url, systemKey, sceneKey);\n
    • url : File url or class instance.
"},{"location":"pluginsystem/#get-instance_1","title":"Get instance","text":"
var pluginInst = scene[sceneKey];\n
"},{"location":"pluginsystem/#plugin-cache","title":"Plugin cache","text":"
  • Has custom plugin
    var hasPlugin = Phaser.Plugins.PluginCache.hasCustom(key);\n
"},{"location":"png-appender/","title":"PNG Appender","text":""},{"location":"png-appender/#introduction","title":"Introduction","text":"

Append user data below tail of PNG data, or extract this user data from PNG data.

  • Author: Rex
  • Methods
"},{"location":"png-appender/#live-demos","title":"Live demos","text":"
  • Append-extract
"},{"location":"png-appender/#usage","title":"Usage","text":"

Sample code

"},{"location":"png-appender/#install-plugin","title":"Install plugin","text":""},{"location":"png-appender/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexpngappenderplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexpngappenderplugin.min.js', true);\n
  • Append, or extract data
    var resultBuffer = scene.plugins.get('rexpngappenderplugin').append(pngBuffer, data);\nvar data = scene.plugins.get('rexpngappenderplugin').extract(pngBuffer);\n
"},{"location":"png-appender/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PNGAppenderPlugin from 'phaser3-rex-plugins/plugins/pngappender-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPNGAppender',\nplugin: PNGAppenderPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Append, or extract data
    var resultBuffer = scene.plugins.get('rexPNGAppender').append(pngBuffer, data);\nvar data = scene.plugins.get('rexPNGAppender').extract(pngBuffer);\n
"},{"location":"png-appender/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import PNGAppender from 'phaser3-rex-plugins/plugins/pngappender.js';\n
  • Append, or extract data
    var resultBuffer = PNGAppender.append(pngBuffer, data);\nvar data = PNGAppender.extract(pngBuffer);\n
"},{"location":"png-appender/#append-data","title":"Append data","text":"
var resultBuffer = scene.plugins.get('rexPNGAppender').append(pngBuffer, data);\n
  • pngBuffer : PNG data loaded from binary loader.
  • data : JSON. dictionary, array, string, number, or Uint8Array.
  • resultBuffer : PNG data with custom data (data).
    • Can add to texture cache via scene.load.image(...)
      1. Create blob from resultBuffer : var blob = new Blob([buffer], { type: 'image/png' })
      2. Create object url from blob : var url = window.URL.createObjectURL(blob)
      3. Load texture from object url : scene.load.image(textureKey, url)
      4. Start loader if in create stage of scene : scene.load.start()
    • Can download and display on image viewer as normal PNG file.
"},{"location":"png-appender/#extract-data","title":"Extract data","text":"
var data = scene.plugins.get('rexPNGAppender').extract(pngBuffer);\n
  • pngBuffer : PNG data loaded from binary loader.
  • data : User data.
    • null : This pngBuffer does not have user data.
"},{"location":"point-light/","title":"Point light","text":""},{"location":"point-light/#introduction","title":"Introduction","text":"

A point light with gradient color in a circle.

  • Author: Richard Davey

WebGL only

It only works in WebGL render mode.

"},{"location":"point-light/#usage","title":"Usage","text":""},{"location":"point-light/#add-point-light","title":"Add point light","text":"
var pointLight = scene.add.pointlight(x, y, color, radius, intensity, attenuation);\n
  • x, y : The horizontal/vertical position of this Game Object in the world.
  • color : Color of this light.
  • radius : Radius of this light.
  • intensity : 0~1, intensity of color.
  • attenuation : 0~1, decay intensity along radius.
"},{"location":"point-light/#position","title":"Position","text":"
  • Set
    pointLight.setPosition(x, y);\n
    or
    pointLight.x = x;\npointLight.y = y;\n
  • Get
    var x = pointLight.x;\nvar y = pointLight.y;\n
"},{"location":"point-light/#color","title":"Color","text":"
  • Set
    • Red, green, blue
      pointLight.color.set(red, green, blue);\n
      or
      pointLight.color.r = red;\npointLight.color.g = green;\npointLight.color.b = blue;\n
      • red, green, blue : 0~1.
  • Get
    • Red, green, blue
      var red = pointLight.color.r;\nvar green = pointLight.color.g;\nvar blue = pointLight.color.b;\n
      • red, green, blue : 0~1.
"},{"location":"point-light/#radius","title":"Radius","text":"
  • Set
    pointLight.radius = radius;\n
  • Get
    var radius = pointLight.radius;\n
"},{"location":"point-light/#intensity","title":"Intensity","text":"
  • Set
    pointLight.intensity = intensity;\n
  • Get
    var intensity = pointLight.intensity;\n
"},{"location":"point-light/#attenuation","title":"Attenuation","text":"
  • Set
    pointLight.attenuation = attenuation;\n
  • Get
    var attenuation = pointLight.attenuation;\n
"},{"location":"polar-coordinate/","title":"Polar-coordinate","text":""},{"location":"polar-coordinate/#introduction","title":"Introduction","text":"

Attach polarOX, polarOY, polarRotation, polarAngle, and polarRadius properties to a game object.

  • Author: Rex
  • Method only
"},{"location":"polar-coordinate/#live-demos","title":"Live demos","text":"
  • Circle
  • Spiral
"},{"location":"polar-coordinate/#usage","title":"Usage","text":"

Sample code

"},{"location":"polar-coordinate/#install-plugin","title":"Install plugin","text":""},{"location":"polar-coordinate/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexpolarcoordinateplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexpolarcoordinateplugin.min.js', true);\n
  • Attach polarOX, polarOY, polarRotation, polarAngle, and polarRadius properties.
    scene.plugins.get('rexpolarcoordinateplugin').add(gameObject, ox, oy, rotation, radius);\ngameObject.polarRadius = 200;\ngameObject.polarAngle = -45;\n
"},{"location":"polar-coordinate/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PolarCoordinatePlugin from 'phaser3-rex-plugins/plugins/polarcoordinate-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPolarCoordinate',\nplugin: PolarCoordinatePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Attach polarOX, polarOY, polarRotation, polarAngle, and polarRadius properties.
    scene.plugins.get('rexPolarCoordinate').add(gameObject, ox, oy, rotation, radius);\ngameObject.polarRadius = 200;\ngameObject.polarAngle = -45;\n
"},{"location":"polar-coordinate/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import AddPolarCoordinateProperties from 'phaser3-rex-plugins/plugins/polarcoordinate.js';\n
  • Attach polarOX, polarOY, polarRotation, polarAngle, and polarRadius properties.
    AddPolarCoordinateProperties(gameObject, ox, oy, rotation, radius);\ngameObject.polarOX = 400;\ngameObject.polarOY = 300;\ngameObject.polarRadius = 200;\ngameObject.polarAngle = -45;\n
"},{"location":"polar-coordinate/#attach-properties","title":"Attach properties","text":"
scene.plugins.get('rexPolarCoordinate').add(gameObject, ox, oy, rotation, radius);\ngameObject.polarOX = 400;\ngameObject.polarOY = 300;\ngameObject.polarRadius = 200;\ngameObject.polarAngle = -45;\n
  • ox, oy : Position of origin point.
  • rotation : Polar angle, in radian.
  • radius : Polar radius.
x = ( polarRadius * cos(polarRotation) ) + polarOX\ny = ( polarRadius * sin(polarRotation) ) + polarOY\n
"},{"location":"polar-coordinate/#circle","title":"Circle","text":"
scene.tweens.add({\ntargets: gameObject,\npolarAngle: 360,\nduration: 3000\n})\n
"},{"location":"popup/","title":"Pop up","text":""},{"location":"popup/#introduction","title":"Introduction","text":"

Scale up from 0 to current scale of game object.

  • Author: Rex
  • Method only
"},{"location":"popup/#usage","title":"Usage","text":"

Sample code

"},{"location":"popup/#install-plugin","title":"Install plugin","text":""},{"location":"popup/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexscaleplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexscaleplugin.min.js', true);\n
  • Pop-up object
    scene.plugins.get('rexscaleplugin').popup(gameObject, duration);\n
"},{"location":"popup/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ScalePlugin from 'phaser3-rex-plugins/plugins/scale-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexScale',\nplugin: ScalePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Pop-up object
    scene.plugins.get('rexScale').popup(gameObject, duration);\n
"},{"location":"popup/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import PopUp from 'phaser3-rex-plugins/plugins/popup.js';\n
  • Pop-up object
    PopUp(gameObject, duration);\n
"},{"location":"popup/#pop-up","title":"Pop up","text":"
  • Pop up width and height
    var scale = scene.plugins.get('rexScale').popup(gameObject, duration);\n// var scale = popUp(gameObject, duration, undefined, ease);\n
    • ease : Ease function, default is 'Cubic'.
  • Pop up width only
    var scale = scene.plugins.get('rexScale').popup(gameObject, duration, 'x');\n// var scale = popUp(gameObject, duration, 'x', ease);\n
    • ease : Ease function, default is 'Cubic'.
  • Pop up height only
    var scale = scene.plugins.get('rexScale').popup(gameObject, duration, 'y');\n// var scale = popUp(gameObject, duration, 'y', ease);\n
    • ease : Ease function, default is 'Cubic'.
"},{"location":"popup/#events","title":"Events","text":"

See Events of tween task

  • Scale completes or is stopped.
    scale.on('complete', function(gameObject, scale){\n\n}, scope);\n
"},{"location":"postfx-pipeline/","title":"Post fx pipeline","text":""},{"location":"postfx-pipeline/#introduction","title":"Introduction","text":"

Post fx pipelines for game objects or camera. A game object or a camera can stack many post-fx effect.

  • Author: Richard Davey

WebGL only

All kinds of post fx pipelines only work in WebGL render mode.

"},{"location":"postfx-pipeline/#usage","title":"Usage","text":""},{"location":"postfx-pipeline/#post-fx-pipeline-class","title":"Post fx pipeline class","text":"
class MyPostFxClass extends Phaser.Renderer.WebGL.Pipelines.PostFXPipeline {\nconstructor(game) {\nsuper({\ngame: game,\nrenderTarget: true,\nfragShader: '...',  // GLSL shader\nuniforms: []\n});\n}\n\nonPreRender() {\nthis.set1f('intensity', this._intensity);\n}\n\nonDraw(renderTarget) {\n}\n}\n
"},{"location":"postfx-pipeline/#set-uniform-values","title":"Set uniform values","text":"
  • Property with 1 value
    • Float
      pipelineInstance.set1f(name, value0);\n// pipelineInstance.set1f(name, value0, shader);\n
    • uniform1fv
      pipelineInstance.set1fv(name, value0);\n// pipelineInstance.set1fv(name, value0, shader);\n
    • Int
      pipelineInstance.set1i(name, value0);\n// pipelineInstance.set1i(name, value0, shader);\n
  • Property with 2 values
    • Float
      pipelineInstance.set2f(name, value0, value1);\n// pipelineInstance.set2f(name, value0, value1, shader);\n
    • uniform2fv
      pipelineInstance.set2fv(name, value0, value1);\n// pipelineInstance.set2fv(name, value0, value1, shader);\n
    • Int
      pipelineInstance.set2i(name, value0, value1);\n// pipelineInstance.set2i(name, value0, value1, shader);\n
  • Property with 3 value
    • Float
      pipelineInstance.set3f(name, value0, value1, value2);\n// pipelineInstance.set3f(name, value0, value1, value2, shader);\n
    • uniform3fv
      pipelineInstance.set3fv(name, value0, value1, value2);\n// pipelineInstance.set3fv(name, value0, value1, value2, shader);\n
    • Int
      pipelineInstance.set3i(name, value0, value1, value2);\n// pipelineInstance.set3i(name, value0, value1, value2, shader);\n
  • Property with 4 values
    • Float
      pipelineInstance.set4f(name, value0, value1, value2, value3);\n// pipelineInstance.set4f(name, value0, value1, value2, value3, shader);\n
    • uniform4fv
      pipelineInstance.set4fv(name, value0, value1, value2, value3);\n// pipelineInstance.set4fv(name, value0, value1, value2, value3, shader);\n
    • Int
      pipelineInstance.set4i(name, value0, value1, value2, value3);\n// pipelineInstance.set4i(name, value0, value1, value2, value3, shader);\n
"},{"location":"postfx-pipeline/#onprerender","title":"onPreRender","text":"
  • Set uniform values in onPreRender method.
"},{"location":"postfx-pipeline/#ondraw","title":"onDraw","text":"
  • Ping-pong drawing
    • Variables :
      • renderTarget : Render target, parameter of onDraw method.
      • pipelineInstance.fullFrame1, pipelineInstance.fullFrame2 : Ping-pong render texture.
    • Steps
      1. Copy frame to pipelineInstance.fullFrame1
        pipelineInstance.copyFrame(source, target);\n// pipelineInstance.copyFrame(source, target, brightness, clear, clearAlpha);\n
      2. Set uniform values
      3. Bind and draw on pipelineInstance.fullFrame1, pipelineInstance.fullFrame2.
        pipelineInstance.bindAndDraw(source, target);\n// pipelineInstance.bindAndDraw(source, target, clear, clearAlpha, shader);\n
      4. Draw result back
        pipelineInstance.bindAndDraw(source);\n
"},{"location":"postfx-pipeline/#register-post-fx-pipeline","title":"Register post-fx pipeline","text":"
  • Register post-fx pipeline in game config
    import MyPostFxClass from 'path';\nvar config = {\n// ...\npipeline: [MyPostFxClass]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Or register post-fx pipeline at runtime
    var pipelineManager = scene.sys.renderer.pipelines;\npipelineManager.addPostPipeline(PostFxName, MyPostFxClass);\n
"},{"location":"postfx-pipeline/#apply-effect","title":"Apply effect","text":"

gameObject.setPostPipeline(MyPostFxClass);\n
camera.setPostPipeline(MyPostFxClass);\n

Will create an effect instance then push it into postPipelines list.

"},{"location":"postfx-pipeline/#get-post-fx-pipeline","title":"Get post-fx pipeline","text":"

var pipelineInstance = gameObject.getPostPipeline(MyPostFxClass);\n
var pipelineInstance = camera.getPostPipeline(MyPostFxClass);\n

"},{"location":"postfx-pipeline/#remove-post-fx-pipeline","title":"Remove post-fx pipeline","text":"

gameObject.removePostPipeline(MyPostFxClass);\n
camera.removePostPipeline(MyPostFxClass);\n

"},{"location":"postfx-pipeline/#unregister-post-fx-pipeline","title":"Unregister post-fx pipeline","text":"
var pipelineManager = scene.sys.renderer.pipelines;\npipelineManager.remove(PostFxName);\n
"},{"location":"postfx-pipeline/#color-matrix","title":"Color matrix","text":"

Use color martix to change RGB render result, and more...

class MyPostFxClass extends Phaser.Renderer.WebGL.Pipelines.PostFXPipeline {\nconstructor(game) {\nsuper({\ngame: game,\nrenderTarget: true,\nfragShader: '...',  // GLSL shader\nuniforms: []\n});\n}\n\nonPreRender() {\n// this.set1f('intensity', this._intensity);\nthis.colorMatrix.grayscale(this._intensity);\n}\n\nonDraw(renderTarget) {\nthis.colorMatrix.grayscale(this._intensity);\nthis.drawFrame(renderTarget, this.fullFrame1);\nthis.bindAndDraw(this.fullFrame1);\n}\n}\n
"},{"location":"postfx-pipeline/#color-adjusting","title":"Color adjusting","text":"

Invoke before drawFrame().

  • Grayscale
    this.colorMatrix.grayscale(value);\n// this.colorMatrix.grayscale(value, true); // Cascade\n
    • value : 0 ~ 1
  • Night vision tone
    this.colorMatrix.night(value);\n// this.colorMatrix.night(value, true); // Cascade\n
    • value : 0 ~ 1
  • Sepia tone
    this.colorMatrix.sepia();\n// this.colorMatrix.sepia(true); // Cascade\n
  • Trippy color tone
    this.colorMatrix.lsd();\n// this.colorMatrix.lsd(true); // Cascade\n
  • Brown tone
    this.colorMatrix.brown();\n// this.colorMatrix.brown(true); // Cascade\n
  • Vintage pinhole color effect
    this.colorMatrix.vintagePinhole();\n// this.colorMatrix.vintagePinhole(true); // Cascade\n
  • Kodachrome color effect
    this.colorMatrix.kodachrome();\n// this.colorMatrix.kodachrome(true); // Cascade\n
  • Technicolor color effect
    this.colorMatrix.technicolor();\n// this.colorMatrix.technicolor(true); // Cascade\n
  • Polaroid color effect
    this.colorMatrix.polaroid();\n// this.colorMatrix.polaroid(true); // Cascade\n
  • Brightness
    this.colorMatrix.brightness(value);\n// this.colorMatrix.brightness(value, true); // Cascade\n
    • value : 0(black) ~ 1
  • Saturation
    this.colorMatrix.saturate(value);\n// this.colorMatrix.saturate(value, true); // Cascade\n
    • value : -1 ~ 1
  • Desaturate
    this.colorMatrix.desaturate();\n// this.colorMatrix.desaturate(true); // Cascade\n
  • Hue
    this.colorMatrix.hue(rotation);\n// this.colorMatrix.hue(rotation, true); // Cascade\n
    • rotation : Hue rotation, in degree.
  • Black and white
    this.colorMatrix.blackWhite();\n// this.colorMatrix.blackWhite(true); // Cascade\n
  • Negative
    this.colorMatrix.negative();\n// this.colorMatrix.negative(true); // Cascade\n
  • Contrast
    this.colorMatrix.contrast(value);\n// this.colorMatrix.contrast(value, true); // Cascade\n
  • Desaturate luminance
    this.colorMatrix.desaturateLuminance();\n// this.colorMatrix.desaturateLuminance(true); // Cascade\n
  • Shifts RGB to BGR order
    this.colorMatrix.shiftToBGR();\n// this.colorMatrix.shiftToBGR(true); // Cascade\n
"},{"location":"postfx-pipeline/#draw","title":"Draw","text":"

Invoke under onDraw(renderTarget).

this.drawFrame(renderTarget, this.fullFrame1);\nthis.bindAndDraw(this.fullFrame1);\n
"},{"location":"prefx-pipeline/","title":"Pre fx pipeline","text":""},{"location":"prefx-pipeline/#introduction","title":"Introduction","text":"

Pre fx pipelines for texture-base game objects. A texture-base game object has a pre-fx effect.

  • Author: Richard Davey

WebGL only

All kinds of post fx pipelines only work in WebGL render mode.

"},{"location":"prefx-pipeline/#usage","title":"Usage","text":""},{"location":"prefx-pipeline/#post-fx-pipeline-class","title":"Post fx pipeline class","text":"
class MyPreFxClass extends Phaser.Renderer.WebGL.Pipelines.PreFXPipeline {\nconstructor(game) {\nsuper({\ngame: game,\nfragShader: '...',  // GLSL shader\n});\n}\n\nonDraw(renderTarget) {\nvar sprite = this.tempSprite;\nthis.set1f('intensity', sprite._intensity);\n\nsuper.onDraw(renderTarget);\n}\n}\n
"},{"location":"prefx-pipeline/#set-uniform-values","title":"Set uniform values","text":"
  • Property with 1 value
    • Float
      pipelineInstance.set1f(name, value0);\n// pipelineInstance.set1f(name, value0, shader);\n
    • uniform1fv
      pipelineInstance.set1fv(name, value0);\n// pipelineInstance.set1fv(name, value0, shader);\n
    • Int
      pipelineInstance.set1i(name, value0);\n// pipelineInstance.set1i(name, value0, shader);\n
  • Property with 2 values
    • Float
      pipelineInstance.set2f(name, value0, value1);\n// pipelineInstance.set2f(name, value0, value1, shader);\n
    • uniform2fv
      pipelineInstance.set2fv(name, value0, value1);\n// pipelineInstance.set2fv(name, value0, value1, shader);\n
    • Int
      pipelineInstance.set2i(name, value0, value1);\n// pipelineInstance.set2i(name, value0, value1, shader);\n
  • Property with 3 value
    • Float
      pipelineInstance.set3f(name, value0, value1, value2);\n// pipelineInstance.set3f(name, value0, value1, value2, shader);\n
    • uniform3fv
      pipelineInstance.set3fv(name, value0, value1, value2);\n// pipelineInstance.set3fv(name, value0, value1, value2, shader);\n
    • Int
      pipelineInstance.set3i(name, value0, value1, value2);\n// pipelineInstance.set3i(name, value0, value1, value2, shader);\n
  • Property with 4 values
    • Float
      pipelineInstance.set4f(name, value0, value1, value2, value3);\n// pipelineInstance.set4f(name, value0, value1, value2, value3, shader);\n
    • uniform4fv
      pipelineInstance.set4fv(name, value0, value1, value2, value3);\n// pipelineInstance.set4fv(name, value0, value1, value2, value3, shader);\n
    • Int
      pipelineInstance.set4i(name, value0, value1, value2, value3);\n// pipelineInstance.set4i(name, value0, value1, value2, value3, shader);\n
"},{"location":"prefx-pipeline/#ondraw","title":"onDraw","text":"
  • Set uniform values in onDraw method.
"},{"location":"prefx-pipeline/#add-pre-fx-pipeline-instance","title":"Add pre-fx pipeline instance","text":"
var pipelineManager = scene.sys.renderer.pipelines;\nvar pipelineInstance = pipelineManager.add(PreFxName, new MyPreFxClass(scene.game));\n
"},{"location":"prefx-pipeline/#apply-effect","title":"Apply effect","text":"
gameObject.setPipeline(pipelineInstance);\n

Will replace current effect instance.

"},{"location":"prefx-pipeline/#get-pre-fx-pipeline","title":"Get pre-fx pipeline","text":"
var pipelineInstance = gameObject.pipeline;\n
"},{"location":"prefx-pipeline/#reset-to-default-effect","title":"Reset to default effect","text":"
gameObject.resetPipeline();\n
"},{"location":"prefx-pipeline/#unregister-pre-fx-pipeline","title":"Unregister pre-fx pipeline","text":"
var pipelineManager = scene.sys.renderer.pipelines;\npipelineManager.remove(PreFxName);\n
"},{"location":"quad-image/","title":"Image","text":""},{"location":"quad-image/#introduction","title":"Introduction","text":"

Image with 4 or 9 vertex control points.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"quad-image/#live-demos","title":"Live demos","text":"
  • Quad image
  • Nine points
"},{"location":"quad-image/#usage","title":"Usage","text":"

Sample code

"},{"location":"quad-image/#install-plugin","title":"Install plugin","text":""},{"location":"quad-image/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquadimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquadimageplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexQuadImage(x, y, texture, frame, config);\n
"},{"location":"quad-image/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuadImagePlugin from 'phaser3-rex-plugins/plugins/quadimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuadImagePlugin',\nplugin: QuadImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexQuadImage(x, y, texture, frame, config);\n
"},{"location":"quad-image/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { QuadImage } from 'phaser3-rex-plugins/plugins/quadimage.js';\n
  • Add image object
    var image = new QuadImage(scene, x, y, texture, frame, config);\nscene.add.existing(image);\n
"},{"location":"quad-image/#create-instance","title":"Create instance","text":"
var image = scene.add.rexQuadImage(x, y, texture, frame, {\n// ninePointMode: false,\n});\n

or

var image = scene.add.rexQuadImage({\n// x: 0,\n// y: 0,\nkey,\n// frame: null,\n// ninePointMode: false,\n// rtl: false\n});\n
  • ninePointMode :
    • true : Add 9 vertex control points.
    • false : Add 4 vertex control points. Default behavior.
  • rtl : Diagonal direction in 4 vertices mode.
    • true : Diagonal from right to left
    • false : Diagonal from left to right. Default behavior.

Add quadimage from JSON

var quadimage = scene.make.rexQuadImage({\nx: 0,\ny: 0,\n\nkey: null,\nframe: null,\n\n// ninePointMode: false,\n// rtl: false\n\nadd: true\n});\n
"},{"location":"quad-image/#custom-class","title":"Custom class","text":"
  • Define class
    class MyQuadImage extends QuadImage {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyQuadImage(scene, x, y, texture, frame, config);\n
"},{"location":"quad-image/#vertex-control-points","title":"Vertex control points","text":"
  • Array of vertex control points
    var controlPoints = image.controlPoints;\n
    • 4, or 9 vertex control points
  • 4 vertex control points
    var topLeftPoint = image.topLeft;         // image.controlPoints[0]\nvar topRightPoint = image.topRight;       // image.controlPoints[1]\nvar bottomLeftPoint = image.bottomLeft;   // image.controlPoints[2]\nvar bottomRightPoint = image.bottomRight; // image.controlPoints[3]\n
  • 9 vertex control points
    var topLeft = image.topLeft;               // image.controlPoints[0]\nvar topCenter = image.topCenter;           // image.controlPoints[1]\nvar topRight = image.topRight;             // image.controlPoints[2]\nvar centerLeft = image.centerLeft;         // image.controlPoints[3]\nvar center = image.center;                 // image.controlPoints[4]\nvar centerRight = image.centerRight;       // image.controlPoints[5]\nvar bottomLeft = image.bottomLeft;         // image.controlPoints[6]\nvar bottomCenter = image.bottomCenter;     // image.controlPoints[7]\nvar bottomRight = image.bottomRight;       // image.controlPoints[8]\n
"},{"location":"quad-image/#position","title":"Position","text":"
  • Get
    var worldXY = controlPoint.getWorldXY();\nvar x = worldXY.x;\nvar y = worldXY.y;\n
    or
    var x = controlPoint.x;\nvar y = controlPoint.y;\n
  • Set
    controlPoint.setPosition(x, y);\n// controlPoint.setWorldXY(x, y);\n
    or
    controlPoint.x = x;\ncontrolPoint.y = y;\n
"},{"location":"quad-image/#tint-color","title":"Tint color","text":"
  • Get
    var color = image.tint;\n
  • Set
    image.tint = color;\n
    or
    image.setTint(color);\n
"},{"location":"quad-image/#other-properties","title":"Other properties","text":"

See Mesh game object, game object

"},{"location":"quad-image/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"quad-image/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"quad-rendertexture/","title":"Render texture","text":""},{"location":"quad-rendertexture/#introduction","title":"Introduction","text":"

Render texture with 4 or 9 vertex control points.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"quad-rendertexture/#live-demos","title":"Live demos","text":"
  • RenderTexture
"},{"location":"quad-rendertexture/#usage","title":"Usage","text":"

Sample code

"},{"location":"quad-rendertexture/#install-plugin","title":"Install plugin","text":""},{"location":"quad-rendertexture/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquadimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquadimageplugin.min.js', true);\n
  • Add render texture object
    var image = scene.add.rexQuadRenderTexture(x, y, width, height, config);\n
"},{"location":"quad-rendertexture/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuadImagePlugin from 'phaser3-rex-plugins/plugins/quadimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuadImagePlugin',\nplugin: QuadImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add render texture object
    var image = scene.add.rexQuadRenderTexturege(x, y, width, height, config);\n
"},{"location":"quad-rendertexture/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { QuadRenderTexture } from 'phaser3-rex-plugins/plugins/quadimage.js';\n
  • Add render texture object
    var image = new QuadRenderTexture(scene, x, y, width, height, config);\nscene.add.existing(image);\n
"},{"location":"quad-rendertexture/#create-instance","title":"Create instance","text":"
var image = scene.add.rexQuadRenderTexturege(x, y, width, height, {\n// hideCCW: true,\n// ninePointMode: false,\n});\n

or

var image = scene.add.rexQuadRenderTexturege({\n// x: 0,\n// y: 0,\n// width: 32,\n// height: 32,\n// hideCCW: true,\n// ninePointMode: false,\n});\n
  • ninePointMode :
    • true : Add 9 vertex control points.
    • false : Add 4 vertex control points. Default behavior.

Add prespective render texture from JSON

var image = scene.make.rexQuadRenderTexturege({\nx: 0,\ny: 0,    width: 32,\nheight: 32,\n\n// hideCCW: false,\n// ninePointMode: false,\n\nadd: true\n});\n
"},{"location":"quad-rendertexture/#custom-class","title":"Custom class","text":"
  • Define class
    class MyQuadRenderTexturege extends QuadRenderTexturege {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyQuadRenderTexturege(scene, x, y, width, height, config);\n
"},{"location":"quad-rendertexture/#internal-render-texture","title":"Internal render texture","text":"
var rt = image.rt;\n
  • rt : Render texture
"},{"location":"quad-rendertexture/#paste-texture","title":"Paste texture","text":"
  • Paste game object
    image.rt.draw(gameObject, x, y);\n// image.rt.draw(gameObject, x, y, alpha, tint);\n
  • gameObject : a game object, or an array of game objects
  • Paste game objects in a group
    image.rt.draw(group, x, y);\n// image.rt.draw(group, x, y, alpha, tint);\n
  • Paste game objects in a scene
    image.rt.draw(scene.children, x, y);\n// image.rt.draw(scene.children, x, y, alpha, tint);\n
  • Paste texture
    image.rt.draw(key, x, y);\n// image.rt.draw(key, x, y, alpha, tint);\n
    or
    image.rt.drawFrame(key, frame, x, y);\n// image.rt.drawFrame(key, frame, x, y, alpha, tint);\n
    • key : The key of the texture to be used, as stored in the Texture Manager.
  • Snapshop game objects
    image.snapshot(gameObjects);\n
    • gameObjects : Array of game objects.
"},{"location":"quad-rendertexture/#erase","title":"Erase","text":"
image.rt.erase(gameObject, x, y);\n
  • gameObject : a game object, or an array of game objects
"},{"location":"quad-rendertexture/#clear","title":"Clear","text":"
image.rt.clear();\n
"},{"location":"quad-rendertexture/#fill","title":"Fill","text":"
image.rt.fill(rgb, alpha);\n// image.rt.fill(rgb, alpha, x, y, width, height);\n
"},{"location":"quad-rendertexture/#other-properties","title":"Other properties","text":"

See Quad image game object, Mesh game object, game object

"},{"location":"quad-rendertexture/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"quad-rendertexture/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"quest/","title":"Quest","text":""},{"location":"quest/#introduction","title":"Introduction","text":"

Question manager.

  • Author: Rex
  • Member of scene, or game object
"},{"location":"quest/#live-demos","title":"Live demos","text":"
  • (CSV) Branch
  • (YAML) Branch
  • Shuffle
"},{"location":"quest/#usage","title":"Usage","text":"

Sample code

"},{"location":"quest/#install-plugin","title":"Install plugin","text":""},{"location":"quest/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquestplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquestplugin.min.js', true);\n
  • Add quest-manager object
    var questionManager = scene.plugins.get('rexquestplugin').add(config);\n
"},{"location":"quest/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuestPlugin from 'phaser3-rex-plugins/plugins/quest-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuest',\nplugin: QuestPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add quest-manager object
    var questionManager = scene.plugins.get('rexQuest').add(config);\n
"},{"location":"quest/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Quest from 'phaser3-rex-plugins/plugins/quest.js';\n
  • Add quest-manager object
    var questionManager = new Quest(config);\n
"},{"location":"quest/#question-manager","title":"Question manager","text":""},{"location":"quest/#create-question-manager-instance","title":"Create question manager instance","text":"
var questionManager = scene.plugins.get('rexQuest').add({\nquestions: undefined,\n// format: undefined,\n// delimiter: ',',\n// types: {\n//     question: 'q',\n//     option: '',\n// },\n// convert: true,\n\nquest: undefined,\n// quest: {\n//     shuffleQuestions: false,\n//     shuffleOptions: false,\n// }\n});\n
  • format : Input data (parameter question) format.
    • 'csv' : Input data is a csv string
    • 'yaml' : Input data is a yaml string represented multiple documents, or an array of yaml string for each document.
    • 'json' : Input data is a json string.
    • undefined : Input data is a plain array of questions, don' parse it.
  • questions : Input data of questions.
    • A plain array of questions. Parsing result of other input formats.
      [\n{\nkey: q0,\nparam0: value0,\nparam1: value1,\nparam2: value2,\noptions: [\n{\nkey: o0,\nparam0: value0,\nparam1: value1,\n// ...\n},\n{\nkey: o1,\nparam0: value0,\nparam1: value1,\n// ...\n}\n]\n},\n{\nkey: q1,\nparam0: value0,\nparam1: value1,\nparam2: value2,\noptions: [\n{\nkey: o0,\nparam0: value0,\nparam1: value1,\n// ...\n},\n{\nkey: o1,\nparam0: value0,\nparam1: value1,\n// ...\n}\n]\n},\n]\n
      • Question object : {key, options, param, ...}
        • key : An unique key string. Create a key string '_' + serialNumber if not given.
        • options : An array of option objects.
        • Other key-value parameters.
      • Option object : {key, param, ...}
        • key : An unique key string. Create a key string '_' + serialNumber if not given.
        • Other key-value parameters.
    • A yaml string represented multiple documents, will parse it to array of questions.
      key: q0\nparam0: value0\nparam1: value1\noptions:\n- key: o0\nparam0: value0\nparam1: value1\n- key: o1\nparam0: value0\nparam1: value1\n---\nkey: q1\nparam0: value0\nparam1: value1\noptions:\n- key: o0\nparam0: value0\nparam1: value1\n- key: o1\nparam0: value0\nparam1: value1\n
    • An array of yaml strings for each document, will parse them to array of questions.
    • A csv string, will parse it to array of questions.
      type,key,param0,param1,...\nq,q0,value0,value1,...\n,o0,value0,value1,...\n,o1,value0,value1,...\nq,q1,value0,value1,...\n,o0,value0,value1,...\n,o1,value0,value1,...\n
      • Fields in first row
        • type : Type of this row. These values can be redefined via types in configuration object.
        • q : A row of question object.
        • Empty string : A row of option object belong a question object.
        • key : Unique key string. Create a key string '_' + serialNumber if this field does not exist.
        • Other fields.
    • A json string, will parse it to array of questions.
  • delimiter : Delimiter of csv string. Default value is ','
  • types : Define value of row type.
    • types.question : Define value of question row. Default value is q.
    • types.option : Define value of option row. Default value is '' (empty string).
  • convert : Convert string values to other types.
    • Default type converting : Convert string to number, boolean, null, or string
      • '0', '1', ... (number string) -> number
      • 'true', or 'false' -> true or false
      • '' (empty string) -> null
      • Others : string.
    • Set false to ignore types converting, i.e. all values are string.
    • A custom type converting function :
      function(stringValue, key) {\n// return value;\n}\n
  • quest : Create a private quest task object.
    • undefined : Don't create a private quest task object.
    • true : Create a private quest task object with default configuration.
    • Configuration of quest task :
      • quest.shuffleQuestions : Set true to shuffle questions.
      • quest.shuffleOptions : Set true to shuffle options.
"},{"location":"quest/#add-questions","title":"Add questions","text":"
questionManager.add(questions, config);\n
  • questions : An array of question objects, or a csv string. See questions section in Create question manager instance section.
  • config :
    • delimiter : Delimiter of csv string. Default value is ','
    • types : Define value of row type.
      • types.question : Define value of question row. Default value is q.
      • types.option : Define value of option row. Default value is '' (empty string).
    • convert : Convert string values to other types.
      • Default type converting : Convert string to number, boolean, null, or string
        • '0', '1', ... (number string) -> number
        • 'true', or 'false' -> true or false
        • '' (empty string) -> null
        • Others : string.
      • Set false to ignore types converting, i.e. all values are string.
      • A custom type converting function :
        function(stringValue, key) {\n// return value;\n}\n
"},{"location":"quest/#remove-question","title":"Remove question","text":"
  • Remove a question object
    questionManager.remove(key);\n
    • key : An unique key string.
  • Remove all question objects
    questionManager.removeAll();\n
"},{"location":"quest/#get-question","title":"Get question","text":"
  • Get a question object
    var question = questionManager.get(key);\n
  • Get all keys of question objects
    var questionKeys = questionManager.getKeys();\n// var out = questionManager.getKeys(out);\n
    • questionKeys : Array of question key string.
"},{"location":"quest/#question-is-existed","title":"Question is existed","text":"
var isExisted = questionManager.has(key);\n
"},{"location":"quest/#array-of-questions","title":"Array of questions","text":"
var questions = questionManager.questions;\n

Rearrange items of this questions array to reorder questions in quest task.

"},{"location":"quest/#get-option","title":"Get option","text":"
var option = questionManager.getOption(question, optionKey);\n
  • question : A question object, or a question key string.
  • optionKey : A option key string.
"},{"location":"quest/#private-quest-task","title":"Private quest task","text":""},{"location":"quest/#create-private-quest-task","title":"Create private quest task","text":"

Each question manager can hava a private quest task object, created when creating question manager, or

questionManager.startQuest(config);\n
  • config :
    • shuffleQuestions : Set true to shuffle questions.
    • shuffleOptions : Set true to shuffle options.
"},{"location":"quest/#get-next-question-object","title":"Get next question object","text":"
  • Get next question object
    var question = questionManager.getNextQuestion();\n
  • Get next question object via question key
    var question = questionManager.getNextQuestion(questionKey);\n
"},{"location":"quest/#event","title":"Event","text":"
  • Fire 'quest' when calling questionManager.getNextQuestion()
    questionManager.on('quest', function(question, questionManager, quest){\n// questionManager.getNextQuestion();\n})\n
    • question : Question object.
      • question.options : Option objects of this question.
    • questionManager : Question manager.
    • quest : Quest task.
"},{"location":"quest/#is-last-question","title":"Is last question","text":"
var isLast = questionManager.isLastQuestion();\n
"},{"location":"quest/#restart-quest-task","title":"Restart quest task","text":"
questionManager.restartQuest();\n
"},{"location":"quest/#private-data","title":"Private data","text":"
  • Get data
    var value = questionManager.getData(key, defaultValue);\n
  • Get all data
    var data = questionManager.getData();\n
  • Set value
    questionManager.setData(key, value);\n
  • Increase value
    questionManager.incData(key, inc, defaultValue);\n
  • Multiple value
    questionManager.mulData(key, mul, defaultValue);\n
  • Clear all data
    questionManager.clearData();\n
"},{"location":"quest/#quest-task","title":"Quest task","text":"

Create new quest task if user needs more then 1 quest task.

"},{"location":"quest/#create-quest-task","title":"Create quest task","text":"
var quest = questionManager.newQuest(config);\n
  • config :
    • shuffleQuestions : Set true to shuffle questions.
    • shuffleOptions : Set true to shuffle options.
"},{"location":"quest/#get-next-question-object_1","title":"Get next question object","text":"
  • Get next question object
    var question = quest.getNextQuestion();\n
  • Get next question object via question key
    var question = quest.getNextQuestion(questionKey);\n
"},{"location":"quest/#event_1","title":"Event","text":"
  • Fire 'quest' when calling questionManager.getNextQuestion()
    quest.on('quest', function(question, questionManager, quest){\n// questionManager.getNextQuestion();\n})\n
    • question : Question object.
      • question.options : Option objects of this question.
    • questionManager : Question manager.
    • quest : Quest task.
"},{"location":"quest/#is-last-question_1","title":"Is last question","text":"
var isLast = quest.isLastQuestion();\n
"},{"location":"quest/#restart-quest-task_1","title":"Restart quest task","text":"
quest.start();\n
"},{"location":"quest/#private-data_1","title":"Private data","text":"
  • Get data
    var value = quest.getData(key, defaultValue);\n
  • Get all data
    var data = quest.getData();\n
  • Set value
    quest.setData(key, value);\n
  • Increase value
    quest.incData(key, inc, defaultValue);\n
  • Multiple value
    quest.mulData(key, inc, defaultValue);\n
  • Clear all data
    quest.clearData();\n
"},{"location":"quest/#get-option_1","title":"Get option","text":"
var option = quest.getOption(question, optionKey);\n
  • question : A question object, or a question key string, or undefined to get current question object.
  • optionKey : A option key string.
"},{"location":"random-data-generator/","title":"Random data generator","text":""},{"location":"random-data-generator/#introduction","title":"Introduction","text":"

Get random value from a random generator, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"random-data-generator/#usage","title":"Usage","text":""},{"location":"random-data-generator/#random-data-generator","title":"Random data generator","text":"
  • Pre-defined random data generator
    var rnd = Phaser.Math.RND;\n
  • New random generator
    var rnd = new Phaser.Math.RandomDataGenerator(seed);\n
"},{"location":"random-data-generator/#set-seed","title":"Set seed","text":"
  • Set seed in game config for pre-defined random data generator
    var config = {\n// ...\nseed: seed,\n// ...\n}\nvar game = new Phaser.Game(config);\n
    • seed :
      • An array of string, like [(Date.now() * Math.random()).toString()]
  • Set seed
    rnd.init(seed);\n
    • seed : A string or an array of string.
"},{"location":"random-data-generator/#get-random-value","title":"Get random value","text":"
  • Random real number between 0 and 1.
    var value = rnd.frac();\n
  • Random integer between 0 and 2^32.
    var value = rnd.integer();\n
  • Random real number between 0 and 2^32.
    var value = rnd.real();\n
  • Random integer between and including min and max.
    var value = rnd.between(min, max);\n// var value = rnd.integerInRange(min, max);\n
  • Random real number between min and max.
    var value = rnd.realInRange(min, max);\n
  • Random real number between -1 and 1.
    var value = rnd.normal();\n
  • Random angle between -180 and 180.
    var angle = rnd.angle();\n
  • Random rotation in radians, between -3.141 and 3.141.
    var angle = rnd.rotation();\n
  • Random timestamp between min and max.
    var timestamp = rnd.timestamp(min, max);\n
    • min : Default value is the beginning of 2000.
    • max : Default value is the end of 2020.
  • UUID
    var uuid = rnd.uuid();\n
  • Random sign value
    var sign = rnd.sign();\n
    • sign : -1 or 1
"},{"location":"random-data-generator/#get-random-item","title":"Get random item","text":"
  • Random element from within the given array.
    var item = rnd.pick(arr);\n
  • Random element from within the given array, favoring the earlier entries.
    var item = rnd.weightedPick(arr);\n
"},{"location":"random-data-generator/#shuffle-array","title":"Shuffle array","text":"
var arr = rnd.shuffle(arr);\n
"},{"location":"random/","title":"Random number","text":""},{"location":"random/#introduction","title":"Introduction","text":"

Get random value, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"random/#usage","title":"Usage","text":""},{"location":"random/#get-random-value-between-min-max","title":"Get random value between (min, max)","text":"
  • Random integer
    var value = Phaser.Math.Between(min, max);\n
  • Random floating point number
    var value = Phaser.Math.FloatBetween(min, max);\n
"},{"location":"random/#get-random-vector","title":"Get random vector","text":"
  • 2D vector
    var vec = Phaser.Math.RandomXY(vec);    // return vec {x, y}\n// var vec = Phaser.Math.RandomXY(vec, scale);\n
  • 3D vector
    var vec = Phaser.Math.RandomXYZ(vec);    // return vec {x, y, z}\n// var vec = Phaser.Math.RandomXYZ(vec, scale);\n
  • 4D vector
    var vec = Phaser.Math.RandomXYZW(vec);    // return vec {x, y, z, w}\n// var vec = Phaser.Math.RandomXYZW(vec, scale);\n
"},{"location":"randomplace/","title":"Random place","text":""},{"location":"randomplace/#introduction","title":"Introduction","text":"

Place objects randomly inside an area without overlapping.

  • Author: Rex
  • Methods
"},{"location":"randomplace/#live-demos","title":"Live demos","text":"
  • Random place
"},{"location":"randomplace/#usage","title":"Usage","text":"

Sample code

"},{"location":"randomplace/#install-plugin","title":"Install plugin","text":""},{"location":"randomplace/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrandomplaceplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrandomplaceplugin.min.js', true);\n
  • Random place objects
    scene.plugins.get('rexrandomplaceplugin').randomPlace(gameObjects, config);\n
"},{"location":"randomplace/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RandomPlacePlugin from 'phaser3-rex-plugins/plugins/randomplace-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRandomPlace',\nplugin: RandomPlacePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Random place objects
    scene.plugins.get('rexRandomPlace').randomPlace(gameObjects, config);\n
"},{"location":"randomplace/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RandomPlace from 'phaser3-rex-plugins/plugins/randomplace.js';\n
  • Random place objects
    RandomPlace(gameObjects, config);\n
"},{"location":"randomplace/#random-place","title":"Random place","text":"
scene.plugins.get('rexRandomPlace').randomPlace(gameObjects, {\nradius: radius,\n\ngetPositionCallback: undefined,\narea: areaGeomObject,\n});\n
  • gameObjects : An array of gameObjects. Each item can be
    • A game objects.
    • A plain object contains
      {\ngameObject: gameObject,\nradius: radius,\n}\n
      • radius : Collision radius of this game object.
  • radius : Default collision radius of each game object.
  • getPositionCallback : A callback to get a random position.
    • undefined : Use area.getRandomPoint(out) as callback.
    • A function object :
      function(out) {\nout.x = 0;\nout.y = 0;\n}\n
  • area : A geom object, which has getRandomPoint method.
    • A circle : new Phaser.Geom.Circle(x, y, radius)
    • A rectangle : new Phaser.Geom.Rectangle(x, y, width, height)
    • A triangle : new Phaser.Geom.Triangle(x1, y1, x2, y2, x3, y3)
    • An ellipse : new Phaser.Geom.Ellipse(x, y, width, height)
    • undefined : A rectangle (0, 0, gameWidth, gameHeight)
"},{"location":"raycaster/","title":"Raycaster","text":""},{"location":"raycaster/#introduction","title":"Introduction","text":"

Raycaster between obstacles.

  • Author: Rex
  • Member of scene
"},{"location":"raycaster/#live-demos","title":"Live demos","text":"
  • Reflaction
"},{"location":"raycaster/#usage","title":"Usage","text":"

Sample code

"},{"location":"raycaster/#install-plugin","title":"Install plugin","text":""},{"location":"raycaster/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexraycasterplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexraycasterplugin.min.js', true);\n
  • Add raycaster object
    var raycaster = scene.plugins.get('rexraycasterplugin').add(config);\n
"},{"location":"raycaster/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RaycasterPlugin from 'phaser3-rex-plugins/plugins/raycaster-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRaycaster',\nplugin: RaycasterPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add raycaster object
    var raycaster = scene.plugins.get('rexRaycaster').add(config);\n
"},{"location":"raycaster/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Raycaster from 'phaser3-rex-plugins/plugins/raycaster.js';\n
  • Add raycaster object
    var raycaster = new Raycaster(config);\n
"},{"location":"raycaster/#create-instance","title":"Create instance","text":"
var raycaster = scene.plugins.get('rexRaycaster').add({\n// maxRayLength: 10000\n});\n
  • maxRayLength : Max length of ray.
"},{"location":"raycaster/#obstacle","title":"Obstacle","text":""},{"location":"raycaster/#add","title":"Add","text":"
raycaster.addObstacle(gameObject);\n// raycaster.addObstacle(gameObject, polygon);\n
  • polygon : A polygon.
    • undefined : Created polygon from 4 vertics of game object.

or

raycaster.addObstacle(gameObjects);\n
  • gameObjects : Array of game object.
"},{"location":"raycaster/#remove","title":"Remove","text":"
raycaster.removeObstacle(gameObject);\n
  • gameObject : A game object, or an array of game objects.
"},{"location":"raycaster/#clear","title":"Clear","text":"
raycaster.clearObstacle();\n
"},{"location":"raycaster/#update-shape","title":"Update shape","text":"
raycaster.updateObstacle(gameObject);\n// raycaster.updateObstacle(gameObject, polygon);\n
  • polygon : A polygon.
    • undefined : Created polygon from 4 vertics of game object.
"},{"location":"raycaster/#raycaster","title":"Raycaster","text":"
var result = raycaster.rayToward(x, y, angle);\n
  • x, y : Emit ray from world-position.
  • angle : Emit ray toward to angle, in radian.
  • result :
    • false : Ray dose not hit any game object.
    • An object : Hit to a game object.
      {\ngameObject,\npolygon,\nsegment,\nx, y,\nreflectAngle\n}\n
      • gameObject : Hitting game object.
      • polygon : Polygon of hitting game object.
      • segment : Segment(line) of hitting polygon.
      • x, y : World position of hitting
      • reflectAngle : Reflect angle, in radian.

Reflection

Use result.x, result.y, result.reflectAngle for next reflection ray.

raycaster.rayToward(result.x, result.y, result.reflectAngle)\n

"},{"location":"realtimetimers/","title":"Real time timers","text":""},{"location":"realtimetimers/#introduction","title":"Introduction","text":"

Start and counting timer by real-time timestamp.

Note

Not support pause, or timescale features.

  • Author: Rex
  • Member of scene, or game object
"},{"location":"realtimetimers/#live-demos","title":"Live demos","text":"
  • Progress
"},{"location":"realtimetimers/#usage","title":"Usage","text":"

Sample code

"},{"location":"realtimetimers/#install-plugin","title":"Install plugin","text":""},{"location":"realtimetimers/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrealtimetimersplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrealtimetimersplugin.min.js', true);\n
  • Add real-time timers object
    var realTimeTimers = scene.plugins.get('rexrealtimetimersplugin').add(config);\n
"},{"location":"realtimetimers/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RealTimeTimersPlugin from 'phaser3-rex-plugins/plugins/realtimetimers-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRealTimeTimers',\nplugin: RealTimeTimersPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add real-time timers object
    var realTimeTimers = scene.plugins.get('rexRealTimeTimers').add(config);\n
"},{"location":"realtimetimers/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RealTimeTimers from 'phaser3-rex-plugins/plugins/realtimetimers.js';\n
  • Add real-time timers object
    var realTimeTimers = new RealTimeTimers(config);\n
"},{"location":"realtimetimers/#create-instance","title":"Create instance","text":"
var realTimeTimers = scene.plugins.get('rexRealTimeTimers').add({\n// startTimestamp: new Date().getTime(),\n// getTimestampCallback: functio() { return timestamp; }\n});\n
  • getTimestampCallback : Custom callback of get current timestamp, optional.
    • Default behavior is getting current timestamp from system.
  • startTimestamp : Start time, optional. Use this start-timestamp if getTimestampCallback is not given.
    • Default value is current timestamp new Date().getTime().
"},{"location":"realtimetimers/#set-start-timestamp","title":"Set start timestamp","text":"

Start-timestamp is set when creating this real-time timers object.

User still can change Start-timestamp by

realTimeTimers.setStartTimestamp(timestamp);\n

This changing won't affect existed timers.

"},{"location":"realtimetimers/#add-a-timer","title":"Add a timer","text":"
realTimeTimers.addTimer(name, period);\n// realTimeTimers.addTimer(name, period, data);\n// realTimeTimers.addTimer(name, period, data, currentTimestamp);\n
  • name : Any name string of this timer.
  • period : Will expire after period time, in millisecond.
  • data : Any kind of custom data.
  • currentTimestamp : Start this time in current time, optional.
    • undefined : Get current timestamp from getTimestampCallback callback.

or

realTimeTimers.addTimer(name, {\nday: dayCount,        // d: dayCount,\nhour: hourCount,      // h: hourCount,\nminute: minuteCount,  // m: minuteCount,\nsecond: secondCount,  // s: secondCount,\n}, data, currentTimestamp);\n
  • Sum period by
    • day, or d : Day count
    • hour, or h : Hour count
    • minute, or m : Minute count
    • second, or s : Second count
"},{"location":"realtimetimers/#increase-period","title":"Increase period","text":"
realTimeTimers.incTimerPeriod(name, period);\n
  • name : Any name string of this timer.
  • period : Will expire after period time, in millisecond.

or

realTimeTimers.incTimerPeriod(name, {\nday: dayCount,        // d: dayCount,\nhour: hourCount,      // h: hourCount,\nminute: minuteCount,  // m: minuteCount,\nsecond: secondCount,  // s: secondCount,\n});\n

Will trigger 'update' event.

"},{"location":"realtimetimers/#expire-timers","title":"Expire timers","text":"
  • Get expired timers
    var timers = realTimeTimers.getExpiredTimers();\n// var timers = realTimeTimers.getExpiredTimers(currentTimestamp);\n
    • timers : Array of expired timers. Each timer include these properties -
      {\nname: name,\nstart: timestamp,\nperiod: time\n}\n
    • currentTimestamp : Start this time in current time, optional.
      • undefined : Get current timestamp from getTimestampCallback callback.
  • Pop(get and remove) expired timers
    var timers = realTimeTimers.popExpiredTimers();\n// var timers = realTimeTimers.popExpiredTimers(currentTimestamp);\n
    • currentTimestamp : Start this time in current time, optional.
      • undefined : Get current timestamp from getTimestampCallback callback.
  • Get progress of timer
    var result = realTimeTimers.getTimersProgress()\n// var result = realTimeTimers.getTimersProgress(currentTimestamp);\n
    • currentTimestamp : Start this time in current time, optional.
      • undefined : Get current timestamp from getTimestampCallback callback.
    • result : Array of timer's progress. Include these properties -
      {\nname: name,\nperiod: time,\nelapsed: time,\nprogress: t    // elapsed/period\ntimer: timerObject\n}\n
      • timer : Timer object, can remove this timer object by
        realTimeTimers.removeTimers(timer);\n
"},{"location":"realtimetimers/#get-timers","title":"Get timers","text":"
  • Get last added timer
    var timer = realtimetimers.lastTimer;\n
  • Get all timers
    var timers = realtimetimers.getTimers();\n
  • Get timers by name.
    var timers = realtimetimers.getTimers(name);\n
  • Amount of total timers
    var amount = realtimetimers.length;\n
"},{"location":"realtimetimers/#remove-timers","title":"Remove timers","text":"
  • Remove timers by name
    realtimetimers.removeTimers(name);\n
  • Remove timer object
    realtimetimers.removeTimers(timer);\n
    • timer : A timer object, or an array of timer objects.
  • Remove all timers
    realtimetimers.clearTimers();\n
"},{"location":"realtimetimers/#states","title":"States","text":"
  • Get states in plain object
    var states = realtimetimers.toJSON();\n
  • Get states in JSON string. Can store this JSON string into webstorage or server.
    var s = JSON.stringify(realtimetimers);\n
  • Set states by plain object
    realtimetimers.resetFromJSON(states)\n
"},{"location":"realtimetimers/#events","title":"Events","text":"
  • On add a timer
    realtimetimers.on('add', function(timer, timers){ })\n
    • timer : Added timer.
      {\nname: name,\nstart: timestamp,\nperiod: time\n}\n
    • timers : Total timers after adding.
  • On remove a timer
    realtimetimers.on('remove', function(timer, timers){ })\n
    • timer : Removed timer.
      {\nname: name,\nstart: timestamp,\nperiod: time\n}\n
    • timers : Total timers after removing.
  • On timers updated (add, remove, or increas period).
    realtimetimers.on('update', function(timers){ var s = JSON.stringify(realtimetimers);\n// Store current states to webstorage or server here.\n})\n
    • timers : Total timers after updating.
"},{"location":"rendertexture/","title":"Render texture","text":""},{"location":"rendertexture/#introduction","title":"Introduction","text":"

Paste game objects or textures on dynaimc texture, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"rendertexture/#usage","title":"Usage","text":""},{"location":"rendertexture/#add-render-texture-object","title":"Add render texture object","text":"
  • Create an empty render texture object.
    var rt = scene.add.renderTexture(x, y, width, height);\n

Add render texture from JSON

var rt = scene.make.renderTexture({\nx: 0,\ny: 0,\nwidth: 32,\nheight: 32,\n\n// angle: 0,\n// alpha: 1\n// flipX: true,\n// flipY: true,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n

Origin position

Origin position of this render texture is (0,0) (top-left)

"},{"location":"rendertexture/#custom-class","title":"Custom class","text":"
  • Define class
    class MyRenderTexture extends Phaser.GameObjects.RenderTexture {\nconstructor(scene, x, y, width, height) {\nsuper(scene, x, y, width, height);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var rt = new MyRenderTexture(scene, x, y, width, height);\n
"},{"location":"rendertexture/#set-size","title":"Set size","text":"
rt.setSize(width, height);\n
"},{"location":"rendertexture/#fill-color","title":"Fill color","text":"
rt.fill(rgb);\n// rt.fill(rgb, alpha, x, y, width, height);\n
  • rgb : The number color to fill this Dynamic Texture with.
  • alpha : The alpha value used by the fill. Default value is 1.
  • x, y, width, height : The area of the fill rectangle. Default behavior is filling whole size.
"},{"location":"rendertexture/#clear","title":"Clear","text":"
rt.clear();\n
rt.clear(x, y, width, height);\n
"},{"location":"rendertexture/#draw-game-object","title":"Draw game object","text":"
rt.draw(entries);\n// rt.draw(entries,x, y);\n// rt.draw(entries, x, y, alpha, tint);\n
  • entries :
    • Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
    • Tilemap Layers.
    • A Group. The contents of which will be iterated and drawn in turn.
    • A Container. The contents of which will be iterated fully, and drawn in turn.
    • A Scene Display List. Pass in Scene.children to draw the whole list.
    • Another Dynamic Texture, or a Render Texture.
    • A Texture Frame instance.
    • A string. This is used to look-up the texture from the Texture Manager.
  • x, y : The x/y position to draw the Frame at, or the offset applied to the object.
    • If the object is a Group, Container or Display List, the coordinates are added to the positions of the children.
    • For all other types of object, the coordinates are exact.
  • alpha, tint : Only used by Texture Frames.
    • Game Objects use their own alpha and tint values when being drawn.
"},{"location":"rendertexture/#erase","title":"Erase","text":"
rt.erase(entries);\n// rt.erase(entries, x, y);\n
  • entries :
    • Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
    • Tilemap Layers.
    • A Group. The contents of which will be iterated and drawn in turn.
    • A Container. The contents of which will be iterated fully, and drawn in turn.
    • A Scene Display List. Pass in Scene.children to draw the whole list.
    • Another Dynamic Texture, or a Render Texture.
    • A Texture Frame instance.
    • A string. This is used to look-up the texture from the Texture Manager.
  • x, y : The x/y position to draw the Frame at, or the offset applied to the object.
    • If the object is a Group, Container or Display List, the coordinates are added to the positions of the children.
    • For all other types of object, the coordinates are exact.
"},{"location":"rendertexture/#draw-frame","title":"Draw frame","text":"
rt.stamp(key, frame, x, y, {\nalpha: 1,\ntint: 0xffffff,\nangle: 0,\nrotation: 0,\nscale: 1,\nscaleX: 1,\nscaleY: 1,\noriginX: 0.5,\noriginY: 0.5,\nblendMode: 0,\nerase: false,\nskipBatch: false\n})\n

or

rt.drawFrame(key, frame, x, y);\n// rt.drawFrame(key, frame, x, y, alpha, tint);\n
  • x, y : Top-left position
"},{"location":"rendertexture/#draw-repeat-frames","title":"Draw repeat frames","text":"
  • Repeat frames full of size
    rt.repeat(key, frame);\n
  • Repeat in an area
    rt.repeat(key, frame, x, y, width, height);\n// rt.repeat(key, frame, x, y, width, height, alpha, tint, skipBatch);\n
"},{"location":"rendertexture/#batch-draw","title":"Batch draw","text":"
  1. Begin
    rt.beginDraw();\n
  2. Draw
    • Draw game object
      rt.batchDraw(entries, x, y, alpha, tint);\n
      • entries :
        • Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
        • Tilemap Layers.
        • A Group. The contents of which will be iterated and drawn in turn.
        • A Container. The contents of which will be iterated fully, and drawn in turn.
        • A Scene Display List. Pass in Scene.children to draw the whole list.
        • Another Dynamic Texture, or a Render Texture.
        • A Texture Frame instance.
        • A string. This is used to look-up the texture from the Texture Manager.
    • Draw frame
      rt.batchDrawFrame(key, frame, x, y, alpha, tint);\n
    • Draw image
      rt.stamp(key, frame, x, y, {\n// ...\nskipBatch: true\n})\n
    • Draw repeat images
      rt.repeat(key, frame, x, y, width, height, alpha, tint, true);\n
  3. End
    rt.endDraw();\n
"},{"location":"rendertexture/#internal-camera","title":"Internal camera","text":"

Internal camera rt.camera

  • Scroll (offset)
    rt.camera.setScroll(x, y);\n
  • Zoom (scale)
    rt.camera.setZoom(zoom);\n
  • Rotate
    rt.camera.setAngle(angle);  // angle in degrees\n
"},{"location":"rendertexture/#snapshot","title":"Snapshot","text":""},{"location":"rendertexture/#snapshot-area","title":"Snapshot area","text":"
texture.snapshot(callback);\n// texture.snapshot(callback, type, encoderOptions);\n

or

texture.snapshotArea(x, y, width, height, callback, type, encoderOptions);\n
  • callback : The Function to invoke after the snapshot image is created.
    function(imageElement) {\n}\n
    • imageElement : HTMLImageElement.
  • type : The format of the image to create, usually 'image/png' or 'image/jpeg'. Default value is 'image/png'.
  • encoderOptions : The image quality, between 0 and 1. Used for image formats with lossy compression, such as 'image/jpeg'. Default value is 0.92.
  • x, y, width, height : Snapshot area.
"},{"location":"rendertexture/#get-color-of-a-pixel","title":"Get color of a pixel","text":"
texture.snapshotPixel(x, y, callback);\n
  • x, y : The x/y coordinate of the pixel to get.
  • callback : The Function to invoke after the snapshot image is created.
    function(color) {        }\n
    • color : Color object.
"},{"location":"rendertexture/#global-alpha","title":"Global alpha","text":"
rt.setGlobalAlpha(alpha);\n// rt.globalAlpha = alpha;\n
"},{"location":"rendertexture/#global-tint","title":"Global tint","text":"
rt.setGlobalTint(tint);\n// rt.globalTint = tint;\n
"},{"location":"rendertexture/#save-texture","title":"Save texture","text":"

Stores a copy of this Render Texture in the Texture Manager using the given key.

rt.saveTexture(key);\n

Calling saveTexture again will not save another copy of the same texture, it will just rename the key of the existing copy.

"},{"location":"rendertexture/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"rendertexture/#create-mask","title":"Create mask","text":"
var mask = rt.createBitmapMask();\n

See mask

"},{"location":"rendertexture/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"repeatimage/","title":"Repeat image","text":""},{"location":"repeatimage/#introduction","title":"Introduction","text":"

Stamp image repeatly on canvas, similar with TileSprite. It has better rendering result when the texture size is not power of 2, in WebGL and pixelArt mode.

  • Author: Rex
  • Game object
"},{"location":"repeatimage/#live-demos","title":"Live demos","text":"
  • PixelArt, compared with TileSprite
  • Scroll
"},{"location":"repeatimage/#usage","title":"Usage","text":"

Sample code

"},{"location":"repeatimage/#install-plugin","title":"Install plugin","text":""},{"location":"repeatimage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrepeatimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrepeatimageplugin.min.js', true);\n
  • Add repeat-image object
    var image = scene.add.rexRepeatImage(x, y, width, height, key, frame);\n
"},{"location":"repeatimage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RepeatImagePlugin from 'phaser3-rex-plugins/plugins/repeatimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRepeatImagePlugin',\nplugin: RepeatImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add repeat-image object
    var image = scene.add.rexRepeatImage(x, y, width, height, key, frame);\n
"},{"location":"repeatimage/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RepeatImage from 'phaser3-rex-plugins/plugins/repeatimage.js';\n
  • Add repeat-image object
    var image = new RepeatImage(scene, x, y, key, frame, config);\nscene.add.existing(image);\n
"},{"location":"repeatimage/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRepeatImagePlugin',\nplugin: RepeatImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"repeatimage/#create-instance","title":"Create instance","text":"
var image = scene.add.rexRepeatImage(x, y, width, height, key, frame);\n

Add image from JSON

var image = scene.make.rexRepeatImage({\nx: 0,\ny: 0,\nwidth: 512,\nheight: 512,\nkey: '',\n\nadd: true\n});\n
"},{"location":"repeatimage/#custom-class","title":"Custom class","text":"
  • Define class
    class MyImage extends RepeatImage {\nconstructor(scene, x, y, width, height, key, frame) {\nsuper(scene, x, y, width, height, key, frame);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyImage(scene, x, y, width, height, key, frame);\n
"},{"location":"repeatimage/#set-texture","title":"Set texture","text":"
image.setTexture(key, frame);\n
"},{"location":"repeatimage/#properties-of-tiles","title":"Properties of tiles","text":"
  • Position
    image.setTilePosition(x, y);\n
    or
    image.tilePositionX = x;\nimage.tilePositionY = y;\n
  • Scale
    image.setTileScale(scaleX, scaleY);\n
    or
    image.tileScaleX = scaleX;\nimage.tileScaleY = scaleY;\n
"},{"location":"repeatimage/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"repeatimage/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"repeatimage/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"repeatimage/#compare-with-tilesprite","title":"Compare with TileSprite","text":"

Using this RepeatImage when the texture size is not power of 2, in WebGL and pixelArt mode. Otherwise, using tileSprite

"},{"location":"restorabledata/","title":"Restorable data","text":""},{"location":"restorabledata/#introduction","title":"Introduction","text":"

Restorable data manager, extends from built-in data manager.

  • Author: Rex
  • Member of scene
"},{"location":"restorabledata/#live-demos","title":"Live demos","text":"
  • Restorable canvas
"},{"location":"restorabledata/#usage","title":"Usage","text":"

Sample code

"},{"location":"restorabledata/#install-plugin","title":"Install plugin","text":""},{"location":"restorabledata/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrestorabledataplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrestorabledataplugin.min.js', true);\n
  • Add restorable data object
    var data = scene.plugins.get('rexrestorabledataplugin').add(parent);\n
"},{"location":"restorabledata/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RestorableDataPlugin from 'phaser3-rex-plugins/plugins/restorabledata-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRestorableData',\nplugin: RestorableDataPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add restorable data object
    var data = scene.plugins.get('rexRestorableData').add(parent);\n
"},{"location":"restorabledata/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RestorableData from 'phaser3-rex-plugins/plugins/restorabledata.js';\n
  • Add restorable data object
    var data = new RestorableData(parent);\n
"},{"location":"restorabledata/#create-instance","title":"Create instance","text":"
var data = scene.plugins.get('rexRData').add(parent);\n// var data = scene.plugins.get('rexRData').add(parent, eventEmitter);\n
  • parent : The object (a scene, or a game object) that this DataManager belongs to.
  • eventEmitter : The DataManager's event emitter.
"},{"location":"restorabledata/#getsetremove-value","title":"Get/set/remove value","text":"

See built-in data manager.

"},{"location":"restorabledata/#commit","title":"Commit","text":"

Commit current data status into repository, and increase current version number.

data.commit();\n

or

data.commit(alias);\n
  • alias : A version alias string.
"},{"location":"restorabledata/#restore","title":"Restore","text":"
  • Restore data status to a specific version.
    data.restore(version);\n
    or
    data.version = version;\n
    • version : Version number or version alias string.
  • Rebuild data status from version 0 to a specific version.
    data.restore(version, true);\n
    • version : Version number or version alias string.
  • Reverse data status to last version.
    data.restore();\n
"},{"location":"restorabledata/#version","title":"Version","text":"
  • Get current version alias string
    var version = data.versionAlias;\n
  • Get all version alias strings
    var aliases = data.versionAliases;\n
  • Get current version number
    var version = data.version;\n
  • Get last version number
    var version = data.lastVersion;\n

Version starts from 0 which has no data. Each data.commit() will increase this version number.

"},{"location":"restorabledata/#saveload-status","title":"Save/load status","text":"
  • Get current status
    var o = data.toJSON();\n
  • Load status
    data.resetFromJSON(o);\n

or

  • Get current status via JSON string
    var s = JSON.stringify(data);\n
  • Load status via JSON string
    data.resetFromJSON(JSON.parse(s));\n
"},{"location":"reverse-string/","title":"Reverse","text":""},{"location":"reverse-string/#introduction","title":"Introduction","text":"

Reverses string, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"reverse-string/#usage","title":"Usage","text":"
var result = Phaser.Utils.String.ReverseString(str);\n
"},{"location":"rexvideo/","title":"Rexvideo","text":"

Warning

This plugin is abandoned, please using built-in video.

"},{"location":"rexvideo/#introduction","title":"Introduction","text":"

Play video on DOM, or on canvas.

  • Author: Rex
  • DOM Game object, or Canvas Game object
"},{"location":"rexvideo/#live-demos","title":"Live demos","text":""},{"location":"rexvideo/#usage","title":"Usage","text":"

Sample code

"},{"location":"rexvideo/#install-plugin","title":"Install plugin","text":""},{"location":"rexvideo/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexvideoplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexvideoplugin.min.js', true);\n
  • Add video object
    var video = scene.add.rexVideoCanvas(x, y, width, height, config);    // var video = scene.add.rexVideo(x, y, width, height, config);\n
"},{"location":"rexvideo/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import VideoPlugin from 'phaser3-rex-plugins/plugins/video-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexVideo',\nplugin: VideoPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add video object
    var video = scene.add.rexVideoCanvas(x, y, width, height, config);\n// var video = scene.add.rexVideo(x, y, width, height, config);\n
"},{"location":"rexvideo/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import VideoCanvas from 'phaser3-rex-plugins/plugins/videocanvas/VideoCanvas.js';\n// import VideoDOM from 'phaser3-rex-plugins/plugins/videodom/VideoDOM.js';\n
  • Add text object
    var video = new VideoCanvas(scene, x, y, width, height, config);\nscene.add.existing(video);\n// var video = new VideoDOM(scene, x, y, width, height, config);\n// scene.add.existing(video);\n
"},{"location":"rexvideo/#add-video-object","title":"Add video object","text":"
  • Video on DOM
    var video = scene.add.rexVideo(x, y, width, height, config);\n// var video = scene.add.rexVideo(x, y, config);\n// var video = scene.add.rexVideo(config);\n
  • Video on canvas
    var video = scene.add.rexVideoCanvas(x, y, width, height, config);\n// var video = scene.add.rexVideoCanvas(x, y, config);\n// var video = scene.add.rexVideoCanvas(config);\n

Default configuration

{\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\n\n// Element properties\nsrc: url,\n// src: {\n//     webm: webmFileURL,\n//     ogg: oggFileURL,\n//     mp4: mp4FileURL,\n//     h264: h264FileURL,\n// }\nid: undefined,\nautoPlay: true,\ncontrols: false,\nloop: false,\nmuted: false,\nplaysInline: true,\ncrossOrigin: 'anonymous',\nplaybackTimeChangeEventEnable: true,\n}\n
  • x, y : Position
  • width, height : Size of element
  • Element properties
    • src : Specifies the URL of the video file.
      • A string : url of the video file.
      • A plain object : { videoType: fileURL }
        1. Get webmFileURL if browser supports webm video format.
        2. Get oggFileURL if browser supports ogg video format.
        3. Get mp4FileURL if browser supports mp4 video format.
        4. Get h264FileURL if browser supports h264 video format.
    • id : id element property.
    • autoPlay : autoplay element property.
    • controls : controls element property.
    • loop : loop element property.
    • muted : muted element property.
    • playsInline : playsInline element property.
    • crossOrigin : crossOrigin element property.
  • playbackTimeChangeEventEnable : Set false to disable playbacktimechange event.
"},{"location":"rexvideo/#different-between-rexvideo-and-rexvideocanvas","title":"Different between rexVideo and rexVideoCanvas","text":"
  • rexVideo plays video on DOM.
    • DOM object always above game canvas.
    • Won't be affected by webgl shader.
    • Right clicks to pop up a menu.
  • rexVideoCanvas plays video on canvas.
    • Can be placed between game objects via depth setting.
    • Can be affected by webgl shader.
"},{"location":"rexvideo/#custom-class","title":"Custom class","text":"
  • Define class
    class MyVideo extends Video {  // or VideoCanvas\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config) {\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     if (super.preUpdate) {\n//         super.preUpdate(time, delta)\n//     }\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var video = new MyVideo(scene, x, y, width, height, config);\n
"},{"location":"rexvideo/#load","title":"Load","text":"
video.load(src);\n
  • src : Specifies the URL of the video file.
    • A string : url of the video file.
    • A plain object : { videoType: fileURL }
      1. Get webmFileURL if browser supports webm video format.
      2. Get oggFileURL if browser supports ogg video format.
      3. Get mp4FileURL if browser supports mp4 video format.
      4. Get h264FileURL if browser supports h264 video format.
"},{"location":"rexvideo/#play","title":"Play","text":"
video.play();\n
"},{"location":"rexvideo/#pause","title":"Pause","text":"
video.pause();\n
"},{"location":"rexvideo/#playback-time","title":"Playback time","text":"
  • Get
    var playbackTime = video.playbackTime; // time in seconds\n
    var t = video.t; // t: 0~1\n
  • Set
    video.setPlaybackTime(time); // time in seconds\n// video.playbackTime = time;\n
    video.setT(t); // t: 0~1\n// video.t = t;\n
"},{"location":"rexvideo/#duration","title":"Duration","text":"
var duration = video.duration;  // time in seconds\n
"},{"location":"rexvideo/#volume","title":"Volume","text":"
  • Get
    var volume = video.volume;  // volume: 0~1\n
  • Set
    video.setVolume(volume);  // volume: 0~1\n// video.volume = volume;\n
"},{"location":"rexvideo/#mute","title":"Mute","text":"
  • Get
    var muted = video.muted;  // muted: true/false\n
  • Set
    video.setMute(muted);  // muted: true/false\n// video.muted = muted;\n
"},{"location":"rexvideo/#loop","title":"Loop","text":"
  • Get
    var loop = video.loop;  // loop: true/false\n
  • Set
    video.setLoop(loop);  // loop: true/false\n// video.loop = loop;\n
"},{"location":"rexvideo/#resize","title":"Resize","text":"
video.resize(width, height);\n
"},{"location":"rexvideo/#status","title":"Status","text":"
  • Is playing
    var isPlaying = video.isPlaying;\n
  • Is paused
    var isPaused = video.isPaused;\n
  • Has end
    var hasEnded = video.hasEnded;\n
  • Ready state
    var readyState = video.readyState;\n
    • 0 = HAVE_NOTHING - no information whether or not the audio/video is ready
    • 1 = HAVE_METADATA - metadata for the audio/video is ready
    • 2 = HAVE_CURRENT_DATA - data for the current playback position is available, but not enough data to play next frame/millisecond
    • 3 = HAVE_FUTURE_DATA - data for the current and at least the next frame is available
    • 4 = HAVE_ENOUGH_DATA - enough data available to start playing
"},{"location":"rexvideo/#events","title":"Events","text":"
  • Load start
    video.on('loadstart', function(video){ }, scope);\n
  • Can play
    video.on('canplay', function(video){ }, scope);\n
  • Can play through
    video.on('canplaythrough', function(video){ }, scope);\n
  • Playing
    video.on('playing', function(video){ }, scope);\n
  • Pause
    video.on('pause', function(video){ }, scope);\n
  • Stalled
    video.on('stalled', function(video){ }, scope);\n
  • Ended
    video.on('ended', function(video){ }, scope);\n
  • Error
    video.on('error', function(video){ }, scope);\n
  • Playback time changed
    video.on('playbacktimechange', function(video){ }, scope);\n
    • Set playbackTimeChangeEventEnable to true to enable this event.
"},{"location":"rope/","title":"Rope","text":""},{"location":"rope/#introduction","title":"Introduction","text":"

Manipulate the vertices of images, built-in game object of phaser.

  • Author: Richard Davey

WebGL only

It only works in WebGL render mode.

"},{"location":"rope/#usage","title":"Usage","text":""},{"location":"rope/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"rope/#add-object","title":"Add object","text":"
var rope = scene.add.rope(x, y, texture, frame, points, horizontal);\n// var rope = scene.add.rope(x, y, texture, frame, points, horizontal, colors, alphas);\n
  • points :
    • A number : Segments to split the texture frame into.
    • An number array : An array containing the vertices data.
  • horizontal :
    • true : Vertices of this Rope be aligned horizontally.
    • false : Vertices of this Rope be aligned vertically.
  • colors : An optional array containing the color data for this Rope. One color value per pair of vertices.
  • alphas : An optional array containing the alpha data for this Rope. One alpha value per pair of vertices.

Add rope from JSON

var rope = scene.make.rope({\nx: 0,\ny: 0,\nkey: '',\nframe: null,\nhorizontal: true,\npoints: undefined,\ncolors: undefined,\nalphas: undefined,\n\n// angle: 0,\n// alpha: 1\n// flipX: true,\n// flipY: true,\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
"},{"location":"rope/#custom-rope-class","title":"Custom rope class","text":"
  • Define class
    class MyRope extends Phaser.GameObjects.Rope {\nconstructor(scene, x, y, texture, frame, points, horizontal, colors, alphas) {\nsuper(scene, x, y, texture, frame, points, horizontal, colors, alphas);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var rope = new MyRope(scene, x, y, texture, frame, points, horizontal);\n
"},{"location":"rope/#origin","title":"Origin","text":"

A Ropes origin is always 0.5 x 0.5 and cannot be changed.

"},{"location":"rope/#set-vertices","title":"Set vertices","text":"

Set vertices via

rope.setPoints(points);\n// rope.setPoints(points, colors, alphas);\n
  • points :
    • A number : Segments to split the texture frame into.
    • An number array : An array containing the vertices data.
  • colors : An optional array containing the color data for this Rope. One color value per pair of vertices.
  • alphas : An optional array containing the alpha data for this Rope. One alpha value per pair of vertices.

Also change horizontal mode :

  • Change vertical rope to horizontal rope, do nothing if rope is horizontal mode already
    rope.setHorizontal(points);\n// rope.setHorizontal(points, colors, alphas);\n
  • Change horizontal rope to vertical rope, do nothing if rope is vertical mode already
    rope.setVertical(points);\n// rope.setVertical(points, colors, alphas);\n

Or set rope.points directly :

  1. Change rope.points
    • Horizontal rope : rope.points[i].y = newY
    • Vertical rope : rope.points[i].x = newX
  2. Call rope.setDirty(), or rope.updateVertices()

Each point is relative to position of rope object, get points of world via

var worldX = rope.points[i].x + rope.x;\nvar worldY = rope.points[i].y + rope.y;\n
"},{"location":"rope/#play-animation","title":"Play animation","text":"
rope.play(key);\n// rope.play(key, ignoreIfPlaying, startFrame);\n
  • ignoreIfPlaying : If an animation is already playing then ignore this call. Default value is false.
  • startFrame : Optionally start the animation playing from this frame index. Default value is 0.
"},{"location":"rope/#alpha","title":"Alpha","text":"
  • Single alpha
    rope.setAlphas(alpha);\n
  • Top - bottom alpha
    rope.setAlphas(topAlpha, bottomAlpha);\n
  • Alpha array for each point
    rope.setAlphas(alphaArray);\n
    • alphaArray : Array of alpha value.
"},{"location":"rope/#color-tint","title":"Color tint","text":"
  • Single color tint
    rope.setColors(color);\n
  • Color tint array for each point
    rope.setAlphas(colorArray);\n
    • colorArray : Array of color tint value.
"},{"location":"rope/#tint-fill-mode","title":"Tint fill mode","text":"

Sets the tint fill mode.

rope.setTintFill(mode);\n
  • mode :
    • 0 : Additive tint, blends the vertices colors with the texture. Default behavior.
    • 1 : Fill tint with alpha.
    • 2 : Fill tint without alpha.
"},{"location":"rope/#flip","title":"Flip","text":"
rope.flipX = flip;\nrope.flipY = flip;\n

If this Game Object has a physics body, it will not change the body. This is a rendering toggle only.

"},{"location":"rope/#debug","title":"Debug","text":"

Draw debug mesh each render tick.

rope.setDebug(graphic);\n// rope.setDebug(graphic, callback);\n
  • graphic : Graphics game object
  • callback : Callback of rendering debug graphics (default callback)
    function(rope, meshLength, verts) {\n// var graphic = rope.debugGraphic;\n}\n
    • rope : Rope instance.
      • rope.debugGraphic : Graphics game object
    • meshLength : The number of mesh vertices in total.
    • verts : An array of the translated vertex coordinates.

Note

Clear Debug graphics (rope.debugGraphic.clear()) during scene's update stage (scene.update() { })

"},{"location":"rotate/","title":"Rotate","text":""},{"location":"rotate/#introduction","title":"Introduction","text":"

Rotate game object continually with a steady speed.

  • Author: Rex
  • Behavior of game object
"},{"location":"rotate/#live-demos","title":"Live demos","text":"
  • Change speed
"},{"location":"rotate/#usage","title":"Usage","text":"

Sample code

"},{"location":"rotate/#install-plugin","title":"Install plugin","text":""},{"location":"rotate/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrotateplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrotateplugin.min.js', true);\n
  • Add rotate behavior
    var rotate = scene.plugins.get('rexrotateplugin').add(gameObject, config);\n
"},{"location":"rotate/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RotatePlugin from 'phaser3-rex-plugins/plugins/rotate-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRotate',\nplugin: RotatePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add rotate behavior
    var rotate = scene.plugins.get('rexRotate').add(gameObject, config);\n
"},{"location":"rotate/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Rotate from 'phaser3-rex-plugins/plugins/rotate.js';\n
  • Add rotate behavior
    var rotate = new Rotate(gameObject, config);\n
"},{"location":"rotate/#create-instance","title":"Create instance","text":"
var rotate = scene.plugins.get('rexRotate').add(gameObject, {\n// speed: 180,\n// enable: true,\n// timeScale: 1,\n});\n
  • speed : Turn speed, degrees in second
"},{"location":"rotate/#enable","title":"Enable","text":"
  • Enable (default)
    rotate.setEnable();\n
    or
    rotate.enable = true;\n
  • Disable
    rotate.setEnable(false);\n
    or
    rotate.enable = false;\n
"},{"location":"rotate/#set-speed","title":"Set speed","text":"
rotate.setSpeed(speed);\n// rotate.speed = speed;\n
  • speed : Turn speed, degrees in second
"},{"location":"rotate/#status","title":"Status","text":"
  • Is rotating
    var enable = rotate.enable;\n// var isRunning = rotate.isRunning;\n
"},{"location":"rotateto/","title":"Rotate to","text":""},{"location":"rotateto/#introduction","title":"Introduction","text":"

Rotate game object towards target position with a steady speed.

  • Author: Rex
  • Behavior of game object
"},{"location":"rotateto/#usage","title":"Usage","text":"

Sample code

"},{"location":"rotateto/#install-plugin","title":"Install plugin","text":""},{"location":"rotateto/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrotatetoplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrotatetoplugin.min.js', true);\n
  • Add rotate-to behavior
    var rotateTo = scene.plugins.get('rexrotatetoplugin').add(gameObject, config);\n
"},{"location":"rotateto/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RotateToPlugin from 'phaser3-rex-plugins/plugins/rotateto-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRotateTo',\nplugin: RotateToPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add rotate-to behavior
    var rotateTo = scene.plugins.get('rexRotateTo').add(gameObject, config);\n
"},{"location":"rotateto/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RotateTo from 'phaser3-rex-plugins/plugins/rotateto.js';\n
  • Add rotate-to behavior
    var rotateTo = new RotateTo(gameObject, config);\n
"},{"location":"rotateto/#create-instance","title":"Create instance","text":"
var rotateTo = scene.plugins.get('rexRotateTo').add(gameObject, {\n// speed: 180,\n// enable: true,\n// timeScale: 1,\n});\n
  • speed : Turn speed, degrees in second
"},{"location":"rotateto/#start-moving","title":"Start moving","text":""},{"location":"rotateto/#rotate-game-object-towards-position","title":"Rotate game object towards position","text":"
  • Shortest angle
    rotateTo.rotateTowardsPosition(x, y);\n
    • x , y : Target position
  • Clockwise/counter-clockwise
    rotateTo.rotateTowardsPosition(x, y, dir);\n// rotateTo.rotateTowardsPosition(x, y, dir, speed);\n
    • dir :
      • 0 : Shortest angle
      • 1, or 'cw' : Clockwise
      • 2, or 'ccw' : Counter-clockwise
    • speed : Turn speed, degrees in second
"},{"location":"rotateto/#rotate-game-object-to-angle","title":"Rotate game object to angle","text":"
  • Shortest angle
    rotateTo.rotateTo(angle);\n
    • angle : Target angle in degrees
  • Clockwise/counter-clockwise
    rotateTo.rotateTo(angle, dir);\n// rotateTo.rotateTo(angle, dir, speed);\n
    • dir :
      • 0 : Shortest angle
      • 1, or cw : Clockwise
      • 2, or ccw : Counter-clockwise
    • speed : Turn speed, degrees in second
"},{"location":"rotateto/#enable","title":"Enable","text":"
  • Enable (default)
    rotateTo.setEnable();\n
    or
    rotateTo.enable = true;\n
  • Disable
    rotateTo.setEnable(false);\n
    or
    rotateTo.enable = false;\n
"},{"location":"rotateto/#pause-resume-stop-rotating","title":"Pause, Resume, stop rotating","text":"
rotateTo.pause();\nrotateTo.resume();\nrotateTo.stop();\n
"},{"location":"rotateto/#set-speed","title":"Set speed","text":"
rotateTo.setSpeed(speed);\n// rotateTo.speed = speed;\n
  • speed : Turn speed, degrees in second
"},{"location":"rotateto/#events","title":"Events","text":"
  • On rotating start
    rotateTo.on('start', function(gameObject, rotateTo){});\n
  • On reached target
    rotateTo.on('complete', function(gameObject, rotateTo){});\n
"},{"location":"rotateto/#status","title":"Status","text":"
  • Is moving
    var isRunning = rotateTo.isRunning;\n
"},{"location":"round-to/","title":"Round to","text":""},{"location":"round-to/#introduction","title":"Introduction","text":"

Round/ceil/floor to the given precision, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"round-to/#usage","title":"Usage","text":""},{"location":"round-to/#round-to","title":"Round to","text":"

var result = Phaser.Math.RoundTo(value);\n
or
var result = Phaser.Math.RoundTo(value, place, base);\n

  • value : The value to round.
  • place : The place to round to. Positive to round the units, negative to round the decimal. Default is 0.
  • base : The base to round in. Default is 10 for decimal.

Examples

RoundTo(123.456789, 0) = 123\nRoundTo(123.456789, -1) = 123.5\nRoundTo(123.456789, -2) = 123.46\nRoundTo(123.456789, -3) = 123.457\n
"},{"location":"round-to/#ceil-to","title":"Ceil to","text":"

var result = Phaser.Math.CeilTo(value);\n
or
var result = Phaser.Math.CeilTo(value, place, base);\n

  • value : The value to round.
  • place : The place to round to. Positive to round the units, negative to round the decimal. Default is 0.
  • base : The base to round in. Default is 10 for decimal.
"},{"location":"round-to/#floor-to","title":"Floor to","text":"

var result = Phaser.Math.floorTo(value);\n
or
var result = Phaser.Math.floorTo(value, place, base);\n

  • value : The value to round.
  • place : The place to round to. Positive to round the units, negative to round the decimal. Default is 0.
  • base : The base to round in. Default is 10 for decimal.
"},{"location":"runcommands/","title":"Run commands","text":""},{"location":"runcommands/#introduction","title":"Introduction","text":"

Run commands in array.

  • Author: Rex
  • Method only
"},{"location":"runcommands/#usage","title":"Usage","text":"

Sample code

"},{"location":"runcommands/#install-plugin","title":"Install plugin","text":""},{"location":"runcommands/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexruncommandsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexruncommandsplugin.min.js', true);\n
  • Run commands
    scene.plugins.get('rexruncommandsplugin').run(commands, scope);\n
"},{"location":"runcommands/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RunCommandsPlugin from 'phaser3-rex-plugins/plugins/runcommands-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRunCommands',\nplugin: RunCommandsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Run commands
    scene.plugins.get('rexRunCommands').run(commands, scope);\n
"},{"location":"runcommands/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RunCommands from 'phaser3-rex-plugins/plugins/runcommands.js';\n
  • Run commands
    RunCommands(commands, scope);\n
"},{"location":"runcommands/#run-commands","title":"Run commands","text":"
scene.plugins.get('rexRunCommands').run(commands, scope);\n
  • Format of command :
    [fnName, param0, param1, ...]\n
    or
    [callback, param0, param1, ...]\n
  • Commands in nested array :
    [\ncommand0,\ncommand1\n[\ncommand2,\ncommand3\n]\n]\n
  • Run command :
    scope[fnName].call(scope, param0, param1 ...)\n
    or
    callback.call(scope, param0, param1 ...)\n
"},{"location":"scaledowndestroy/","title":"Scale down destroy","text":""},{"location":"scaledowndestroy/#introduction","title":"Introduction","text":"

Scale down (i.e. ease scaleX, scaleY to 0) game object then destroy it.

  • Author: Rex
  • Method only
"},{"location":"scaledowndestroy/#usage","title":"Usage","text":"

Sample code

"},{"location":"scaledowndestroy/#install-plugin","title":"Install plugin","text":""},{"location":"scaledowndestroy/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexscaleplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexscaleplugin.min.js', true);\n
  • Scale down, then destroy object
    scene.plugins.get('rexscaleplugin').scaleDownDestroy(gameObject, duration);\n
"},{"location":"scaledowndestroy/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ScalePlugin from 'phaser3-rex-plugins/plugins/scale-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexScale',\nplugin: ScalePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Scale down, then destroy object
    scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration);\n
"},{"location":"scaledowndestroy/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ScaleDownDestroy from 'phaser3-rex-plugins/plugins/scale-down-destroy.js';\n
  • Scale down, then destroy object
    ScaleDownDestroy(gameObject, duration);\n
"},{"location":"scaledowndestroy/#scale-down","title":"Scale down","text":"
  • Scale down width and height
    var scale = scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration);\n// var scale = scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration, undefined, ease);\n
    • ease : Ease function, default is 'Linear'.
  • Scale down width only
    var scale = scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration, 'x');\n// var scale = scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration, 'x', ease);\n
  • Scale down height only
    var scale = scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration, 'y');\n// var scale = scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration, 'y', ease);\n
"},{"location":"scaledowndestroy/#events","title":"Events","text":"

See Events of tween task

  • Scale completes or is stopped.
    scale.on('complete', function(gameObject, scale){\n\n}, scope);\n
"},{"location":"scaledowndestroy/#inject-methods","title":"Inject methods","text":"
  • Inject methods into game object
    scene.plugins.get('rexScale').injectMethods(gameObject);\n
  • Inject methods into class of game object
    scene.plugins.get('rexScale').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexScale').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into class of game object
    scene.plugins.get('rexScale').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexScale').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into root class of game object
    scene.plugins.get('rexScale').injectMethodsToRootClass(e);\n// scene.plugins.get('rexScale').injectMethods(Phaser.GameObjects.GameObject.prototype);\n
"},{"location":"scaledowndestroy/#injected-methods","title":"Injected methods","text":"
  • Scale up from 0 to current scale of game object.
    • Pop-up width and height
      gameObject\n//.setScale(scaleX, scaleY)\n.popUp(duration);\n\n// gameObject.popUp(duration, undefined, ease);\n
      or
      gameObject\n//.setScale(scaleX, scaleY)\n.popUpPromise(duration)\n.then(function() {\n// ....\n})\n
      • ease : Ease function, default is 'Cubic'.
    • Pop-up width only
      gameObject\n//.setScaleX(scaleX)\n.popUp(duration, 'x');\n\n// gameObject.popUp(duration, 'x', ease);\n
      or
      gameObject\n//.setScaleX(scaleX)\n.popUpPromise(duration, 'x')\n.then(function() {\n// ....\n})\n
    • Pop-up height only
      gameObject\n//.setScaleY(scaleY)\n.popUp(duration, 'y');\n\n// gameObject.popUp(duration, 'y', ease);\n
      or
      gameObject\n//.setScaleY(scaleY)\n.popUpPromise(duration, 'y')\n.then(function() {\n// ....\n})\n
    • Pop-up via config
      gameObject\n//.setScale(scaleX, scaleY)\n.popUp({\nduration: undefined,\norientation: undefined,\nease: undefined,\n})\n
      or
      gameObject\n//.setScale(scaleX, scaleY)\n.popUpPromise(config)\n.then(function() {\n// ....\n})\n
      • orientation : undefined, x, or y
  • Scale-down destroy
    • Scale-down width and height
      gameObject.scaleDownDestroy(duration);\n// gameObject.scaleDownDestroy(duration, undefined, ease);\n
      or
      gameObject.scaleDownDestroyPromise(duration)\n.then(function() {\n// ....\n})\n
      • ease : Ease function, default is 'Linear'.
    • Scale-down width only
      gameObject.scaleDownDestroy(duration, 'x');\n// gameObject.scaleDownDestroy(duration, 'x', ease);\n
      or
      gameObject.scaleDownDestroyPromise(duration, 'x');\n.then(function() {\n// ....\n})\n
    • Scale-down height only
      gameObject.scaleDownDestroy(duration, 'y');\n// gameObject.scaleDownDestroy(duration, 'y', ease);\n
      or
      gameObject.scaleDownDestroyPromise(duration, 'y')\n.then(function() {\n// ....\n})\n
  • Scale-down without destroy
    • Scale-down width and height
      gameObject.scaleDown(duration);\n// gameObject.scaleDown(duration, undefined, ease);\n
      or
      gameObject.scaleDownPromise(duration, undefined, ease)\n.then(function() {\n// ....\n})\n
    • Scale-down width only
      gameObject.scaleDowny(duration, 'x');\n// gameObject.scaleDowny(duration, 'x', ease);\n
      or
      gameObject.scaleDownPromise(duration, 'x', ease)\n.then(function() {\n// ....\n})\n
    • Scale-down height only
      gameObject.scaleDown(duration, 'y');\n// gameObject.scaleDown(duration, 'y', ease);\n
      or
      gameObject.scaleDownPromise(duration, 'y', ease)\n.then(function() {\n// ....\n})\n
  • Scale up/down, then scale back (yoyo)
    • Scale up/down, then scale back width and height
      gameObject\n//.setScale(scaleX, scaleY)\n.scaleYoyo(duration, peakValue);\n\n// gameObject.scaleYoyo(duration, peakValue, repeat, undefined, ease);\n
      or
      gameObject\n//.setScale(scaleX, scaleY)\n.scaleYoyoPromise(duration, peakValue, repeat)\n.then(function() {\n// ....\n})\n
      • peakValue : Scale to this peak value, then scale back
      • repeat : Yoyo repeat, default value is 0.
      • ease : Ease function, default is 'Cubic'.
    • Scale up/down, then scale back width only
      gameObject\n//.setScaleX(scaleX)\n.scaleYoyo(duration, peakValue, 0, 'x');\n\n// gameObject.popUp(duration, peakValue, repeat, 'x', ease);\n
      or
      gameObject\n//.setScaleX(scaleX)\n.scaleYoyoPromise(duration, peakValue, repeat, 'x')\n.then(function() {\n// ....\n})\n
    • Scale up/down, then scale back height only
      gameObject\n//.setScaleY(scaleY)\n.scaleYoyo(duration, peakValue, 0, 'y');\n\n// gameObject.popUp(duration, peakValue, repeat, 'y', ease);\n
      or
      gameObject\n//.setScaleY(scaleY)\n.scaleYoyoPromise(duration, peakValue, repeat, 'y')\n.then(function() {\n// ....\n})\n
    • Scale up/down via config
      gameObject\n//.setScale(scaleX, scaleY)\n.scaleYoyo({\nduration: undefined,\npeakValue: 1.2,\nrepeat: 0,\norientation: undefined,\nease: undefined,\n})\n
      or
      gameObject\n//.setScale(scaleX, scaleY)\n.scaleYoyoPromise(config)\n.then(function() {\n// ....\n})\n
      • orientation : undefined, x, or y
  • Events
    • Pop-up complete
      gameObject.on('popup.complete', function(gameObject) { });\n
    • Scale-down, scale-down destroy complete
      gameObject.on('scaledown.complete', function(gameObject) { });\n
    • Scale up/down, then scale back (yoyo)
      gameObject.on('scaleyoyo.complete', function(gameObject) { });\n
"},{"location":"scalemanager/","title":"Scale manager","text":""},{"location":"scalemanager/#introduction","title":"Introduction","text":"

Scale game window, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"scalemanager/#usage","title":"Usage","text":""},{"location":"scalemanager/#setup","title":"Setup","text":"

Setup scale mode in game configuration.

var config = {\n// ...\nparent: divId,\n\n// Game size\nwidth: 1024,\nheight: 768,\n\nscale: {\n// Or set parent divId here\nparent: divId,\n\nmode: Phaser.Scale.FIT,\nautoCenter: Phaser.Scale.CENTER_BOTH,\n\n// Or put game size here\n// width: 1024,\n// height: 768,\n\n// Minimum size\nmin: {\nwidth: 800,\nheight: 600\n},\n// Or set minimum size like these\n// minWidth: 800,\n// minHeight: 600,\n\n// Maximum size\nmax: {\nwidth: 1600,\nheight: 1200\n},\n// Or set maximum size like these\n// maxWidth: 1600,\n// maxHeight: 1200,\n\nzoom: 1,  // Size of game canvas = game size * zoom\n},\nautoRound: false\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • scale.mode :
    • Phaser.Scale.NONE : No scaling happens at all.
    • Phaser.Scale.FIT : The width and height are automatically adjusted to fit inside the given target area, while keeping the aspect ratio. Depending on the aspect ratio there may be some space inside the area which is not covered.
    • Phaser.Scale.ENVELOP : The width and height are automatically adjusted to make the size cover the entire target area while keeping the aspect ratio. This may extend further out than the target size.
    • Phaser.Scale.WIDTH_CONTROLS_HEIGHT : The height is automatically adjusted based on the width.
    • Phaser.Scale.HEIGHT_CONTROLS_WIDTH : The width is automatically adjusted based on the height.
    • Phaser.Scale.EXPAND : The Canvas's visible area is resized to fit all available parent space like RESIZE mode, and scale canvas size to fit inside the visible area like FIT mode.
    • Phaser.Scale.RESIZE : The Canvas is resized to fit all available parent space, regardless of aspect ratio.
  • scale.autoCenter :
    • Phaser.Scale.NO_CENTER : The game canvas is not centered within the parent by Phaser.
    • Phaser.Scale.CENTER_BOTH : The game canvas is centered both horizontally and vertically within the parent.
    • Phaser.Scale.CENTER_HORIZONTALLY : The game canvas is centered horizontally within the parent.
    • Phaser.Scale.CENTER_VERTICALLY : The game canvas is centered both vertically within the parent.
"},{"location":"scalemanager/#resize-canvas-element","title":"Resize canvas element","text":"
scene.scale.resize(width, height);\n

Modify the size of the Phaser canvas element directly. You should only use this if you are using the NO_SCALE scale mode,

"},{"location":"scalemanager/#set-game-size","title":"Set game size","text":"
scene.scale.setGameSize(width, height);\n

It should only be used if you're looking to change the base size of your game and are using one of the Scale Manager scaling modes, i.e. FIT. If you're using NO_SCALE and wish to change the game and canvas size directly, then please use the resize method instead.

"},{"location":"scalemanager/#get-view-port","title":"Get view port","text":"
var viewport = scene.scale.getViewPort();\n// var viewport = scene.scale.getViewPort(camera, out);\n
  • viewport : The Rectangle of visible area.
  • camera : The camera this viewport is respond upon.
  • out : The Rectangle of visible area.
"},{"location":"scalemanager/#members","title":"Members","text":"
  • The un-modified game size, as requested in the game config (the raw width / height), as used for world bounds, cameras, etc
    var gameSize = scene.scale.gameSize;\n
    • gameSize.width, gameSize.height
  • The modified game size, which is the auto-rounded gameSize, used to set the canvas width and height (but not the CSS style)
    var baseSize = scene.scale.baseSize;\n
    • baseSize.width, baseSize.height
  • The size used for the canvas style, factoring in the scale mode, parent and other values.
    var displaySize = scene.scale.displaySize;\n
    • displaySize.width, displaySize.height
  • The size of parent dom element
    var parentSize = scene.scale.parentSize;\n
    • parentSize.width, parentSize.height
"},{"location":"scalemanager/#events","title":"Events","text":"
scene.scale.on('resize', function(gameSize, baseSize, displaySize, previousWidth, previousHeight) {});\n
  • gameSize : The un-modified game size, as requested in the game config (the raw width / height)
    • gameSize.width, gameSize.height
  • baseSize : The canvas width and height (actually size of canvas)
    • baseSize.width, baseSize.height
  • displaySize : Size used for the canvas style (display size of canvas)
    • displaySize.width, displaySize.height
"},{"location":"scalemanager/#update-bounds","title":"Update bounds","text":"

This method dose not have to be invoked, unless the canvas position, or visibility is changed via any other method (i.e. via an Angular route).

scene.scale.updateBounds();\n
"},{"location":"scalemanager/#full-screen","title":"Full screen","text":"

Under 'pointerup' touch event :

  • Start full screen
    scene.scale.startFullscreen();\n
  • Stop full screen
    scene.scale.stopFullscreen();\n
  • Toggle full screen
    scene.scale.toggleFullscreen();\n
  • Is full screen
    var isFullscreen = scene.scale.isFullscreen;\n

Games within an iframe will also be blocked from fullscreen unless the iframe has the allowfullscreen attribute.

Performing an action that navigates to another page, or opens another tab, will automatically cancel fullscreen mode, as will the user pressing the ESC key.

"},{"location":"scalemanager/#events_1","title":"Events","text":"
  • Enter full screen
    scene.scale.on('enterfullscreen', function() {}, scope);\n
  • Enter full screen failed
    scene.scale.on('fullscreenfailed', function(error) {}, scope);\n
  • Leave full screen
    scene.scale.on('leavefullscreen', function() {}, scope);\n
  • Full screen unsupport
    scene.scale.on('fullscreenunsupported', function() {}, scope);\n
  • Leave full screen
    scene.scale.on('leavefullscreen', function() {}, scope);\n
"},{"location":"scalemanager/#orientation","title":"Orientation","text":""},{"location":"scalemanager/#properties","title":"Properties","text":"
  • Is portrait orientation
    var isPortrait = scene.scale.isPortrait;\n
  • Is landscape orientation
    var isLandscape = scene.scale.isLandscape;\n
"},{"location":"scalemanager/#lock-orientation","title":"Lock orientation","text":"
scene.scale.lockOrientation(orientation);\n
  • orientation : 'landscape', or 'portrait';
"},{"location":"scalemanager/#events_2","title":"Events","text":"
scene.scale.on('orientationchange', function(orientation) {\nif (orientation === Phaser.Scale.PORTRAIT) {\n\n} else if (orientation === Phaser.Scale.LANDSCAPE) {\n\n}\n}, scope);\n
"},{"location":"scaleouter/","title":"Scale outer","text":""},{"location":"scaleouter/#introduction","title":"Introduction","text":"

Scroll and zoom camera to make default game window fit the display area, in RESIZE scale mode.

  • Author: Rex
  • Member of scene
"},{"location":"scaleouter/#live-demos","title":"Live demos","text":"
  • Viewport
  • Static camera
  • Tween camera
"},{"location":"scaleouter/#usage","title":"Usage","text":"

Sample code

"},{"location":"scaleouter/#install-plugin","title":"Install plugin","text":""},{"location":"scaleouter/#set-scale-mode-to-resize","title":"Set scale mode to RESIZE","text":"
var config = {\n// ...\nscale: {\nparent: divId,\nmode: Phaser.Scale.RESIZE,\nwidth: 1024,    // Default game window width\nheight: 768,    // Default game window height\n// ...\n}\n}\nvar game = new Phaser.Game(config);\n
"},{"location":"scaleouter/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexscaleouterplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexscaleouterplugin.min.js', 'rexScaleOuter', 'rexScaleOuter');\n
  • Scale outer is created as a member of scene (scene.rexScaleOuter) for each scene. It will control main camera (scene.cameras.main) by default.
"},{"location":"scaleouter/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install scene plugin in configuration of game
    import ScaleOuterPlugin from 'phaser3-rex-plugins/plugins/scaleouter-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexScaleOuter',\nplugin: ScaleOuterPlugin,\nmapping: 'rexScaleOuter'\n}]\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Scale outer is created as a member of scene (scene.rexScaleOuter) for each scene. It will control main camera (scene.cameras.main) by default.
"},{"location":"scaleouter/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ScaleOuter from 'phaser3-rex-plugins/plugins/scaleouter.js';\n
  • Add scaleouter object
    var scaleouter = new ScaleOuter(scene);\n
"},{"location":"scaleouter/#create-instance","title":"Create instance","text":"

ScaleOuter plugin is a scene plugin, which created as a member of scene (scene.rexScaleOuter) for each scene. It does not have to create other scale outer instance.

"},{"location":"scaleouter/#remove-instance","title":"Remove instance","text":"

Invoke scene.rexScaleOuter.destroy() under scene.create() { ... }.

"},{"location":"scaleouter/#add-camera","title":"Add camera","text":"
  • Add camera manually, under scene.create() { ... }
    scene.rexScaleOuter.add(camera);\n
  • Scale outer will control main camera (scene.cameras.main) if no camera added.
"},{"location":"scaleouter/#viewport","title":"Viewport","text":"
  • Inner viewport, a recangle object, for area of default size in game config after camera zoom/scroll.
    var innerViewport = scene.rexScaleOuter.innerViewport;\n
  • Outer viewport, a recangle object, for the visible area after camera zoom/scroll.
    var outerViewport = scene.rexScaleOuter.outerViewport;\n
"},{"location":"scaleouter/#manual-scale","title":"Manual scale","text":"
  1. Stop resize callback
    scene.rexScaleOuter.stop()\n
  2. Manual scale
    scene.rexScaleOuter.scale();\n
"},{"location":"scene/","title":"Scene","text":""},{"location":"scene/#define-a-scene","title":"Define a scene","text":""},{"location":"scene/#configuration-of-scene","title":"Configuration of scene","text":"
var config = {\nkey: \"\",\n// active: false,\n// visible: true,\n// pack: false,\n// cameras: null,\n// map: {},\n// physics: {},\n// loader: {},\n// plugins: false,\n// input: {}\n};\n
  • key : The unique key of this Scene. Must be unique within the entire Game instance.
  • active : Does the Scene start as active or not? An active Scene updates each step.
  • visible : Does the Scene start as visible or not? A visible Scene renders each step.
  • pack : An optional Loader Packfile to be loaded before the Scene begins.
  • cameras : An optional Camera configuration object.
    {\nname: '',\nx: 0,\ny: 0,\nwidth: scene.sys.scale.width,\nheight: scene.sys.scale.height,\nzoom: 1,\nrotation: 0,\nscrollX: 0,\nscrollY: 0,\nroundPixels: false,\nvisible: true,\nbackgroundColor: false,\nbounds: null, // {x, y, width, height}\n}\n
  • map : Overwrites the default injection map for a scene.
  • physics : The physics configuration object for the Scene.
    {\ndefault: 'arcade', // 'arcade', or 'matter'\narcade: {...},\nmatter: {...}\n}\n
  • arcade : Arcade Physics configuration.
  • matter : Matter Physics configuration.
  • loader : The loader configuration object for the Scene.
    {\nbaseURL: '',\npath: '',\nenableParallel: true,\nmaxParallelDownloads: 4,\ncrossOrigin: undefined,\nresponseType: '',\nasync: true,\nuser: '',\npassword: '',\ntimeout: 0\n}\n
  • plugins : The plugin configuration object for the Scene.
    {\nglobal: [\n//{key, plugin, start}\n],\nscene: [\n// ...\n]\n}\n
  • input : The input configuration object for the Scene.
    {\nkeyboard: {\ntarget: window\n},\nmouse: {\ntarget: null,\ncapture: true\n},\nactivePointers: 1,\ntouch: {\ntarget: null,\ncapture: true\n},\nsmoothFactor: 0,\ngamepad: false,\nwindowEvents: true,\n}\n
"},{"location":"scene/#es6-class","title":"ES6 class","text":"
class MyScene extends Phaser.Scene {\nconstructor(config) {\nsuper(config);\n}\n\ninit(data) {}\npreload() {}\ncreate(data) {}\nupdate(time, delta) {}\n}\n
  • data : Parameters passed from adding new scene, or starting scene
"},{"location":"scene/#class","title":"Class","text":"
var MyScene = new Phaser.Class({\nExtends: Phaser.Scene,\n\ninitialize: function MyScene(config) {\nPhaser.Scene.call(this, config);\n},\n\ninit: function (data) {},\npreload: function () {},\ncreate: function (data) {},\nupdate: function (time, delta) {},\n});\n
  • data : Parameters passed from adding new scene, or starting scene
var MyGame = {};\n\nMyGame.Boot = function () {};\n\nMyGame.Boot.prototype.constructor = MyGame.Boot;\n\nMyGame.Boot.prototype = {\ninit: function (data) {},\npreload: function () {},\ncreate: function (data) {},\nupdate: function (time, delta) {},\n};\n
  • data : Parameters passed from adding new scene, or starting scene
"},{"location":"scene/#override","title":"Override","text":"
var demo = new Phaser.Scene(\"Demo\");\n\ndemo.init = function (data) {};\ndemo.preload = function () {};\ndemo.create = function (data) {};\ndemo.update = function (time, delta) {};\n
  • data : Parameters passed from adding new scene, or starting scene
"},{"location":"scene/#flow-chart","title":"Flow chart","text":"
graph TB\n\nsubgraph Stop\nSceneEventDestroy>\"scene.events: destroy\"]\nShutdown[\"Shutdown<br>Free game objects\"]\nend\n\nsubgraph Update\nSceneUpdate[\"Run: Every tick<br>scene.update()\"]\nSceneEventPauseSleep>\"scene.events: pause<br>scene.events: sleep\"]\nPause[\"Pause: render but no update<br>Sleep: no update, no render\"]\nSceneEventResumeWake>\"scene.events: resume<br>scene.events: wake\"]\nend\n\nsubgraph Create\nSceneEventStart>\"scene.events: start\"]\nSceneEventReady>\"scene.events: ready\"]\nSceneInit[\"scene.init()\"]\nScenePreLoad[\"Load assets<br>scene.preload()\"]\nSceneCreate[\"Create game objects<br>scene.create()\"]\nend\n\nStart((Start)) --> SceneEventStart\nSceneEventStart --> SceneEventReady\nSceneEventReady --> SceneInit\nSceneInit --> ScenePreLoad\nScenePreLoad --> SceneCreate\nSceneCreate --> SceneUpdate\nSceneUpdate --> SceneUpdate\nSceneUpdate --> |\"scene.scene.pause()<br>scene.scene.sleep()\"|SceneEventPauseSleep\nSceneEventPauseSleep --> Pause\nPause --> |\"scene.scene.resume()<br>scene.scene.wake()\"|SceneEventResumeWake\nSceneEventResumeWake --> SceneUpdate\n\nSceneUpdate --> |\"scene.scene.stop()<br>scene.scene.restart()\"|Stop\nPause --> |\"scene.scene.stop()<br>scene.scene.restart()\"|SceneEventDestroy\nSceneEventDestroy --> Shutdown\n\nShutdown --> |\"scene.scene.start()<br>scene.scene.launch()<br>scene.scene.restart()\"|SceneEventStart
  • Run : Update and render
  • Pause : Render but no update
  • Sleep : No update, no render
  • Stop : Shutdown

See also

  • Pause/resume
  • Stop
  • Main loop
"},{"location":"scene/#start","title":"Start","text":"
  1. Invoke scene.preload()
  2. Invoke scene.create()

scene.scene.restart() is equal to

scene.scene.stop();\nscene.scene.start();\n
"},{"location":"scene/#stop","title":"Stop","text":"
  • All game objects will be destroyed.
  • Registered events on game objects will also be clear, too.
  • Touch, keyboard and GamePad events will be clear.
  • Cameras will be destroyed.
  • Loader will be stopped.
  • Assets will be stored in global cache.
  • Events registered on scene plugin (scene.events.on) won't be clear.
"},{"location":"scene/#members","title":"Members","text":"
  • plugins
  • load : Loader
  • events : Local events
  • input : Touch, keyboard
  • tweens : Tween tasks
  • time : Timer
  • cameras : Camera
  • scene : scenePlugin
  • anims
  • physics : ArcadePhysics
  • matter :\u3000 MatterPhysics
  • registry : Global data manager across all scenes
    scene.registry.set(key, value);\nvar value = scene.registry.get(key);\n
  • data : Local data manager
    scene.data.set(key, value);\nvar value = scene.data.get(key);\n
  • sys
  • game
  • render
  • cache
  • sound
  • textures
  • add
  • make
  • children : DisplayList
    scene.children.bringToTop(child);\nscene.children.sendToBack(child);\nscene.children.moveUp(child);\nscene.children.moveDown(child);\nscene.children.moveUp(child);\nscene.children.moveTo(child, index);\nscene.children.moveAbove(child1, child2); // Move child1 above child2\nscene.children.moveBelow(child1, child2); // Move child1 below child2\nscene.children.swap(child1, child2);\n
  • lights

Preserve word in a scene.

"},{"location":"scene/#events","title":"Events","text":"
  • Start (Before scene.init())
    scene.events.on(\"start\", function () {});\n
  • Ready (After start)
    scene.events.on(\"ready\", function () {});\n
  • Every tick
    • Preupdate
      scene.events.on(\"preupdate\", function (time, delta) {});\n
    • Update
      scene.events.on(\"update\", function (time, delta) {});\n
    • Postupdate
      scene.events.on(\"postupdate\", function (time, delta) {});\n
    • Render
      scene.events.on(\"render\", function () {});\n
  • State changed
    • Pause (from scene.scene.pause())
      scene.events.on(\"pause\", function () {});\n
    • Resume (from scene.scene.resume())
      scene.events.on(\"resume\", function () {});\n
    • Sleep (from scene.scene.sleep())
      scene.events.on(\"sleep\", function () {});\n
    • Wake (from scene.scene.wake())
      scene.events.on(\"wake\", function () {});\n
    • Stop/shutdown (from scene.scene.stop())
      scene.events.on(\"shutdown\", function () {});\n
      • Free-up any resources that may be in use by this scene
  • Destroy (from scene.scene.remove())
    scene.events.on(\"destroy\", function () {});\n
  • Boot
    scene.events.on(\"boot\", function () {});\n
  • Game object added to scene
    • Add
      scene.events.on(\"addedtoscene\", function (gameObject, scene) {});\n
    • Remove
      scene.events.on(\"removedfromscene\", function (gameObject, scene) {});\n
"},{"location":"scenemanager/","title":"Scene manager","text":"

Scene manager plugin:

  • In each scene instance: scene.scene
"},{"location":"scenemanager/#add-new-scene","title":"Add new scene","text":"
var newScene = scene.scene.add(key, sceneConfig, autoStart, data);\n// var newScene = game.scene.add(key, sceneConfig, autoStart, data);\n
  • key : A unique key used to reference the Scene.
  • sceneConfig :
    • A scene class
    • A plain object
      {\ninit(data) {},\npreload() {},\ncreate(data) {},\nupdate(time, delta) {},\n\nextend: {\ndata: {},\n// ...\n},\n}\n
  • autoStart : Set true to start scene immediately after added.
  • data : Optional data object. This will be set as scene.settings.data and passed to scene.init.
"},{"location":"scenemanager/#load-scene-from-external-files","title":"Load scene from external files","text":"
  1. load script
    scene.load.script(key, url);\n
  2. add new scene
    scene.scene.add(key, sceneConfig, autoStart);\n// game.scene.add(key, sceneConfig, autoStart);\n
"},{"location":"scenemanager/#destroy-scene","title":"Destroy scene","text":"
scene.scene.remove(key);\n
  • Fires scene.events destroy
"},{"location":"scenemanager/#start-scene","title":"Start scene","text":"
  • Launch the given Scene and run it in parallel with this one
    scene.scene.launch(key, data);\n
  • Shutdown this Scene and run the given one
    scene.scene.start(key, data);\n
  • Restarts this Scene
    scene.scene.restart(data);\n
"},{"location":"scenemanager/#pauseresume-scene","title":"Pause/Resume scene","text":"
  • Pause : stops the update step but still renders
    scene.scene.pause(key);\n// scene.scene.pause();  // pause myself\n
    • Fires scene.events pause
  • Resume : starts the update loop again
    scene.scene.resume(key);\n// scene.scene.resume();  // resume myself\n
    • Fires scene.events resume
  • Sleep : no update, no render but doesn't shutdown
    scene.scene.sleep(key);\n// scene.scene.sleep();  // sleep myself\n
    • Fires scene.events sleep
  • Wake-up: starts update and render
    scene.scene.wake(key);\n// scene.scene.wake();  // wake-up myself\n
    • Fires scene.events wake
  • Makes this Scene sleep then starts the Scene given
    scene.scene.switch(key, data);\n
"},{"location":"scenemanager/#run-scene","title":"Run scene","text":"

Runs the given Scene, but does not change the state of this Scene.

If the given Scene is paused, it will resume it. If sleeping, it will wake it. If not running at all, it will be started.

scene.scene.run(key, data);\n
"},{"location":"scenemanager/#stop-scene","title":"Stop scene","text":"

Shutdown the Scene, clearing display list, timers, etc.

scene.scene.stop(key);\n// scene.scene.stop();  // stop myself\n
"},{"location":"scenemanager/#set-visible","title":"Set visible","text":"
scene.scene.setVisible(value, key);  // value: true/false\n// scene.scene.setVisible(value);    // set visible to myself\n
"},{"location":"scenemanager/#read-status","title":"Read status","text":"
var isSleep = scene.scene.isSleeping(key);\n// var isSleep = scene.scene.isSleeping();\n
var isPaused = scene.scene.isPaused(key);\n// var isPaused = scene.scene.isPaused();\n
var isActive = scene.scene.isActive(key);\n// var isActive = scene.scene.isActive();\n
var isVisible = scene.scene.isVisible(key);\n// var isVisible = scene.scene.isVisible();\n
Update/isActive Render/isVisible Run Pause Sleep

Pause/Sleep/Stop

  • Pause: Pause update stage.
  • Sleep: Pause update stage, and set scene invisible.
  • Stop: Shoutdown, clearing display list, timers, etc.
var status = scene.scene.getStatus(key);\n// var status = scene.scene.getStatus();\n
  • status :
    • Phaser.Scenes.PENDING, or 0
    • Phaser.Scenes.INIT, or 1
    • Phaser.Scenes.START, or 2
    • Phaser.Scenes.LOADING, or 3
    • Phaser.Scenes.CREATING, or 4
    • Phaser.Scenes.RUNNING, or 5
    • Phaser.Scenes.PAUSED, or 6
    • Phaser.Scenes.SLEEPING, or 7
    • Phaser.Scenes.SHUTDOWN, or 8
    • Phaser.Scenes.DESTROYED, or 9
"},{"location":"scenemanager/#get-scene","title":"Get scene","text":"
var scene = scene.scene.get(key);\n
"},{"location":"scenemanager/#order-of-scenes","title":"Order of scenes","text":"

Swaps the position of two scenes in the Scenes list.

scene.scene.swapPosition(keyA, keyB);\n// scene.scene.stop(keyA);\n
scene.scene.moveAbove(keyA, keyB);\n// scene.scene.moveAbove(keyA);\n

Scene B is directly above Scene A.

scene.scene.moveBelow(keyA, keyB);\n// scene.scene.moveBelow(keyA);\n

Scene B is directly below Scene A.

scene.scene.moveUp(keyA);\n// scene.scene.moveBelow();\n
scene.scene.moveDown(keyA);\n// scene.scene.moveDown();\n
scene.scene.bringToTop(keyA);\n// scene.scene.bringToTop();\n
scene.scene.sendToBack(keyA);\n// scene.scene.sendToBack();\n
"},{"location":"scenemanager/#transition","title":"Transition","text":"
scene.scene.transition({\ntarget: key,\n// data: null,\n// moveAbove: false,\n// moveBelow: false,\n\nduration: 1000,\n\n// remove: false,\n// sleep: false,\n// allowInput: false,\n\n// onStart: null,\n// onStartScope: scene,\n\n// onUpdate: null,\n// onUpdateScope: scene,\n})\n
  • target : The Scene key to transition to.
  • data : An object containing any data you wish to be passed to the target scenes init / create methods.
  • moveAbove. moveBelow : Move the target Scene to be above/below this current scene before the transition starts.
  • duration : Transition duration, in ms.
  • remove : Set true to remove this scene.
  • sleep : Set true to sleep this scene, set false to stop this scene.
  • allowInput : Set true to enable input system of current scene and target scene.
  • onStart, onStartScope : Invoked when transition start
    function(fromScene, toScene, duration) {\n\n}\n
    • fromScene : Current scene instance
    • toScene : Target scene instance
    • duration : Transition duration, in ms.
  • onUpdate ,onUpdateScope : Transition callback in each tick.
    function(progress) {\n\n}\n
    • progress : 0 ~ 1
"},{"location":"scenemanager/#execution-flow","title":"Execution flow","text":"
  1. Invoke scene.scene.transition method.
    • Current scene :
      • Fire 'transitionout' event.
        fromScene.events.on('transitionout', function(targetScene, duration){ });\n
      • Run transition's onUpdate callback every tick.
      • Current scene's update method is still running every tick.
    • Target scene :
      • Start target scene immediately.
      • Fire target scene's 'transitionstart' event. (Register this event in create stage)
        targetScene.events.on('transitionstart', function(fromScene, duration){ });\n
  2. When transition completed.
    • Current scene :
      • Remove or sleep current scene after transition completed.
    • Target scene :
      • Fire target scene's transitioncomplete event.
        targetScene.events.on('transitioncomplete', function(fromScene){ });\n
"},{"location":"scenemanager/#events","title":"Events","text":"
  • boot
    scene.events.on('transitioninit', function(fromScene, duration)){ });\n
  • start
    scene.events.on('transitionstart', function(fromScene, duration){ });\n
  • transition-out
    scene.events.on('transitionout', function(targetScene){ });\n
  • complete
    scene.events.on('transitioncomplete', function(fromScene){ });\n
  • wake : wake-up target scene if it was previously asleep
    scene.events.on('transitionwake', function(fromScene, duration){ });\n
"},{"location":"scenemanager/#system-scene","title":"System scene","text":"

A default empty Scene that lives outside of the Scene list, but can be used by plugins and managers that need access to a live Scene, without being tied to one.

var scene = scene.scene.get('__SYSTEM');\n

or

var scene = scene.scene.systemScene;\n
"},{"location":"scripttagloader/","title":"Script tag loader","text":""},{"location":"scripttagloader/#introduction","title":"Introduction","text":"

Load script tag in preload stage.

  • Author: Rex
  • Custom File of loader
"},{"location":"scripttagloader/#usage","title":"Usage","text":"

Sample code

"},{"location":"scripttagloader/#install-plugin","title":"Install plugin","text":""},{"location":"scripttagloader/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    var sceneConfig = {\n// ....\npack: {\nfiles: [{\ntype: 'plugin',\nkey: 'rexscripttagloaderplugin',\nurl: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexscripttagloaderplugin.min.js',\nstart: true\n}]\n}\n};\nclass MyScene extends Phaser.Scene {\nconstructor() {\nsuper(sceneConfig)\n}\n// ....\n\npreload() {\n// rexscripttagloaderplugin will be installed before preload(), but not added to loader yet\n// Call addToScene(scene) to add this await loader to loader of this scene\nthis.plugins.get('rexscripttagloaderplugin').addToScene(this);\n\nthis.load.rexScriptTag(url);\n}\n}\n
"},{"location":"scripttagloader/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ScriptTagLoaderPlugin from 'phaser3-rex-plugins/plugins/scripttagloader-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexScriptTagLoader',\nplugin: ScriptTagLoaderPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • In preload stage
    scene.load.rexScriptTag(url);\n
"},{"location":"scripttagloader/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ScriptTagLoader from 'phaser3-rex-plugins/plugins/scripttagloader.js';\n
  • Start loading task
    ScriptTagLoader.call(scene.load, url);\n// ScriptTagLoader.call(scene.load, url, availableTest);\n
"},{"location":"scripttagloader/#load-script-tag","title":"Load script tag","text":"

In preload stage:

this.load.rexScriptTag(url);\n// this.load.rexScriptTag(url, availableTest);\n

or

this.load.rexScriptTag({\nurl: url,\navailableTest: undefined\n});\n
  • availableTest : Callback invoked after loading script tag, optional.
    function() {        return true;\n}\n
    • Wait until availableTest return true.
"},{"location":"scripttagloader/#compare-with-script-loader","title":"Compare with script loader","text":"
  • Built-in script loader uses AJAX to load text as script, which might have CORS issue.
  • Script tag loader uses <script> tag to load script.
"},{"location":"scroller/","title":"Scroller","text":""},{"location":"scroller/#introduction","title":"Introduction","text":"

Drag content. Slow down when dragging released, pull back when out of bounds.

  • Author: Rex
  • Behavior of game object
"},{"location":"scroller/#live-demos","title":"Live demos","text":"
  • Scroller
"},{"location":"scroller/#usage","title":"Usage","text":"

Sample code

"},{"location":"scroller/#install-plugin","title":"Install plugin","text":""},{"location":"scroller/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexscrollerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexscrollerplugin.min.js', true);\n
  • Add scroller behavior
    var scroller = scene.plugins.get('rexscrollerplugin').add(gameObject, config);\n
"},{"location":"scroller/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ScrollerPlugin from 'phaser3-rex-plugins/plugins/scroller-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexScroller',\nplugin: ScrollerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add scroller behavior
    var scroller = scene.plugins.get('rexScroller').add(gameObject, config);\n
"},{"location":"scroller/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Scroller from 'phaser3-rex-plugins/plugins/scroller.js';\n
  • Add scroller behavior
    var scroller = new Scroller(gameObject, config);\n
"},{"location":"scroller/#create-instance","title":"Create instance","text":"
var scroller = scene.plugins.get('rexScroller').add(gameObject, {\nbounds: [\nbottomBound,\ntopBound\n],\nvalue: topBound,    // threshold: 10,\n// slidingDeceleration: 5000,\n// backDeceleration: 2000,\n\n// dragReverse: false,\n// dragRate: 1,\n\n// enable: true,\n// orientation: 'vertical',\n// pointerOutRelease: true,\n// rectBoundsInteractive: false,\n\n// valuechangeCallback: null,\n// valuechangeCallbackScope: null,\n\n// overmaxCallback: null,\n// overmaxCallbackScope: null,\n\n// overminCallback: null,\n// overminCallbackScope: null,\n});\n
  • bounds : An array of 2 values [bound0, bound1]
  • value : Initial value between bound0 and bound1
    • Map this value to position of content under event 'valuechange'
  • threshold : Minimal movement to scroll. Set 0 to scroll immediately.
  • slidingDeceleration : Deceleration of slow down when dragging released.
    • Set false to disable it.
  • backDeceleration : Deceleration of pull back when out of bounds.
    • Set false to disable it.
  • dragReverse :
    • false : Dragging up will decrease value, dragging down will increase value. Default behavior.
      • Use this mode when scrolling by position of game object.
    • true : Dragging up will increase value, dragging down will decrease value.
      • Use this mode when scrolling by camera.
  • dragRate : Rate of dragging distance/dragging speed. Default value is 1.
  • enable : Set true to get dragging events.
  • orientation :
    • 'vertical','v', 'y', or 0 : dragging on vertical/y axis.
    • 'horizontal','h', 'x', or 1 : dragging on horizontal/x axis.
  • pointerOutRelease : Set to true to release input control when pointer out of gameObject. Default value is true.
  • rectBoundsInteractive :
    • false : Detect scrolling by game object's touch input. Default behavior.
    • true : Detect scrolling by rectangle bounds of game object.
  • valuechangeCallback , valuechangeCallbackScope : Bind this callback to valuechange event
  • overminCallback , overmaxCallbackScope : Bind this callback to overmax event
  • overminCallback , overminCallbackScope : Bind this callback to overmin event
"},{"location":"scroller/#set-bounds","title":"Set bounds","text":"
this.setBounds(bounds);  // bounds: [bound0, bound1]\n// this.setBounds(bound0, bound1);\n
"},{"location":"scroller/#set-deceleration","title":"Set deceleration","text":"
  • Deceleration of slow down when dragging released
    scroller.setSlidingDeceleration(dec);\n
    • Disable
      scroller.setSlidingDeceleration(false);\n
  • Deceleration of pull back when out of bounds
    scroller.setBackDeceleration(dec);\n
    • Disable
      scroller.setBackDeceleration(false);\n
"},{"location":"scroller/#get-value","title":"Get value","text":"
var value = scroller.value;\n
"},{"location":"scroller/#set-value","title":"Set value","text":"
  • Set value
    scroller.value = newValue;\n// scroller.setValue(newValue);\n
  • Set value, clamp between minValue and maxValue
    scroller.setValue(newValue, true);\n
  • Add value
    scroller.value += inc;\n// scroller.addValue(inc);\n
  • Add value, clamp between minValue and maxValue
    scroller.addValue(inc, true);\n

Fires valuechange event if new value is not equal to current value.

"},{"location":"scroller/#events","title":"Events","text":"
  • Value changed
    scroller.on('valuechange', function(newValue, prevValue){ /* ... */ });\n
    • Set position of content under this event
  • Value out of max/min bound
    scroller.on('overmax', function(newValue, prevValue){ /* ... */ });\n
    scroller.on('overmin', function(newValue, prevValue){ /* ... */ });\n
  • On drag start
    scroller.on('dragstart', function() { /* ... */ });\n
  • On drag end
    scroller.on('dragend', function() { /* ... */ });\n
"},{"location":"scroller/#drag","title":"Drag","text":""},{"location":"scroller/#drag-enable","title":"Drag enable","text":"
  • Get
    var enable = scroller.enable;\n
  • Set
    scroller.setEnable();\n// scroller.setEnable(enable);  // enable: true, or false\n
    or
    scroller.enable = enable; // enable: true, or false\n
  • Toggle
    scroller.toggleEnable();\n
"},{"location":"scroller/#is-dragging","title":"Is dragging","text":"
var isDragging = scroller.isDragging;\n
"},{"location":"scroller/#state-machine","title":"State machine","text":"
graph TB\n\nIDLE[\"Idle\"] --> |Drag| DRAG[\"Dragging<br>event 'valuechange'\"]\nDRAG --> |Release| OnRelease{\"Under bounds?\"}\n\nOnRelease --> |Yes| SLIDE[\"Sliding<br>Sliding-deceleration\"]\nSLIDE --> |Stop| IDLE\nSLIDE --> |Drag| DRAG\n\nOnRelease --> |No| BACK[\"Pull back to bounds<br>Back-deceleration\"]\nBACK --> |Stop| IDLE\nBACK --> |Drag| DRAG
  • Get state
    var state = scroller.state;\n
    • 'IDLE' : No dragging, no sliding
    • 'DRAG' : Dragging
    • 'SLIDE' : Sliding when dragging released
    • 'BACK' : Sliding back to bound when out of bound
"},{"location":"sequence/","title":"Sequence","text":""},{"location":"sequence/#introduction","title":"Introduction","text":"

Run sequence commands in array.

  • Author: Rex
  • Object
"},{"location":"sequence/#live-demos","title":"Live demos","text":"
  • Sequence
"},{"location":"sequence/#usage","title":"Usage","text":"

Sample code

"},{"location":"sequence/#install-plugin","title":"Install plugin","text":""},{"location":"sequence/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexsequenceplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexsequenceplugin.min.js', true);\n
  • Create sequence instance
    var seq = this.plugins.get('rexsequenceplugin').add(config);\n
"},{"location":"sequence/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SequencePlugin from 'phaser3-rex-plugins/plugins/sequence-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexSequence',\nplugin: SequencePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create sequence instance
    var seq = this.plugins.get('rexSequence').add(config);\n
"},{"location":"sequence/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Sequence from 'phaser3-rex-plugins/plugins/sequence.js';\n
  • Create sequence instance
    var seq = new Sequence(config);\n
"},{"location":"sequence/#create-sequence-instance","title":"Create sequence instance","text":"
var seq = this.plugins.get('rexSequence').add({\n// yoyo: false,\n// repeat: 0, \n// loop: false\n});\n
  • yoyo : Reverse sequence when it reaches the end
  • repeat : Repeat count
  • loop : Repeat forever
"},{"location":"sequence/#load-commands","title":"Load commands","text":"
seq.load(commands, actionScope);\n
  • Format of command :
    [fnName, param0, param1, ...]\n
  • Commands in nested array :
    [\ncommand0,\ncommand1\n[\ncommand2,\ncommand3\n]\n]\n
  • ActionScope

Format of command is the same as run-command.

"},{"location":"sequence/#run-commands","title":"Run commands","text":"
seq.start();\n
  • Run command :
    var eventEmitter = actionScope[fnName].call(actionScope, param0, param1 ...);\n
    • Return an event emitter to pause the sequence, otherwise run next command
    • Sequence will continue when that event emitter fires complete event
"},{"location":"sequence/#stop","title":"Stop","text":"
seq.stop();\n
"},{"location":"sequence/#events","title":"Events","text":"
  • On sequence completed :
    seq.on('complete', function(actionScope, seq){ });\n
"},{"location":"sequence/#action-of-commands","title":"Action of commands","text":"

Action of commands, extended from Phaser.Events.EventEmitter.

class ActionKlass extends Phaser.Events.EventEmitter {\nconstructor(scene) {\nsuper();\n\nthis.scene = scene;\nthis.myConsole = scene.add.text(100, 100, '');\n\nthis['wait-click'] = this.waitClick;\nthis['wait-time'] = this.waitTime;\n}\n\n// callbacks\nprint(msg) {\nthis.myConsole.setText(msg);\n// return undefined to run next command\n}\n\nwaitClick() {\nthis.scene.input.once('pointerup', this.complete, this);\nreturn this;  // return eventEmitter to pause the sequence\n}\n\nwaitTime(delay) {\nthis.scene.time.delayedCall(delay * 1000, this.complete, [], this);\nreturn this;  // return eventEmitter to pause the sequence\n}\n\ncomplete() {\nthis.emit('complete');  // resume sequence\n}\n}\nvar actionScope = new ActionKlass(scene);\n

Now this scope supports 3 commands

  • print(msg): ['print', msg]
  • waitClick(): ['wait-click']
  • waitTime(delay): ['wait-time', delay]
"},{"location":"sequence/#state","title":"State","text":"
var state = seq.state;\n
  • 0 : Idle
  • 1 : Run
  • 2 : Last command
  • 3 : Completed
var completed = seq.completed; // seq.state === 3\n
"},{"location":"sequence/#other-properties","title":"Other properties","text":"
  • Yoyo
    • Get
      var yoyo = seq.yoyo;\n
    • Set
      seq.setYoyo();\nseq.setYoyo(fals);\n// seq.yoyo = yoyo;\n
  • Repeat
    • Get
      var repeat = seq.repeat;\n
    • Set
      seq.setRepeat(count);\n
  • Loop
    • Get
      var loop = seq.loop;\n
    • Set
      seq.setLoop();\nseq.setLoop(fals);\n// seq.loop = loop;\n
"},{"location":"shader-barrel/","title":"Barrel","text":"

Note

Phaser3.60 has a built-in barrel effect.

"},{"location":"shader-barrel/#introduction","title":"Introduction","text":"

Barrel post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-barrel/#live-demos","title":"Live demos","text":"
  • Barrel
"},{"location":"shader-barrel/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-barrel/#install-plugin","title":"Install plugin","text":""},{"location":"shader-barrel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbarrelpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbarrelpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexbarrelpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexbarrelpipelineplugin').add(camera, config);\n
"},{"location":"shader-barrel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BarrelPipelinePlugin from 'phaser3-rex-plugins/plugins/barrelpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBarrelPipeline',\nplugin: BarrelPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexBarrelPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexBarrelPipeline').add(camera, config);\n
"},{"location":"shader-barrel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import BarrelPostFx from 'phaser3-rex-plugins/plugins/barrelpipeline.js';\nvar config = {\n// ...\npipeline: [BarrelPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(BarrelPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(BarrelPostFx);\n
"},{"location":"shader-barrel/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 barrel effect.
    var pipelineInstance = scene.plugins.get('rexBarrelPipeline').add(gameObject, {\n// shrink: false,\n// center: {\n//    x: windowWidth / 2,\n//    y: windowHeight / 2\n//}\n// radius: 0,\n// power: 0.5,\n// intensity: 1,\n\n// name: 'rexBarrelPostFx'\n});\n
    • shrink :
      • false : Fish-eye effect
      • true : Anti fish-eye effect.
    • center.x, center.y : Local position of barrel center.
    • radius : Barrel radius.
    • power : 0~1.
    • intensity : 0(original) ~ 1(barrel). Default value is 1.
  • Apply effect to camera. A camera only can add 1 barrel effect.
    var pipelineInstance = scene.plugins.get('rexBarrelPipeline').add(camera, config);\n
"},{"location":"shader-barrel/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexBarrelPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexBarrelPipeline').remove(camera);\n
"},{"location":"shader-barrel/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexBarrelPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexBarrelPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexBarrelPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexBarrelPipeline').get(camera);\n
"},{"location":"shader-barrel/#shrink-mode","title":"Shrink mode","text":"
  • Get
    var shrinkMode = pipelineInstance.shrinkMode;\n
  • Set
    pipelineInstance.setShrinkMode(true);\n// pipelineInstance.setShrinkMode(false);\n
"},{"location":"shader-barrel/#radius","title":"Radius","text":"
  • Get
    var radius = pipelineInstance.radius;\n
  • Set
    pipelineInstance.radius = radius;\n// pipelineInstance.radius += value;\n
    or
    pipelineInstance.setRadius(radius);\n
"},{"location":"shader-barrel/#power","title":"Power","text":"
  • Get
    var power = pipelineInstance.power;\n
  • Set
    pipelineInstance.power = power;\n
    or
    pipelineInstance.setPower(power);\n
"},{"location":"shader-barrel/#intensity","title":"Intensity","text":"
  • Get
    var intensity = pipelineInstance.intensity;\n
  • Set
    pipelineInstance.intensity = intensity;\n// pipelineInstance.intensity += value;\n
    or
    pipelineInstance.setIntensity(radius);\n
    • intensity : 0(original) ~ 1(barrel)
"},{"location":"shader-barrel/#center-position","title":"Center position","text":"

Default value is center of window.

  • Get
    var x = pipelineInstance.centerX;\nvar y = pipelineInstance.centerY;\n
  • Set
    pipelineInstance.centerX = x;\npipelineInstance.centerY = y;\n
    or
    pipelineInstance.setCenter(x, y);\n// pipelineInstance.setCenter();   // set to center of window\n
"},{"location":"shader-builtin/","title":"Effects","text":""},{"location":"shader-builtin/#introduction","title":"Introduction","text":"

Built-in pre-fx, and post-fx shader effects.

  • Barrel Distortion : A nice pinch / bulge distortion effect.
  • Bloom : Add bloom to any Game Object, with custom offset, blur strength, steps and color.
  • Blur : 3 different levels of gaussian blur (low, medium and high) and custom distance and color.
  • Bokeh / Tilt Shift : A bokeh and tiltshift effect, with intensity, contrast and distance settings.
  • Circle Outline : Add a circular ring around any Game Object, useful for masking / avatar frames, with custom color, width and background color.
  • Color Matrix : Add a ColorMatrix to any Game Object with access to all of its methods, such as sepia, greyscale, lsd and lots more.
  • Glow : Add a smooth inner or outer glow, with custom distance, strength and color.
  • Displacement : Use a displacement texture, such as a noise texture, to drastically (or subtly!) alter the appearance of a Game Object.
  • Gradient : Draw a gradient between two colors across any Game Object, with optional 'chunky' mode for classic retro style games.
  • Pixelate : Make any Game Object appear pixelated, to a varying degree.
  • Shine : Run a 'shine' effect across a Game Object, either additively or as part of a reveal.
  • Shadow : Add a drop shadow behind a Game Object, with custom depth and color.
  • Vignette : Apply a vignette around a Game Object, with custom offset position, radius and color.
  • Wipe / Reveal : Set a Game Object to 'wipe' or 'reveal' with custom line width, direction and axis of the effect.

Texture-based Game Objects also support Pre FX, including: Image, Sprite, TileSprite, Text, RenderTexture, Video.

All Game Objects and camera support Post FX. These are effects applied after the Game Object has been rendered.

  • Author: Richard Davey
  • Pre-fx, and Post-fx shader effects

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-builtin/#live-demos","title":"Live demos","text":"
  • Official demos
"},{"location":"shader-builtin/#usage","title":"Usage","text":""},{"location":"shader-builtin/#barrel","title":"Barrel","text":"
  • Add pre-fx to game object
    // gameObject.preFX.setPadding(padding);\nvar effect = gameObject.preFX.addBarrel(amount);\n
    • padding : The amount of padding to add to this Game Object, in pixels.
      • Used when amount is larger than 1.
    • amount : The amount of distortion applied to the barrel effect.
      • 1 : No distortion
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addBarrel(amount);\n
    var effect = camera.postFX.addBarrel(amount);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.amount = amount;\n
"},{"location":"shader-builtin/#bloom","title":"Bloom","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addBloom(color, offsetX, offsetY, blurStrength, strength, steps);\n
    • color : The color of the Bloom, as a hex value.
    • offsetX, offsetY : The horizontal/vertical offset of the bloom effect. Default value is 1.
    • blurStrength , strength : The strength of the blur/blend process of the bloom effect. Default value is 1.
    • steps : The number of steps to run the Bloom effect for. This value should always be an integer. Default value is 4.
      • The higher the value, the smoother the Bloom, but at the cost of exponentially more gl operations.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addBloom(color, offsetX, offsetY, blurStrength, strength, steps);\n
    var effect = camera.postFX.addBloom(color, offsetX, offsetY, blurStrength, strength, steps);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.color = color;  // hex value\neffect.offsetX = offsetX;\neffect.offsetY = offsetY;\neffect.blurStrength = blurStrength;\neffect.strength = strength;\neffect.steps = steps; // integer\n
"},{"location":"shader-builtin/#blur","title":"Blur","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addBlur(quality, x, y, strength, color, steps);\n
    • quality : The quality of the blur effect. Default value is 0.
      • 0 : Low Quality
      • 1 : Medium Quality
      • 2 : High Quality
    • x, y : The horizontal/vertical offset of the blur effect. Default value is 2
    • strength : The strength of the blur effect. Default value is 1.
    • color : The color of the blur, as a hex value. Default value is 0xffffff.
    • steps : The number of steps to run the blur effect for. This value should always be an integer.
      • The higher the value, the smoother the blur, but at the cost of exponentially more gl operations.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addBlur(quality, x, y, strength, color, steps);\n
    var effect = camera.postFX.addBlur(quality, x, y, strength, color, steps);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.quality = quality;\neffect.x = x;\neffect.y = y;\neffect.strength = strength;\neffect.color = color;\neffect.steps = steps;\n
"},{"location":"shader-builtin/#bokeh","title":"Bokeh","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addBokeh(radius, amount, contrast);\n
    • radius : The radius of the bokeh effect. Default value is 0.5.
    • amount : The amount of the bokeh effect. Default value is 1.
    • contrast : The color contrast of the bokeh effect. Default value is 0.2.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addBlur(quality, x, y, strength, color, steps);\n
    var effect = camera.postFX.addBokeh(radius, amount, contrast);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.radius = radius;\neffect.amount = amount;\neffect.contrast = contrast;\n
"},{"location":"shader-builtin/#tilt-shift","title":"Tilt Shift","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addTiltShift(radius, amount, contrast, blurX, blurY, strength);\n
    • radius : The radius of the bokeh effect. Default value is 0.5.
    • amount : The amount of the bokeh effect. Default value is 1.
    • contrast : The color contrast of the bokeh effect. Default value is 0.2.
    • blurX, blurY : The amount of horizontal/vertical blur.
    • strength : The strength of the blur.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addTiltShift(radius, amount, contrast, blurX, blurY, strength);\n
    var effect = camera.postFX.addTiltShift(radius, amount, contrast, blurX, blurY, strength);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.radius = radius;\neffect.amount = amount;\neffect.contrast = contrast;\neffect.blurX = blurX;\neffect.blurY = blurY;\neffect.strength = strength;\n
"},{"location":"shader-builtin/#circle-outline","title":"Circle Outline","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addCircle(thickness, color, backgroundColor, scale, feather);\n
    • thickness : The width of the circle around the texture, in pixels. Default value is 8.
    • color : The color of the circular ring, given as a number value. Default value is 0xfeedb6.
    • backgroundColor : The color of the background, behind the texture, given as a number value. Default value is 0xff0000.
    • scale : The scale of the circle. Default value is 1.
      • 1 : Full size of the underlying texture.
    • feather : The amount of feathering to apply to the circle from the ring. Default value is 0.005.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addCircle(thickness, color, backgroundColor, scale, feather);\n
    var effect = camera.postFX.addCircle(thickness, color, backgroundColor, scale, feather);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.thickness = thickness;\neffect.color = color;\neffect.backgroundColor = backgroundColor;\neffect.backgroundAlpha = backgroundAlpha;\neffect.scale = scale;\neffect.feather = feather;\n
"},{"location":"shader-builtin/#colormatrix","title":"ColorMatrix","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addColorMatrix();\n
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addColorMatrix();\n
    var effect = camera.postFX.addColorMatrix();\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Methods
    • Brightness : Changes the brightness of this ColorMatrix by the given amount.
      effect.brightness(value, multiply);\n
      • value : The amount of brightness to apply to this ColorMatrix. 0(black)~1. Default value is 0.
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Saturate : Changes the saturation of this ColorMatrix by the given amount.
      effect.saturate(value, multiply);\n
      • value : The amount of saturation to apply to this ColorMatrix. Default value is 0.
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Desaturate : Desaturates this ColorMatrix (removes color from it).
      effect.desaturate(value, multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Hue : Rotates the hues of this ColorMatrix by the value given.
      effect.hue(rotation, multiply);\n
      • rotation : The amount of hue rotation to apply to this ColorMatrix, in degrees. Default value is 0.
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Grayscale : Sets this ColorMatrix to be grayscale.
      effect.grayscale(value, multiply);\n
      • value : The grayscale scale 0(black)~1. Default value is 1.
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • BlackWhite : Sets this ColorMatrix to be black and white.
      effect.blackWhite(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Contrast : Change the contrast of this ColorMatrix by the amount given.
      effect.contrast(value, multiply);\n
      • value : The amount of contrast to apply to this ColorMatrix. Default value is 0.
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Negative : Converts this ColorMatrix to have negative values.
      effect.negative(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • DesaturateLuminance : Apply a desaturated luminance to this ColorMatrix.
      effect.desaturateLuminance(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Sepia : Applies a sepia tone to this ColorMatrix.
      effect.sepia(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Night : Applies a night vision tone to this ColorMatrix.
      effect.night(intensity, multiply);\n
      • intensity : The intensity of this effect. Default value is 0.1.
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • LSD : Applies a trippy color tone to this ColorMatrix.
      effect.lsd(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Brown : Applies a brown tone to this ColorMatrix.
      effect.brown(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • VintagePinhole : Applies a vintage pinhole color effect to this ColorMatrix.
      effect.vintagePinhole(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Kodachrome : Applies a kodachrome color effect to this ColorMatrix.
      effect.kodachrome(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Technicolor : Applies a technicolor color effect to this ColorMatrix.
      effect.technicolor(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Polaroid : Applies a polaroid color effect to this ColorMatrix.
      effect.polaroid(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • ShiftToBGR : Shifts the values of this ColorMatrix into BGR order.
      effect.shiftToBGR(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
"},{"location":"shader-builtin/#displacement","title":"Displacement","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addDisplacement(texture, x, y);\n
    • texture : The unique string-based key of the texture to use for displacement, which must exist in the Texture Manager. Default value is '__WHITE'.
      • You can only use a whole texture, not a frame from a texture atlas or sprite sheet.
    • x, y : The amount of horizontal/vertical displacement to apply. Default value is 0.005.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addDisplacement(texture, x, y);\n
    var effect = camera.postFX.addDisplacement(texture, x, y);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.x = x;\neffect.y = y;    
  • Methods
    • Set texture
      effect.setTexture(key);\n
"},{"location":"shader-builtin/#glow","title":"Glow","text":"
  • Add pre-fx to game object
    // gameObject.preFX.setPadding(padding);\nvar effect = gameObject.preFX.addGlow(color, outerStrength, innerStrength, knockout);\n
    • padding : The amount of padding to add to this Game Object, in pixels.
      • Used when amount is larger than 1.
    • color : The color of the glow effect as a number value. Default value is 0xffffff.
    • outerStrength, innerStrength : The strength of the glow outward/inward from the edge of the Sprite. Default value is 4/0.
    • knockout :
      • true : Only the glow is drawn
      • false : Draw glow and texture. Default behavior.
    • quality : Only available for PostFX. Sets the quality of this Glow effect. Default is 0.1. Cannot be changed post-creation.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addGlow(color, outerStrength, innerStrength, knockout, quality, distance);\n
    var effect = camera.postFX.addGlow(color, outerStrength, innerStrength, knockout, quality, distance);\n
    • quality : Sets the quality of this Glow effect. Default is 0.1. Cannot be changed post-creation.
    • distance : Sets the distance of this Glow effect. Default is 10. Cannot be changed post-creation.
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.color = color;\neffect.outerStrength = outerStrength;\neffect.innerStrength = innerStrength;\neffect.knockout = knockout;\n
"},{"location":"shader-builtin/#gradient","title":"Gradient","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addGradient(color1, color2, alpha, fromX, fromY, toX, toY, size);\n
    • color1, color2 : The first/second gradient color, given as a number value. Default values are 0xff0000/0x00ff00.
    • alpha : The alpha value of the gradient effect.
    • fromX, fromY : The horizontal/vertical position the gradient will start from. Value between 0 and 1.
    • toX, toY : The horizontal/vertical position the gradient will end at. Value between 0 and 1.
    • size : How many 'chunks' the gradient is divided in to, as spread over the entire height of the texture.
      • 0 : Smooth gradient. Default behavior.
      • Others : Retro chunky effect.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addGradient(color1, color2, alpha, fromX, fromY, toX, toY, size);\n
    var effect = camera.postFX.addGradient(color1, color2, alpha, fromX, fromY, toX, toY, size);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.color1 = color1;\neffect.color2 = color2;\neffect.alpha = alpha;\neffect.fromX = fromX;\neffect.fromY = fromY;\neffect.toX = toX;\neffect.toY = toY;\neffect.size = size;\n
"},{"location":"shader-builtin/#pixelate","title":"Pixelate","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addPixelate(amount);\n
    • amount : The amount of pixelation to apply, in pixels.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addPixelate(amount);\n
    var effect = camera.postFX.addPixelate(amount);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.amount = amount;\n
"},{"location":"shader-builtin/#shadow","title":"Shadow","text":"
  • Add pre-fx to game object
    // gameObject.preFX.setPadding(padding);\nvar effect = gameObject.preFX.addShadow(x, y, decay, power, color, samples, intensity);\n
    • padding : The amount of padding to add to this Game Object, in pixels.
      • Used when amount is larger than 1.
    • x, y : The horizontal/vertical offset of the shadow effect. Default value is 0.
    • decay : The amount of decay for shadow effect. Default value is 0.1.
    • power : The power of the shadow effect. Default value is 1.
    • color : The color of the shadow. Default value is 0x000000.
    • samples : The number of samples that the shadow effect will run for. An integer between 1 and 12.
    • intensity : The intensity of the shadow effect. Default value is 1.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addShadow(x, y, decay, power, color, samples, intensity);\n
    var effect = camera.postFX.addShadow(x, y, decay, power, color, samples, intensity);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.x = x;\neffect.y = y;\neffect.decay = decay;\neffect.power = power;\neffect.color = color;\neffect.samples = samples;\neffect.intensity = intensity;\n
"},{"location":"shader-builtin/#shine","title":"Shine","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addShine(speed, lineWidth, gradient, reveal);\n
    • speed : The speed of the Shine effect. Default value is 0.5.
    • lineWidth : The line width of the Shine effect. Default value is 0.5.
    • gradient : The gradient of the Shine effect. Default value is 3.
    • reveal : Does this Shine effect reveal or get added to its target?
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addShine(speed, lineWidth, gradient, reveal);\n
    var effect = camera.postFX.addShine(speed, lineWidth, gradient, reveal);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.speed = speed;\neffect.lineWidth = lineWidth;\neffect.gradient = gradient;\neffect.reveal = reveal;\n
"},{"location":"shader-builtin/#vignette","title":"Vignette","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addVignette(x, y, radius, strength);\n
    • x, y : The horizontal/vertical offset of the vignette effect. Value is between 0 and 1. Default value is 0.5.
    • radius : The radius of the vignette effect. Value is between 0 and 1. Default value is 0.5.
    • strength : The strength of the vignette effect. Default value is 0.5.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addVignette(x, y, radius, strength);\n
    var effect = camera.postFX.addVignette(x, y, radius, strength);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.x = x;\neffect.y = y;\neffect.radius = radius;\neffect.strength = strength;\n
"},{"location":"shader-builtin/#wipe","title":"Wipe","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addWipe(wipeWidth, direction, axis);\n
    • wipeWidth : The width of the wipe effect. Value is between 0 and 1. Default value is 0.1.
    • direction : The direction of the wipe effect.
      • 0 : Left to right, or top to bottom
      • 1 : Right to left, or bottom to top
    • axis : The axis of the wipe effect.
      • 0 : Left to right, or right to left
      • 1 : Bottom to top, or top to bottom
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addWipe(wipeWidth, direction, axis);\n
    var effect = camera.postFX.addWipe(wipeWidth, direction, axis);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.progress = t; // 0~1\neffect.wipeWidth = wipeWidth;\neffect.direction = direction;  // 0, 1\neffect.axis = axis;  // 0, 1    \n
"},{"location":"shader-builtin/#reveal","title":"Reveal","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addReveal(wipeWidth, direction, axis);\n
    • wipeWidth : The width of the wipe effect. Value is between 0 and 1. Default value is 0.1.
    • direction : The direction of the wipe effect.
      • 0 : Left to right, or top to bottom
      • 1 : Right to left, or bottom to top
    • axis : The axis of the wipe effect.
      • 0 : Left to right, or right to left
      • 1 : Bottom to top, or top to bottom
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addReveal(wipeWidth, direction, axis);\n
    var effect = camera.postFX.addReveal(wipeWidth, direction, axis);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.progress = t; // 0~1\neffect.wipeWidth = wipeWidth;\neffect.direction = direction;  // 0, 1\neffect.axis = axis;  // 0, 1\n
"},{"location":"shader-builtin/#remove-all-effects","title":"Remove all effects","text":"

gameObject.preFX.clear();\n
gameObject.postFX.clear();\n
camera.postFX.clear();\n

"},{"location":"shader-builtin/#disable-all-effects","title":"Disable all effects","text":"

gameObject.preFX.disable();\n// gameObject.preFX.disable(true);  // Also remove all effects\n
gameObject.postFX.disable();\n// gameObject.postFX.disable(true);  // Also remove all effects\n
camera.postFX.disable();\n// camera.postFX.disable(true);  // Also remove all effects\n

"},{"location":"shader-colorreplace/","title":"Color replace","text":""},{"location":"shader-colorreplace/#introduction","title":"Introduction","text":"

Replace color post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-colorreplace/#live-demos","title":"Live demos","text":"
  • Color replace
"},{"location":"shader-colorreplace/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-colorreplace/#install-plugin","title":"Install plugin","text":""},{"location":"shader-colorreplace/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcolorreplacepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcolorreplacepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexcolorreplacepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexcolorreplacepipelineplugin').add(camera, config);\n
"},{"location":"shader-colorreplace/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ColorReplacePipelinePlugin from 'phaser3-rex-plugins/plugins/colorreplacepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexColorReplacePipeline',\nplugin: ColorReplacePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexColorReplacePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexColorReplacePipeline').add(camera, config);\n
"},{"location":"shader-colorreplace/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import ColorReplacePostFx from 'phaser3-rex-plugins/plugins/colorreplacepipeline.js';\nvar config = {\n// ...\npipeline: [ColorReplacePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(ColorReplacePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(ColorReplacePostFx);\n
"},{"location":"shader-colorreplace/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 colorreplace effect.
    var pipelineInstance = scene.plugins.get('rexColorReplacePipeline').add(gameObject, {\noriginalColor: 0xFF0000,\nnewColor: 0x000000,\n// epsilon: 0.4,\n\n// name: 'rexColorReplacePostFx'\n});\n
    • originalColor : The color (0xRRGGBB) that will be changed.
    • newColor : The resulting color (0xRRGGBB).
    • epsilon : Tolerance/sensitivity of the floating-point comparison between colors (lower = more exact, higher = more inclusive)
  • Apply effect to camera. A camera only can add 1 colorreplace effect.
    var pipelineInstance = scene.plugins.get('rexColorReplacePipeline').add(camera, config);\n
"},{"location":"shader-colorreplace/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexColorReplacePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexColorReplacePipeline').remove(camera);\n
"},{"location":"shader-colorreplace/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexColorReplacePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexColorReplacePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexColorReplacePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexColorReplacePipeline').get(camera);\n
"},{"location":"shader-colorreplace/#original-color","title":"Original color","text":"
  • Get
    var color = pipelineInstance.originalColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    pipelineInstance.setOriginalColor(value);\n
    pipelineInstance.originalColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"shader-colorreplace/#new-color","title":"New color","text":"
  • Get
    var color = pipelineInstance.newColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    pipelineInstance.setNewColor(value);\n
    pipelineInstance.newColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"shader-colorreplace/#epsilon","title":"Epsilon","text":"
  • Get
    var epsilon = pipelineInstance.epsilon;\n
  • Set
    pipelineInstance.epsilon = epsilon;\n// pipelineInstance.epsilon += value;\n
    or
    pipelineInstance.setEpsilon(value);\n
"},{"location":"shader-crossstitching/","title":"Cross-stitching","text":""},{"location":"shader-crossstitching/#introduction","title":"Introduction","text":"

Cross-stitching post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-crossstitching/#live-demos","title":"Live demos","text":"
  • Cross-stitching
"},{"location":"shader-crossstitching/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-crossstitching/#install-plugin","title":"Install plugin","text":""},{"location":"shader-crossstitching/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcrossstitchingpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcrossstitchingpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexcrossstitchingpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexcrossstitchingpipelineplugin').add(camera, config);\n
"},{"location":"shader-crossstitching/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CrossStitchingPipelinePlugin from 'phaser3-rex-plugins/plugins/crossstitchingpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCrossStitchingPipeline',\nplugin: CrossStitchingPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexCrossStitchingPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexCrossStitchingPipeline').add(camera, config);\n
"},{"location":"shader-crossstitching/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import CrossStitchingPostFx from 'phaser3-rex-plugins/plugins/crossstitchingpipeline.js';\nvar config = {\n// ...\npipeline: [CrossStitchingPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(CrossStitchingPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(CrossStitchingPostFx);\n
"},{"location":"shader-crossstitching/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 cross-stitching effect.
    var pipelineInstance = scene.plugins.get('rexCrossStitchingPipeline').add(gameObject, {\n// stitchingWidth: 6,\n// stitchingHeight: 6,\n// brightness: 0,\n\n// name: 'rexCrossStitchingPostFx'\n});\n
    • stitchingWidth, stitchingHeight : Stitching size.
    • brightness : Brightness of stitching edges
  • Apply effect to camera. A camera only can add 1 cross-stitching effect.
    var pipelineInstance = scene.plugins.get('rexCrossStitchingPipeline').add(camera, config);\n
"},{"location":"shader-crossstitching/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexCrossStitchingPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexCrossStitchingPipeline').remove(camera);\n
"},{"location":"shader-crossstitching/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexCrossStitchingPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexCrossStitchingPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexCrossStitchingPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexCrossStitchingPipeline').get(camera);\n
"},{"location":"shader-crossstitching/#stitching-size","title":"Stitching size","text":"
  • Get
    var stitchingWidth = pipelineInstance.stitchingWidth;\nvar stitchingHeight = pipelineInstance.stitchingHeight;\n
  • Set
    pipelineInstance.stitchingWidth = stitchingWidth;\npipelineInstance.stitchingHeight = stitchingHeight;\n// pipelineInstance.stitchingWidth += value;\n// pipelineInstance.stitchingHeight += value;\n
    or
    pipelineInstance.setStitchingWidth(stitchingWidth);\npipelineInstance.setStitchingHeight(stitchingHeight);\npipelineInstance.setStitchingSize(stitchingWidth, stitchingHeight);\n
"},{"location":"shader-crossstitching/#brightness","title":"Brightness","text":"
  • Get
    var brightness = pipelineInstance.brightness;\n
  • Set
    pipelineInstance.brightness = brightness;\n// pipelineInstance.brightness += value;\n
    or
    pipelineInstance.setBrightness(radius);\n
    • brightness : 0(black) ~ 1(white)
"},{"location":"shader-crt/","title":"CRT","text":""},{"location":"shader-crt/#introduction","title":"Introduction","text":"

CRT post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-crt/#live-demos","title":"Live demos","text":"
  • CRT
"},{"location":"shader-crt/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-crt/#install-plugin","title":"Install plugin","text":""},{"location":"shader-crt/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcrtpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcrtpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexcrtpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexcrtpipelineplugin').add(camera, config);\n
"},{"location":"shader-crt/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CrtPipelinePlugin from 'phaser3-rex-plugins/plugins/crtpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCrtPipeline',\nplugin: CrtPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexCrtPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexCrtPipeline').add(camera, config);\n
"},{"location":"shader-crt/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import CrtPostFx from 'phaser3-rex-plugins/plugins/crtpipeline.js';\nvar config = {\n// ...\npipeline: [CrtPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(CrtPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(CrtPostFx);\n
"},{"location":"shader-crt/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 crt effect.
    var pipelineInstance = scene.plugins.get('rexCrtPipeline').add(gameObject, {\n// warpX: 0.75,\n// warpY: 0.75,\n// scanLineStrength: 0.2,\n// scanLineWidth: 1024,\n\n// name: 'rexCrtPostFx'\n});\n
    • warpX, warpY : Horizontal and Vertical warp.
    • scanLineStrength, scanLineWidth : Scan line parameters.
  • Apply effect to camera. A camera only can add 1 crt effect.
    var pipelineInstance = scene.plugins.get('rexCrtPipeline').add(camera, config);\n
"},{"location":"shader-crt/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexCrtPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexCrtPipeline').remove(camera);\n
"},{"location":"shader-crt/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexCrtPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexCrtPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexCrtPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexCrtPipeline').get(camera);\n
"},{"location":"shader-crt/#warp","title":"Warp","text":"
  • Get
    var warpX = pipelineInstance.warpX;\nvar warpY = pipelineInstance.warpY;\n
  • Set
    pipelineInstance.setWarp(warpX, warpY);\n
    or
    pipelineInstance.warpX = warpX;\npipelineInstance.warpY = warpY;\n
"},{"location":"shader-crt/#scan-lines","title":"Scan lines","text":"
  • Get
    var scanLineStrength = pipelineInstance.scanLineStrength;\nvar scanLineWidth = pipelineInstance.scanLineWidth;\n
  • Set
    pipelineInstance.setScanStrength(scanLineStrength);\npipelineInstance.setScanLineWidth(scanLineWidth);\n
    or
    pipelineInstance.scanLineStrength = scanLineStrength;\npipelineInstance.scanLineWidth = scanLineWidth;\n
"},{"location":"shader-dissolve/","title":"Dissolve","text":""},{"location":"shader-dissolve/#introduction","title":"Introduction","text":"

Dissolve transition post processing filter. (Reference)

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-dissolve/#live-demos","title":"Live demos","text":"
  • Dissolve
"},{"location":"shader-dissolve/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-dissolve/#install-plugin","title":"Install plugin","text":""},{"location":"shader-dissolve/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexdissolvepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdissolvepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexdissolvepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexdissolvepipelineplugin').add(camera, config);\n
"},{"location":"shader-dissolve/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import DissolvePipelinePlugin from 'phaser3-rex-plugins/plugins/dissolvepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexDissolvePipeline',\nplugin: DissolvePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexDissolvePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexDissolvePipeline').add(camera, config);\n
"},{"location":"shader-dissolve/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import DissolvePostFx from 'phaser3-rex-plugins/plugins/dissolvepipeline.js';\nvar config = {\n// ...\npipeline: [DissolvePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(DissolvePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(DissolvePostFx);\n
"},{"location":"shader-dissolve/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 gray-scale effect.
    var pipelineInstance = scene.plugins.get('rexDissolvePipeline').add(gameObject, {\n// toTexture: textureKey,\n// toFrame: frameName,\n// resizeMode: 1,\n\n// noiseX: undefined,\n// noiseY: undefined,\n// noiseZ: undefined,\n// fromEdgeStart: 0.01,\n// fromEdgeWidth: 0.05,\n// toEdgeStart: 0.01,\n// toEdgeWidth: 0.05,\n\n// progress: 0,\n\n// name: 'rexDissolvePostFx'\n});\n
    • toTexture, toFrame : Texture key and frame name of transition target texture.
    • resizeMode : Resize mode of transition target texture.
      • 0, or 'stretch' : The target texture is stretched to the size of the source texture.
      • 1, or 'contain' : The target texture is resized to fit the source texture.
      • 2, or 'cover' : The target texture is resized to cover the source texture.
    • noiseX, noiseY, noiseZ : Parameter of Perline noise.
      • undefined : A random value.
    • fromEdgeStart, fromEdgeWidth : Dissolve edge start, edge width of from-texture (texture of game object, or render result of camera).
    • toEdgeStart, toEdgeWidth : Reveal edge start, edge width of to-texture.
  • Apply effect to camera. A camera only can add 1 gray-scale effect.
    var pipelineInstance = scene.plugins.get('rexDissolvePipeline').add(camera, config);\n
"},{"location":"shader-dissolve/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexDissolvePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexDissolvePipeline').remove(camera);\n
"},{"location":"shader-dissolve/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexDissolvePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexDissolvePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexDissolvePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexDissolvePipeline').get(camera);\n
"},{"location":"shader-dissolve/#transition-target-texture","title":"Transition target texture","text":"
  • Get
    var textureKey = pipelineInstance.toFrame.texture.key;\nvar frameName = pipelineInstance.toFrame.name;\n
  • Set
    pipelineInstance.setTransitionTargetTexture(textureKey, frameName);\n// pipelineInstance.setTransitionTargetTexture(textureKey, frameName, resizeMode);\n
"},{"location":"shader-dissolve/#progress","title":"Progress","text":"
  • Get
    var progress = pipelineInstance.progress;\n
  • Set
    pipelineInstance.setProgress(value);  // value: 0~1\n
    or
    pipelineInstance.progress = value;  // value: 0~1\n
"},{"location":"shader-dissolve/#resize-mode","title":"Resize mode","text":"
  • Get
    var mode = pipelineInstance.resizeMode;\n
  • Set
    pipelineInstance.setResizeMode(mode);\n
    • mode :
      • 0, or 'stretch' : The target texture is stretched to the size of the source texture.
      • 1, or 'contain' : The target texture is resized to fit the source texture.
      • 2, or 'cover' : The target texture is resized to cover the source texture.
"},{"location":"shader-dissolve/#noise","title":"Noise","text":"
  • Get
    var noiseX = pipelineInstance.noiseX;\nvar noiseY = pipelineInstance.noiseY;\nvar noiseZ = pipelineInstance.noiseZ;\n
  • Set
    pipelineInstance.noiseX = noiseX;\npipelineInstance.noiseY = noiseY;\npipelineInstance.noiseZ = noiseZ;\n
    or
    pipelineInstance.setNoise(noiseX, noiseY, noiseZ);\n// pipelineInstance.setNoise(); // Passing 3 random float numbers\n
"},{"location":"shader-dissolve/#edge","title":"Edge","text":"
  • Get
    • From texture (texture of game object, or render result of camera)
      var edgeStart = pipelineInstance.fromEdgeStart;\nvar edgeWidth = pipelineInstance.fromEdgeWidth;\n
    • To texture (transition target texture)
      var edgeStart = pipelineInstance.toEdgeStart;\nvar edgeWidth = pipelineInstance.toEdgeWidth;\n
  • Set
    • From texture (texture of game object, or render result of camera)
      pipelineInstance.fromEdgeStart = edgeStart;\npipelineInstance.fromEdgeWidth = edgeWidth;\n
      or
      pipelineInstance.setFromEdge(edgeStart, edgeWidth);\n
      • edgeStart : 0~1, default value is 0.01
      • edgeWidth : 0~1, default value is 0.05
    • To texture (transition target texture)
      pipelineInstance.toEdgeStart = edgeStart;\npipelineInstance.toEdgeWidth = edgeWidth;\n
      or
      pipelineInstance.setToEdge(edgeStart, edgeWidth);\n
      • edgeStart : 0~1, default value is 0.01
      • edgeWidth : 0~1, default value is 0.05
"},{"location":"shader-dropshadow/","title":"Drop shadow","text":"

Note

Built-in preFX/postFX also provide shadow effect, might try these first.

"},{"location":"shader-dropshadow/#introduction","title":"Introduction","text":"

Drop-shadow post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-dropshadow/#live-demos","title":"Live demos","text":"
  • Drop-shadow
"},{"location":"shader-dropshadow/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-dropshadow/#install-plugin","title":"Install plugin","text":""},{"location":"shader-dropshadow/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexdropshadowpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdropshadowpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexdropshadowpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexdropshadowpipelineplugin').add(camera, config);\n
"},{"location":"shader-dropshadow/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import DropShadowPipelinePlugin from 'phaser3-rex-plugins/plugins/dropshadowpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexDropShadowPipeline',\nplugin: DropShadowPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexDropShadowPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexDropShadowPipeline').add(camera, config);\n
"},{"location":"shader-dropshadow/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import DropShadowPostFx from 'phaser3-rex-plugins/plugins/dropshadowpipeline.js';\nvar config = {\n// ...\npipeline: [DropShadowPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(DropShadowPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(DropShadowPostFx);\n
"},{"location":"shader-dropshadow/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 dropshadow effect.
    var pipelineInstance = scene.plugins.get('rexDropShadowPipeline').add(gameObject, {\n// ** Offset **\n// rotation: \n// angle: 45,      // degrees\n// distance: 5,\n\n// ** Shadow color **\n// shadowColor: 0xffffff,\n// alpha: 0.5,\n\n// shadowOnly: false,\n\n// ** Parameters of KawaseBlur **\n// blur: 4,\n// quality: 3,\n// pixelWidth: 1,\n// pixelHeight: 1,\n\n// name: 'rexDropShadowPostFx'\n});\n
    • Offset
      • rotation, angle : The angle of the shadow in radians/degrees.
      • distance : Distance of shadow.
    • Color
      • shadowColor : Color of the shadow.
      • alpha : Alpha of the shadow.
    • shadowOnly : Whether render shadow only.
    • Parameters of KawaseBlur
      • blur : The blur of the filter. Should be greater than 0. If value is an Array, setting kernels.
      • quality : The quality of the filter. Should be an integer greater than 1.
      • pixelWidth, pixelHeight : Sets the pixel size of the filter. Large size is blurrier. For advanced usage.
  • Apply effect to camera. A camera only can add 1 dropshadow effect.
    var pipelineInstance = scene.plugins.get('rexDropShadowPipeline').add(camera, config);\n
"},{"location":"shader-dropshadow/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexDropShadowPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexDropShadowPipeline').remove(camera);\n
"},{"location":"shader-dropshadow/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexDropShadowPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexDropShadowPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexDropShadowPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexDropShadowPipeline').get(camera);\n
"},{"location":"shader-dropshadow/#rotation","title":"Rotation","text":"
  • Get
    var rotation = pipelineInstance.rotation;  // radians\n// var angle = pipelineInstance.angle;     // degrees\n
  • Set
    pipelineInstance.rotation = rotation;   // radians\n// pipelineInstance.angle = angle;      // degrees\n
    or
    pipelineInstance.setRotation(radians);\npipelineInstance.setAngle(degrees);\n
"},{"location":"shader-dropshadow/#distance","title":"Distance","text":"
  • Get
    var distance = pipelineInstance.distance;\n
  • Set
    pipelineInstance.distance = distance;\n// pipelineInstance.distance += value;\n
    or
    pipelineInstance.setDistance(distance);\n
"},{"location":"shader-dropshadow/#shadow-color","title":"Shadow color","text":"
  • Get
    var color = pipelineInstance.shadowColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    pipelineInstance.setShadowColor(value);\n
    pipelineInstance.shadowColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"shader-dropshadow/#alpha","title":"Alpha","text":"
  • Get
    var alpha = pipelineInstance.alpha;\n
  • Set
    pipelineInstance.alpha = alpha;\n
    or
    pipelineInstance.setAlpha(alpha);\n
"},{"location":"shader-dropshadow/#shadow-only","title":"Shadow-only","text":"
  • Get
    var enable = pipelineInstance.shadowOnly;\n
  • Set
    pipelineInstance.shadowOnly = enable;\n
    or
    pipelineInstance.setShadowOnly(enable);\n
"},{"location":"shader-dropshadow/#blur","title":"Blur","text":"
  • Get
    var blur = pipelineInstance.blur;\n
  • Set
    pipelineInstance.blur = blur;\n// pipelineInstance.blur += value;\n
    or
    pipelineInstance.setBlur(value);\n
"},{"location":"shader-dropshadow/#quality","title":"Quality","text":"
  • Get
    var quality = pipelineInstance.quality;\n
  • Set
    pipelineInstance.quality = quality;\n// pipelineInstance.quality += value;\n
    or
    pipelineInstance.setQuality(value);\n
"},{"location":"shader-dropshadow/#pixel-size","title":"Pixel size","text":"
  • Get
    var pixelWidth = pipelineInstance.pixelWidth;\nvar pixelHeight = pipelineInstance.pixelHeight;\n
  • Set
    pipelineInstance.pixelWidth = pixelWidth;\npipelineInstance.pixelHeight = pixelHeight;\n
    or
    pipelineInstance.setPixelWidth(pixelWidth);\npipelineInstance.setPixelHeight(pixelHeight);\npipelineInstance.setPixelSize(pixelWidth, pixelHeight);\n
"},{"location":"shader-fisheye/","title":"Fisheye","text":""},{"location":"shader-fisheye/#introduction","title":"Introduction","text":"

Fish-eye post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-fisheye/#live-demos","title":"Live demos","text":"
  • FishEye
"},{"location":"shader-fisheye/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-fisheye/#install-plugin","title":"Install plugin","text":""},{"location":"shader-fisheye/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfisheyepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfisheyepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexfisheyepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexfisheyepipelineplugin').add(camera, config);\n
"},{"location":"shader-fisheye/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FishEyePipelinePlugin from 'phaser3-rex-plugins/plugins/fisheyepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFishEyePipeline',\nplugin: FishEyePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexFishEyePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexFishEyePipeline').add(camera, config);\n
"},{"location":"shader-fisheye/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import FishEyePostFx from 'phaser3-rex-plugins/plugins/fisheyepipeline.js';\nvar config = {\n// ...\npipeline: [FishEyePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(FishEyePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(FishEyePostFx);\n
"},{"location":"shader-fisheye/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 fisheye effect.
    var pipelineInstance = scene.plugins.get('rexFishEyePipeline').add(gameObject, {\n// center: {\n//    x: windowWidth / 2,\n//    y: windowHeight / 2\n//}\n// radius: 0,\n// intensity: 1,\n// mode:0,  // 0|1|'asin'|'sin'\n\n// name: 'rexFishEyePostFx'\n});\n
    • center.x, center.y : Local position of fisheye center.
    • radius : FishEye radius.
    • intensity : 0(original) ~ 1(fisheye). Default value is 1.
    • mode :
      • 0, or 'asin' : asin mode. Defaule value is 0.
      • 1, or 'sin' : sin mode.
  • Apply effect to camera. A camera only can add 1 fisheye effect.
    var pipelineInstance = scene.plugins.get('rexFishEyePipeline').add(camera, config);\n
"},{"location":"shader-fisheye/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexFishEyePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexFishEyePipeline').remove(camera);\n
"},{"location":"shader-fisheye/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexFishEyePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexFishEyePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexFishEyePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexFishEyePipeline').get(camera);\n
"},{"location":"shader-fisheye/#radius","title":"Radius","text":"
  • Get
    var radius = pipelineInstance.radius;\n
  • Set
    pipelineInstance.radius = radius;\n// pipelineInstance.radius += value;\n
    or
    pipelineInstance.setRadius(radius);\n
"},{"location":"shader-fisheye/#intensity","title":"Intensity","text":"
  • Get
    var intensity = pipelineInstance.intensity;\n
  • Set
    pipelineInstance.intensity = intensity;\n// pipelineInstance.intensity += value;\n
    or
    pipelineInstance.setIntensity(intensity);\n
    • intensity : 0(original) ~ 1(fisheye)
"},{"location":"shader-fisheye/#center-position","title":"Center position","text":"

Default value is center of window.

  • Get
    var x = pipelineInstance.centerX;\nvar y = pipelineInstance.centerY;\n
  • Set
    pipelineInstance.centerX = x;\npipelineInstance.centerY = y;\n
    or
    pipelineInstance.setCenter(x, y);\n// pipelineInstance.setCenter();   // set to center of window\n
"},{"location":"shader-fisheye/#mode","title":"Mode","text":"
  • Get
    var mode = pipelineInstance.fishEyeMode;\n
  • Set
    pipelineInstance.setFishEyeMode(mode);\n
    • 0, or 'asin' : asin mode.
    • 1, or 'sin' : sin mode.
"},{"location":"shader-glowfilter/","title":"Glow","text":"

Note

Phaser3.60 has a built-in Glow effect.

"},{"location":"shader-glowfilter/#introduction","title":"Introduction","text":"

Glow post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-glowfilter/#live-demos","title":"Live demos","text":"
  • Glow filter
"},{"location":"shader-glowfilter/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-glowfilter/#install-plugin","title":"Install plugin","text":""},{"location":"shader-glowfilter/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexglowfilterpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexglowfilterpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexglowfilterpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexglowfilterpipelineplugin').add(camera, config);\n
"},{"location":"shader-glowfilter/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GlowFilterPipelinePlugin from 'phaser3-rex-plugins/plugins/glowfilterpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGlowFilterPipeline',\nplugin: GlowFilterPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(camera, config);\n
"},{"location":"shader-glowfilter/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import GlowFilterPostFx from 'phaser3-rex-plugins/plugins/glowfilterpipeline.js';\nvar config = {\n// ...\npipeline: [GlowFilterPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(GlowFilterPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(GlowFilterPostFx);\n
"},{"location":"shader-glowfilter/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 glow effect.
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(gameObject, {\n// intensity: 0\n});\n
    • intensity : 0(original color) ~ 1(white color)
      • Suggestion value : 0 ~ 0.02
  • Apply effect to camera. A camera only can add 1 glow effect.
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(camera, config);\n
"},{"location":"shader-glowfilter/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexGlowFilterPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexGlowFilterPipeline').remove(camera);\n
"},{"location":"shader-glowfilter/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexGlowFilterPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexGlowFilterPipeline').get(camera);\n
"},{"location":"shader-glowfilter/#intensity","title":"Intensity","text":"
  • Get
    var intensity = pipelineInstance.intensity;\n
  • Set
    pipelineInstance.intensity = intensity;\n// pipelineInstance.intensity += value;\n
    or
    pipelineInstance.setIntensity(radius);\n
    • intensity : 0(original color) ~ 1(white color)
      • Suggestion value : 0 ~ 0.02
"},{"location":"shader-glowfilter2/","title":"Glow","text":"

Note

Phaser3.60 has a built-in Glow effect.

"},{"location":"shader-glowfilter2/#introduction","title":"Introduction","text":"

Glow post processing filter, port from pixi. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-glowfilter2/#live-demos","title":"Live demos","text":"
  • Glow filter
"},{"location":"shader-glowfilter2/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-glowfilter2/#install-plugin","title":"Install plugin","text":""},{"location":"shader-glowfilter2/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexglowfilter2pipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexglowfilter2pipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexglowfilter2pipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexglowfilter2pipelineplugin').add(camera, config);\n
"},{"location":"shader-glowfilter2/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GlowFilterPipelinePlugin from 'phaser3-rex-plugins/plugins/glowfilter2pipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGlowFilterPipeline',\nplugin: GlowFilterPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(camera, config);\n
"},{"location":"shader-glowfilter2/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import GlowFilterPostFx from 'phaser3-rex-plugins/plugins/glowfilter2pipeline.js';\nvar config = {\n// ...\npipeline: [GlowFilterPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(GlowFilterPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(GlowFilterPostFx);\n
"},{"location":"shader-glowfilter2/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 glowfilter effect.
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(gameObject, {    // outerStrength: 4,\n// innerStrength: 0,\n// glowColor: 0xffffff,\n// knockout: false,\n\n// distance: 10,\n// quality: 0.1,\n\n// name: 'rexGlowFilterPostFx'\n});\n
    • outerStrength : The strength of the glow outward from the edge of the texture.
    • innerStrength : The strength of the glow inward from the edge of the texture.
    • glowColor : The color of the glow.
    • knockout :
      • true : Only show effect.
      • false : Show content and effect.
    • distance : The distance of the glow. It can't be changed after filter creation.
    • quality : 0~1. The higher the number the less performant. It can't be changed after filter creation.
  • Apply effect to camera. A camera only can add 1 glowfilter effect.
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(camera, config);\n
"},{"location":"shader-glowfilter2/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexGlowFilterPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexGlowFilterPipeline').remove(camera);\n
"},{"location":"shader-glowfilter2/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexGlowFilterPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexGlowFilterPipeline').get(camera);\n
"},{"location":"shader-glowfilter2/#outer-strength","title":"Outer strength","text":"
  • Get
    var outerStrength = pipelineInstance.outerStrength;\n
  • Set
    pipelineInstance.outerStrength = outerStrength;\n// pipelineInstance.outerStrength += value;\n
    or
    pipelineInstance.setOuterStrength(value);\n
"},{"location":"shader-glowfilter2/#inner-strength","title":"Inner strength","text":"
  • Get
    var innerStrength = pipelineInstance.innerStrength;\n
  • Set
    pipelineInstance.innerStrength = innerStrength;\n// pipelineInstance.innerStrength += value;\n
    or
    pipelineInstance.setInnerStrength(value);\n
"},{"location":"shader-glowfilter2/#glow-color","title":"Glow color","text":"
  • Get
    var color = pipelineInstance.glowColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    pipelineInstance.setGlowColor(value);\n
    pipelineInstance.glowColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"shader-glowfilter2/#distance","title":"Distance","text":"

The distance of the glow. Make it 2 times more for resolution=2. It can't be changed after filter creation.

  • Get
    var distance = pipelineInstance.distance;\n
  • Set
    pipelineInstance.setDistance(distance);\n
    or
    pipelineInstance.distance = distance;\n
    • distance : The distance of the glow.
"},{"location":"shader-glowfilter2/#quality","title":"Quality","text":"

A number between 0 and 1 that describes the quality of the glow. The higher the number the less performant.

  • Get
    var quality = pipelineInstance.quality;\n
  • Set
    pipelineInstance.setQuality(quality);\n
    or
    pipelineInstance.quality = quality;\n
    • quality : 0 ~ 1, default is 0.1.
      • 0.1 : 10 sample points.
      • 0.08 : 8 sample points.
      • 1 : 100 sample points.
"},{"location":"shader-grayscale/","title":"Gray scale","text":"

Note

Phaser3.60 has a built-in Color Matrix effects.

"},{"location":"shader-grayscale/#introduction","title":"Introduction","text":"

Gray scale post processing filter.

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-grayscale/#live-demos","title":"Live demos","text":"
  • Gray scale
"},{"location":"shader-grayscale/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-grayscale/#install-plugin","title":"Install plugin","text":""},{"location":"shader-grayscale/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexgrayscalepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgrayscalepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexgrayscalepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexgrayscalepipelineplugin').add(camera, config);\n
"},{"location":"shader-grayscale/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GrayScalePipelinePlugin from 'phaser3-rex-plugins/plugins/grayscalepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGrayScalePipeline',\nplugin: GrayScalePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexGrayScalePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexGrayScalePipeline').add(camera, config);\n
"},{"location":"shader-grayscale/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import GrayScalePostFx from 'phaser3-rex-plugins/plugins/grayscalepipeline.js';\nvar config = {\n// ...\npipeline: [GrayScalePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(GrayScalePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(GrayScalePostFx);\n
"},{"location":"shader-grayscale/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 gray-scale effect.
    var pipelineInstance = scene.plugins.get('rexGrayScalePipeline').add(gameObject, {\n// intensity: 1,\n\n// name: 'rexGrayScalePostFx'\n});\n
    • intensity : 0(original color) ~ 1(gray scale). Default value is 1.
  • Apply effect to camera. A camera only can add 1 gray-scale effect.
    var pipelineInstance = scene.plugins.get('rexGrayScalePipeline').add(camera, config);\n
"},{"location":"shader-grayscale/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexGrayScalePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexGrayScalePipeline').remove(camera);\n
"},{"location":"shader-grayscale/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexGrayScalePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexGrayScalePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexGrayScalePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexGrayScalePipeline').get(camera);\n
"},{"location":"shader-grayscale/#intensity","title":"Intensity","text":"
  • Get
    var intensity = pipelineInstance.intensity;\n
  • Set
    pipelineInstance.intensity = intensity;\n// pipelineInstance.intensity += value;\n
    or
    pipelineInstance.setIntensity(radius);\n
    • intensity : 0(original color) ~ 1(gray scale)
"},{"location":"shader-horrifi/","title":"Horri-fi","text":""},{"location":"shader-horrifi/#introduction","title":"Introduction","text":"

6-in-1 post processing filter

  • Bloom
  • Chromatic Abberation
  • Scanlines
  • VHS Distortion
  • CRT TV Curve
  • Noise
  • Vignette

Reference : Horri-fi shader effect

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-horrifi/#live-demos","title":"Live demos","text":"
  • Horrifi
"},{"location":"shader-horrifi/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-horrifi/#install-plugin","title":"Install plugin","text":""},{"location":"shader-horrifi/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexhorrifipipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexhorrifipipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexhorrifipipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexhorrifipipelineplugin').add(camera, config);\n
"},{"location":"shader-horrifi/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import HorrifiPipelinePlugin from 'phaser3-rex-plugins/plugins/horrifipipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexHorrifiPipeline',\nplugin: HorrifiPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexHorrifiPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexHorrifiPipeline').add(camera, config);\n
"},{"location":"shader-horrifi/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import HorrifiPostFx from 'phaser3-rex-plugins/plugins/horrifipipeline.js';\nvar config = {\n// ...\npipeline: [HorrifiPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(HorrifiPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(HorrifiPostFx);\n
"},{"location":"shader-horrifi/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 horrifi effect.
    var pipelineInstance = scene.plugins.get('rexHorrifiPipeline').add(gameObject, {\nenable: false,\n\n// Bloom\nbloomEnable: false,\nbloomRadius: 0, bloomIntensity: 0, bloomThreshold: 0,\nbloomTexelWidth: 0, bloomTexelHeight: 0,\n\n// Chromatic abberation\nchromaticEnable: false,\nchabIntensity: 0,\n\n// Vignette\nvignetteEnable: false,\nvignetteStrength: 0, vignetteIntensity: 0,\n\n// Noise\nnoiseEnable: false,\nnoiseStrength: 0,\nnoiseSeed: 0,\n\n// VHS\nvhsEnable: false,\nvhsStrength: 0,\n\n// Scanlines\nscanlinesEnable: false,\nscanStrength: 0,\n\n// CRT\ncrtEnable: false,\ncrtWidth: 0, crtHeight: 0,\n\n// name: 'rexHorrifiPostFx'\n});\n
    • enable : Default enable value for all shader effects.
    • Bloom
      • bloomEnable : Set true to enable bloom effect.
      • bloomRadius, bloomIntensity, bloomThreshold
      • bloomTexelWidth, bloomTexelHeight
    • Chromatic abberation
      • chromaticEnable : Set true to enable chromatic abberation effect.
      • chabIntensity
    • Vignette
      • vignetteEnable : Set true to enable vignette effect.
      • vignetteStrength, vignetteIntensity
    • Noise
      • noiseEnable : Set true to enable noise effect.
      • noiseStrength
      • noiseSeed
    • VHS
      • vhsEnable : Set true to enable VHS effect.
      • vhsStrength
    • Scanlines
      • scanlinesEnable : Set true to enable Scanlines effect.
      • scanStrength
    • CRT
      • crtEnable : Set true to enable Scanlines effect.
      • crtWidth, crtHeight
  • Apply effect to camera. A camera only can add 1 horrifi effect.
    var pipelineInstance = scene.plugins.get('rexHorrifiPipeline').add(camera, config);\n
"},{"location":"shader-horrifi/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexHorrifiPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexHorrifiPipeline').remove(camera);\n
"},{"location":"shader-horrifi/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexHorrifiPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexHorrifiPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexHorrifiPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexHorrifiPipeline').get(camera);\n
"},{"location":"shader-horrifi/#bloom","title":"Bloom","text":""},{"location":"shader-horrifi/#enable","title":"Enable","text":"
  • Enable
    pipelineInstance.setBloomEnable();\n// pipelineInstance.setBloomEnable(true);\n
    or
    pipelineInstance.bloomEnable = true;\n
  • Disable
    pipelineInstance.setBloomEnable(false);\n
    or
    pipelineInstance.bloomEnable = false;\n
  • Get
    var bloomEnable = pipelineInstance.bloomEnable;\n
"},{"location":"shader-horrifi/#parameters","title":"Parameters","text":"
  • Set
    pipelineInstance.setBloomRadius(value);\npipelineInstance.setBloomIntensity(value);\npipelineInstance.setBloomThreshold(value);\npipelineInstance.setBloomTexelSize(width, height);\n
    or
    pipelineInstance.bloomRadius = value;\npipelineInstance.bloomIntensity = value;\npipelineInstance.bloomThreshold = value;\npipelineInstance.bloomTexelWidth = width;\npipelineInstance.bloomTexelHeight = height;\n
  • Get
    var bloomRadius = pipelineInstance.bloomRadius;\nvar bloomIntensity = pipelineInstance.bloomIntensity;\nvar bloomThreshold = pipelineInstance.bloomThreshold;\nvar bloomTexelWidth = pipelineInstance.bloomTexelWidth;\nvar bloomTexelHeight = pipelineInstance.bloomTexelHeight;\n
"},{"location":"shader-horrifi/#chromatic-abberation","title":"Chromatic abberation","text":""},{"location":"shader-horrifi/#enable_1","title":"Enable","text":"
  • Enable
    pipelineInstance.setChromaticEnable();\n// pipelineInstance.setChromaticEnable(true);\n
    or
    pipelineInstance.chromaticEnable = true;\n
  • Disable
    pipelineInstance.setChromaticEnable(false);\n
    or
    pipelineInstance.chromaticEnable = false;\n
  • Get
    var chromaticEnable = pipelineInstance.chromaticEnable;\n
"},{"location":"shader-horrifi/#parameters_1","title":"Parameters","text":"
  • Set
    pipelineInstance.setChabIntensity(value);\n
    or
    pipelineInstance.chabIntensity = value;\n
  • Get
    var chabIntensity = pipelineInstance.chabIntensity;\n
"},{"location":"shader-horrifi/#vignette","title":"Vignette","text":""},{"location":"shader-horrifi/#enable_2","title":"Enable","text":"
  • Enable
    pipelineInstance.setVignetteEnable();\n// pipelineInstance.setVignetteEnable(true);\n
    or
    pipelineInstance.vignetteEnable = true;\n
  • Disable
    pipelineInstance.setVignetteEnable(false);\n
    or
    pipelineInstance.vignetteEnable = false;\n
  • Get
    var vignetteEnable = pipelineInstance.vignetteEnable;\n
"},{"location":"shader-horrifi/#parameters_2","title":"Parameters","text":"
  • Set
    pipelineInstance.setVignetteStrength(value);\npipelineInstance.setVignetteIntensity(value);\n
    or
    pipelineInstance.vignetteStrength = value;\npipelineInstance.vignetteIntensity = value;\n
  • Get
    var vignetteStrength = pipelineInstance.vignetteStrength;\nvar vignetteIntensity = pipelineInstance.vignetteIntensity;\n
"},{"location":"shader-horrifi/#noise","title":"Noise","text":""},{"location":"shader-horrifi/#enable_3","title":"Enable","text":"
  • Enable
    pipelineInstance.setNoiseEnable();\n// pipelineInstance.setNoiseEnable(true);\n
    or
    pipelineInstance.noiseEnable = true;\n
  • Disable
    pipelineInstance.setNoiseEnable(false);\n
    or
    pipelineInstance.noiseEnable = false;\n
  • Get
    var noiseEnable = pipelineInstance.noiseEnable;\n
"},{"location":"shader-horrifi/#parameters_3","title":"Parameters","text":"
  • Set
    pipelineInstance.setNoiseStrength(value);\npipelineInstance.setNoiseSeed(value);\n
    or
    pipelineInstance.noiseStrength = value;\npipelineInstance.noiseSeed = value;\n
  • Get
    var noiseStrength = pipelineInstance.noiseStrength;\nvar noiseSeed = pipelineInstance.noiseSeed;\n
"},{"location":"shader-horrifi/#vhs","title":"VHS","text":""},{"location":"shader-horrifi/#enable_4","title":"Enable","text":"
  • Enable
    pipelineInstance.setVHSEnable();\n// pipelineInstance.setVHSEnable(true);\n
    or
    pipelineInstance.vhsEnable = true;\n
  • Disable
    pipelineInstance.setVHSEnable(false);\n
    or
    pipelineInstance.vhsEnable = false;\n
  • Get
    var vhsEnable = pipelineInstance.vhsEnable;\n
"},{"location":"shader-horrifi/#parameters_4","title":"Parameters","text":"
  • Set
    pipelineInstance.setVhsStrength(value);\n
    or
    pipelineInstance.vhsStrength = value;\n
  • Get
    var vhsStrength = pipelineInstance.vhsStrength;\n
"},{"location":"shader-horrifi/#scanlines","title":"Scanlines","text":""},{"location":"shader-horrifi/#enable_5","title":"Enable","text":"
  • Enable
    pipelineInstance.setScanlinesEnable();\n// pipelineInstance.setScanlinesEnable(true);\n
    or
    pipelineInstance.scanlinesEnable = true;\n
  • Disable
    pipelineInstance.setScanlinesEnable(false);\n
    or
    pipelineInstance.scanlinesEnable = false;\n
  • Get
    var scanlinesEnable = pipelineInstance.scanlinesEnable;\n
"},{"location":"shader-horrifi/#parameters_5","title":"Parameters","text":"
  • Set
    pipelineInstance.setScanStrength(value);\n
    or
    pipelineInstance.scanStrength = value;\n
  • Get
    var scanStrength = pipelineInstance.scanStrength;\n
"},{"location":"shader-horrifi/#crt","title":"CRT","text":""},{"location":"shader-horrifi/#enable_6","title":"Enable","text":"
  • Enable
    pipelineInstance.setCRTEnable();\n// pipelineInstance.setCRTEnable(true);\n
    or
    pipelineInstance.crtEnable = true;\n
  • Disable
    pipelineInstance.setCRTEnable(false);\n
    or
    pipelineInstance.crtEnable = false;\n
  • Get
    var crtEnable = pipelineInstance.crtEnable;\n
"},{"location":"shader-horrifi/#parameters_6","title":"Parameters","text":"
  • Set
    pipelineInstance.setCrtSize(width, height);\n
    or
    pipelineInstance.crtWidth = width;\npipelineInstance.crtHeight = height;\n
  • Get
    var crtWidth = pipelineInstance.crtWidth;\nvar crtHeight = pipelineInstance.crtHeight;\n
"},{"location":"shader-horrifi/#enable-all-effects","title":"Enable all effects","text":"
  • Enable all
    pipelineInstance.setEnable();\n// pipelineInstance.setEnable(true);\n
  • Disable all
    pipelineInstance.setEnable(false);\n
"},{"location":"shader-hsladjust/","title":"HSL adjust","text":"

Note

Phaser3.60 has a built-in Color Matrix effects.

"},{"location":"shader-hsladjust/#introduction","title":"Introduction","text":"

Adjust color in HSL domain, post processing filter.

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-hsladjust/#live-demos","title":"Live demos","text":"
  • HSL adjust
"},{"location":"shader-hsladjust/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-hsladjust/#install-plugin","title":"Install plugin","text":""},{"location":"shader-hsladjust/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexhsladjustpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexhsladjustpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexhsladjustpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexhsladjustpipelineplugin').add(camera, config);\n
"},{"location":"shader-hsladjust/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import HSLAdjustPipelinePlugin from 'phaser3-rex-plugins/plugins/hsladjustpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexHSLAdjustPipeline',\nplugin: HSLAdjustPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexHSLAdjustPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexHSLAdjustPipeline').add(camera, config);\n
"},{"location":"shader-hsladjust/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import HSLAdjustPostFx from 'phaser3-rex-plugins/plugins/hsladjustpipeline.js';\nvar config = {\n// ...\npipeline: [HSLAdjustPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(HSLAdjustPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(HSLAdjustPostFx);\n
"},{"location":"shader-hsladjust/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 hsl-adjust effect.
    var pipelineInstance = scene.plugins.get('rexHslAdjustPipeline').add(gameObject, {\n// hueRotate: 0,\n// satAdjust: 1,\n// lumAdjust: 0.5,\n\n// name: 'rexHslAdjustPostFx'\n});\n
    • hueRotate : Hue rotation
      • 0 : Rotate 0 degrees, original color (Default value)
      • 0.5 : Rotate 180 degrees
      • 1 : Rotate 360 degrees
    • satAdjust : Saturation adjustment
      • 0 : Gray
      • 1 : Original color (Default value)
      • 1 :

    • lumAdjust : Lumen adjustment
      • 0 : Dark
      • 0.5 : Original color (Default value)
      • 1 : White
  • Apply effect to camera. A camera only can add 1 hsl-adjust effect.
    var pipelineInstance = scene.plugins.get('rexHslAdjustPipeline').add(camera, config);\n
"},{"location":"shader-hsladjust/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexHslAdjustPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexHslAdjustPipeline').remove(camera);\n
"},{"location":"shader-hsladjust/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexHslAdjustPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexHslAdjustPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexHslAdjustPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexHslAdjustPipeline').get(camera);\n
"},{"location":"shader-hsladjust/#hue-rotation","title":"Hue rotation","text":"
  • Get
    var hueRotate = pipelineInstance.hueRotate;\n
  • Set
    pipelineInstance.hueRotate = hueRotate;\n// pipelineInstance.hueRotate += value;\n
    or
    pipelineInstance.setHueRotate(value);\n
    • 0 : Rotate 0 degrees, original color
    • 0.5 : Rotate 180 degrees
    • 1 : Rotate 360 degrees
"},{"location":"shader-hsladjust/#saturation-adjustment","title":"Saturation adjustment","text":"
  • Get
    var satAdjust = pipelineInstance.satAdjust;\n
  • Set
    pipelineInstance.satAdjust = satAdjust;\n// pipelineInstance.satAdjust += value;\n
    or
    pipelineInstance.setSatAdjust(value);\n
    • 0 : Gray
    • 1 : Original color
    • 1 :

"},{"location":"shader-hsladjust/#lumen-adjustment","title":"Lumen adjustment","text":"
  • Get
    var lumAdjust = pipelineInstance.lumAdjust;\n
  • Set
    pipelineInstance.lumAdjust = lumAdjust;\n// pipelineInstance.lumAdjust += value;\n
    or
    pipelineInstance.setLumAdjust(value);\n
    • 0 : Dark
    • 0.5 : Original color
    • 1 : White
"},{"location":"shader-inverse/","title":"Inverse","text":"

Note

Phaser3.60 has a built-in Color Matrix effects.

"},{"location":"shader-inverse/#introduction","title":"Introduction","text":"

Inverse color post processing filter.

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-inverse/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-inverse/#install-plugin","title":"Install plugin","text":""},{"location":"shader-inverse/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexinversepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexinversepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexinversepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexinversepipelineplugin').add(camera, config);\n
"},{"location":"shader-inverse/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import InversePipelinePlugin from 'phaser3-rex-plugins/plugins/inversepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexInversePipeline',\nplugin: InversePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexInversePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexInversePipeline').add(camera, config);\n
"},{"location":"shader-inverse/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import InversePostFx from 'phaser3-rex-plugins/plugins/inversepipeline.js';\nvar config = {\n// ...\npipeline: [InversePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(InversePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(InversePostFx);\n
"},{"location":"shader-inverse/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 inverse effect.
    var pipelineInstance = scene.plugins.get('rexInversePipeline').add(gameObject, {\n// intensity: 1,\n\n// name: 'rexInversePostFx'\n});\n
    • intensity : 0(original color) ~ 1(inverse scale). Default value is 1.
  • Apply effect to camera. A camera only can add 1 inverse effect.
    var pipelineInstance = scene.plugins.get('rexInversePipeline').add(camera, config);\n
"},{"location":"shader-inverse/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexInversePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexInversePipeline').remove(camera);\n
"},{"location":"shader-inverse/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexInversePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexInversePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexInversePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexInversePipeline').get(camera);\n
"},{"location":"shader-inverse/#intensity","title":"Intensity","text":"
  • Get
    var intensity = pipelineInstance.intensity;\n
  • Set
    pipelineInstance.intensity = intensity;\n// pipelineInstance.intensity += value;\n
    or
    pipelineInstance.setIntensity(radius);\n
    • intensity : 0(original color) ~ 1(inverse color)
"},{"location":"shader-kawaseblur/","title":"Kawase blur","text":"

Note

Phaser3.60 has a built-in blur effect.

"},{"location":"shader-kawaseblur/#introduction","title":"Introduction","text":"

Kawase-blur post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-kawaseblur/#live-demos","title":"Live demos","text":"
  • Kawase-blur
"},{"location":"shader-kawaseblur/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-kawaseblur/#install-plugin","title":"Install plugin","text":""},{"location":"shader-kawaseblur/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexkawaseblurpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexkawaseblurpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexkawaseblurpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexkawaseblurpipelineplugin').add(camera, config);\n
"},{"location":"shader-kawaseblur/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import KawaseBlurPipelinePlugin from 'phaser3-rex-plugins/plugins/kawaseblurpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexKawaseBlurPipeline',\nplugin: KawaseBlurPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexKawaseBlurPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexKawaseBlurPipeline').add(camera, config);\n
"},{"location":"shader-kawaseblur/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import KawaseBlurPostFx from 'phaser3-rex-plugins/plugins/kawaseblurpipeline.js';\nvar config = {\n// ...\npipeline: [KawaseBlurPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(KawaseBlurPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(KawaseBlurPostFx);\n
"},{"location":"shader-kawaseblur/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 kawaseblur effect.
    var pipelineInstance = scene.plugins.get('rexKawaseBlurPipeline').add(gameObject, {\n// blur: 4,\n// quality: 3,\n// pixelWidth: 1,\n// pixelHeight: 1,\n\n// name: 'rexKawaseBlurPostFx'\n});\n
    • blur : The blur of the filter. Should be greater than 0. If value is an Array, setting kernels.
    • quality : The quality of the filter. Should be an integer greater than 1.
    • pixelWidth, pixelHeight : Sets the pixel size of the filter. Large size is blurrier. For advanced usage.
  • Apply effect to camera. A camera only can add 1 kawaseblur effect.
    var pipelineInstance = scene.plugins.get('rexKawaseBlurPipeline').add(camera, config);\n
"},{"location":"shader-kawaseblur/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexKawaseBlurPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexKawaseBlurPipeline').remove(camera);\n
"},{"location":"shader-kawaseblur/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexKawaseBlurPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexKawaseBlurPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexKawaseBlurPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexKawaseBlurPipeline').get(camera);\n
"},{"location":"shader-kawaseblur/#blur","title":"Blur","text":"
  • Get
    var blur = pipelineInstance.blur;\n
  • Set
    pipelineInstance.blur = blur;\n// pipelineInstance.blur += value;\n
    or
    pipelineInstance.setBlur(value);\n
"},{"location":"shader-kawaseblur/#quality","title":"Quality","text":"
  • Get
    var quality = pipelineInstance.quality;\n
  • Set
    pipelineInstance.quality = quality;\n// pipelineInstance.quality += value;\n
    or
    pipelineInstance.setQuality(value);\n
"},{"location":"shader-kawaseblur/#pixel-size","title":"Pixel size","text":"
  • Get
    var pixelWidth = pipelineInstance.pixelWidth;\nvar pixelHeight = pipelineInstance.pixelHeight;\n
  • Set
    pipelineInstance.pixelWidth = pixelWidth;\npipelineInstance.pixelHeight = pixelHeight;\n
    or
    pipelineInstance.setPixelWidth(pixelWidth);\npipelineInstance.setPixelHeight(pixelHeight);\npipelineInstance.setPixelSize(pixelWidth, pixelHeight);\n
"},{"location":"shader-outline/","title":"Outline","text":""},{"location":"shader-outline/#introduction","title":"Introduction","text":"

Outline post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-outline/#live-demos","title":"Live demos","text":"
  • Outline
"},{"location":"shader-outline/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-outline/#install-plugin","title":"Install plugin","text":""},{"location":"shader-outline/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexoutlinepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexoutlinepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexoutlinepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexoutlinepipelineplugin').add(camera, config);\n
"},{"location":"shader-outline/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import OutlinePipelinePlugin from 'phaser3-rex-plugins/plugins/outlinepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexOutlinePipeline',\nplugin: OutlinePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexOutlinePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexOutlinePipeline').add(camera, config);\n
"},{"location":"shader-outline/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import OutlinePostFx from 'phaser3-rex-plugins/plugins/outlinepipeline.js';\nvar config = {\n// ...\npipeline: [OutlinePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(OutlinePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(OutlinePostFx);\n
"},{"location":"shader-outline/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 outline effect.
    var pipelineInstance = scene.plugins.get('rexOutlinePipeline').add(gameObject, {\n// thickness: 3,\n// outlineColor: 0x000000,\n\n// quality: 0.1,\n\n// name: 'rexOutlinePostFx'\n});\n
    • thickness : Thickness of outline.
    • outlineColor : Color of outline.
    • quality : 0~1. The higher the number the less performant. It can't be changed after filter creation.
  • Apply effect to camera. A camera only can add 1 outline effect.
    var pipelineInstance = scene.plugins.get('rexOutlinePipeline').add(camera, config);\n
"},{"location":"shader-outline/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexOutlinePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexOutlinePipeline').remove(camera);\n
"},{"location":"shader-outline/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexOutlinePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexOutlinePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexOutlinePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexOutlinePipeline').get(camera);\n
"},{"location":"shader-outline/#thickness","title":"Thickness","text":"
  • Get
    var thickness = pipelineInstance.thickness;\n
  • Set
    pipelineInstance.thickness = thickness;\n// pipelineInstance.thickness += value;\n
    or
    pipelineInstance.setThickness(value);\n
"},{"location":"shader-outline/#outline-color","title":"Outline color","text":"
  • Get
    var color = pipelineInstance.outlineColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    pipelineInstance.setOutlineColor(value);\n
    pipelineInstance.outlineColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"shader-outline/#quality","title":"Quality","text":"

The quality of the outline from 0 to 1, using a higher quality setting will result in slower performance and more accuracy.

  • Get
    var quality = pipelineInstance.quality;\n
  • Set
    pipelineInstance.setQuality(quality);\n
    or
    pipelineInstance.quality = quality;\n
    • quality : 0 ~ 1, default is 0.1.
      • 0.1 : 10 sample points.
      • 0.08 : 8 sample points.
      • 1 : 100 sample points.
"},{"location":"shader-pixelation/","title":"Pixelation","text":"

Note

Phaser3.60 has a built-in pixelate effect.

"},{"location":"shader-pixelation/#introduction","title":"Introduction","text":"

Pixelation post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-pixelation/#live-demos","title":"Live demos","text":"
  • Pixelation
"},{"location":"shader-pixelation/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-pixelation/#install-plugin","title":"Install plugin","text":""},{"location":"shader-pixelation/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexpixelationpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexpixelationpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexpixelationpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexpixelationpipelineplugin').add(camera, config);\n
"},{"location":"shader-pixelation/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PixelationPipelinePlugin from 'phaser3-rex-plugins/plugins/pixelationpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPixelationPipeline',\nplugin: PixelationPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexPixelationPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexPixelationPipeline').add(camera, config);\n
"},{"location":"shader-pixelation/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import PixelationPostFx from 'phaser3-rex-plugins/plugins/pixelationpipeline.js';\nvar config = {\n// ...\npipeline: [PixelationPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(PixelationPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(PixelationPostFx);\n
"},{"location":"shader-pixelation/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 pixelation effect.
    var pipelineInstance = scene.plugins.get('rexPixelationPipeline').add(gameObject, {\n// pixelWidth: 0,\n// pixelHeight: 0,\n\n// name: 'rexPixelationPostFx'\n});\n
    • pixelWidth, pixelHeight : Pixel size.
  • Apply effect to camera. A camera only can add 1 pixelation effect.
    var pipelineInstance = scene.plugins.get('rexPixelationPipeline').add(camera, config);\n
"},{"location":"shader-pixelation/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexPixelationPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexPixelationPipeline').remove(camera);\n
"},{"location":"shader-pixelation/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexPixelationPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexPixelationPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexPixelationPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexPixelationPipeline').get(camera);\n
"},{"location":"shader-pixelation/#pixel-size","title":"Pixel size","text":"
  • Get
    var pixelWidth = pipelineInstance.pixelWidth;\nvar pixelHeight = pipelineInstance.pixelHeight;\n
  • Set
    pipelineInstance.pixelWidth = pixelWidth;\npipelineInstance.pixelHeight = pixelHeight;\n// pipelineInstance.pixelWidth += value;\n// pipelineInstance.pixelHeight += value;\n
    or
    pipelineInstance.setPixelWidth(pixelWidth);\npipelineInstance.setPixelHeight(pixelHeight);\npipelineInstance.setPixelSize(pixelWidth, pixelHeight);\n
"},{"location":"shader-shockwave/","title":"Shockwave","text":""},{"location":"shader-shockwave/#introduction","title":"Introduction","text":"

Shockwave post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-shockwave/#live-demos","title":"Live demos","text":"
  • Shockwave
"},{"location":"shader-shockwave/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-shockwave/#install-plugin","title":"Install plugin","text":""},{"location":"shader-shockwave/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexshockwavepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexshockwavepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexshockwavepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexshockwavepipelineplugin').add(camera, config);\n
"},{"location":"shader-shockwave/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ShockwavePipelinePlugin from 'phaser3-rex-plugins/plugins/shockwavepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexShockwavePipeline',\nplugin: ShockwavePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexShockwavePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexShockwavePipeline').add(camera, config);\n
"},{"location":"shader-shockwave/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import ShockwavePostFx from 'phaser3-rex-plugins/plugins/shockwavepipeline.js';\nvar config = {\n// ...\npipeline: [ShockwavePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(ShockwavePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(ShockwavePostFx);\n
"},{"location":"shader-shockwave/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 shockwave effect.
    var pipelineInstance = scene.plugins.get('rexShockwavePipeline').add(gameObject, {\n// center: {\n//    x: windowWidth / 2,\n//    y: windowHeight / 2\n//}\n// waveRadius: 0,\n// waveWidth: 20,\n// powBaseScale: 0.8,\n// powExponent: 0.1,\n\n// name: 'rexShockwavePostFx'\n});\n
    • waveRadius : Radius of shockwave, in pixels.
    • waveWidth : Width of shockwave, in pixels.
    • powBaseScale, powExponent : Parameters of shockwave.
  • Apply effect to camera. A camera only can add 1 shockwave effect.
    var pipelineInstance = scene.plugins.get('rexShockwavePipeline').add(camera, config);\n
"},{"location":"shader-shockwave/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexShockwavePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexShockwavePipeline').remove(camera);\n
"},{"location":"shader-shockwave/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexShockwavePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexShockwavePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexShockwavePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexShockwavePipeline').get(camera);\n
"},{"location":"shader-shockwave/#wave-radius","title":"Wave radius","text":"
  • Get
    var waveRadius = pipelineInstance.waveRadius;\n
  • Set
    pipelineInstance.waveRadius = waveRadius;\n
    or
    pipelineInstance.setWaveRadius(waveRadius);\n
"},{"location":"shader-shockwave/#wave-width","title":"Wave width","text":"
  • Get
    var waveWidth = pipelineInstance.waveWidth;\n
  • Set
    pipelineInstance.waveWidth = waveWidth;\n
    or
    pipelineInstance.setWaveWidth(waveWidth);\n
"},{"location":"shader-split/","title":"Split","text":""},{"location":"shader-split/#introduction","title":"Introduction","text":"

Split image into 4 parts.

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-split/#live-demos","title":"Live demos","text":"
  • Split
"},{"location":"shader-split/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-split/#install-plugin","title":"Install plugin","text":""},{"location":"shader-split/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexsplitpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexsplitpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexsplitpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexsplitpipelineplugin').add(camera, config);\n
"},{"location":"shader-split/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SplitPipelinePlugin from 'phaser3-rex-plugins/plugins/splitpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexSplitPipeline',\nplugin: SplitPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexSplitPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexSplitPipeline').add(camera, config);\n
"},{"location":"shader-split/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import SplitPostFx from 'phaser3-rex-plugins/plugins/splitpipeline.js';\nvar config = {\n// ...\npipeline: [SplitPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(SplitPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(SplitPostFx);\n
"},{"location":"shader-split/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 split effect.
    var pipelineInstance = scene.plugins.get('rexSplitPipeline').add(gameObject, {\n// x: undefined,  // renderer.width / 2\n// y: undefined,  // renderer.height / 2\n\n// width: undefined,\n// left: 0,\n// right: 0,\n// height: undefined,\n// top: 0,\n// bottom: 0,\n\n// angle: undefined,  // Degrees\n// rotation: 0,       // Radian\n\n// shiftEnable: true,\n\n// name: 'rexSplitPostFx'\n});\n
    • x : Vertical split position. Default value is center of render width.
    • y : Horizontal split position. Default value is center of render height.
    • width, height : Vertical/Horizontal split length.
    • left, right : Specify left/right part length of vertical split. Default value is half Vertical split length.
    • top, bottom : Specify top/bottom part length of horizontal split. Default value is half Horizontal split length.
    • angle, rotation : Rotation of split axis. Default value is 0.
    • shiftEnable :
      • true : Shift splitted parts out. Default value.
      • false : Don't shift splitted parts. Equal to apply mask on this image.
  • Apply effect to camera. A camera only can add 1 split effect.
    var pipelineInstance = scene.plugins.get('rexSplitPipeline').add(camera, config);\n
"},{"location":"shader-split/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexSplitPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexSplitPipeline').remove(camera);\n
"},{"location":"shader-split/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexSplitPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexSplitPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexSplitPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexSplitPipeline').get(camera);\n
"},{"location":"shader-split/#split-position","title":"Split position","text":"
  • Get
    var splitX = pipelineInstance.splitX;\nvar splitY = pipelineInstance.splitY;\n
  • Set
    pipelineInstance.splitX = splitX;\npipelineInstance.splitY = splitY;\n
    or
    pipelineInstance.setSplit(x, y);\n
"},{"location":"shader-split/#split-at-center-of-render","title":"Split at center of render","text":"
pipelineInstance.splitAtCenter();\n// pipelineInstance.splitAtCenter(width, height);\n
"},{"location":"shader-split/#split-length","title":"Split length","text":"
  • Get
    var splittedWidth = pipelineInstance.splittedWidth;\nvar splittedHeight = pipelineInstance.splittedHeight;\n
  • Set
    pipelineInstance.splittedWidth = splittedWidth;\npipelineInstance.splittedHeight = splittedHeight;\n
    or
    pipelineInstance.setSplittedWidth(splittedWidth);\npipelineInstance.setSplittedHeight(splittedHeight);\n

or specify left/right/top/bottom of split length

  • Get
    var left = pipelineInstance.spaceLeft;\nvar right = pipelineInstance.spaceRight;\nvar top = pipelineInstance.spaceTop;\nvar bottom = pipelineInstance.spaceBottom;\n
  • Set
    pipelineInstance.spaceLeft = left;\npipelineInstance.spaceRight = right;\npipelineInstance.spaceTop = top;\npipelineInstance.spaceBottom = bottom;\n
    or
    pipelineInstance.setSpace(left, right, top, bottom);\n
"},{"location":"shader-split/#rotation-axis-of-split-edge","title":"Rotation Axis of Split edge","text":"
  • Get
    var rotation = pipelineInstance.rotation;  // radians\n// var angle = pipelineInstance.angle;     // degrees\n
  • Set
    pipelineInstance.rotation = rotation;\npipelineInstance.rotation += value;\n// pipelineInstance.angle = angle;\n// pipelineInstance.angle += value;\n
    or
    pipelineInstance.setRotation(rotation);\n// pipelineInstance.setAngle(angle);\n
"},{"location":"shader-split/#shift-enable","title":"Shift enable","text":"
  • Get
    var enable = pipelineInstance.shiftEnable;\n
  • Set
    pipelineInstance.shiftEnable = enable;\n
    or
    pipelineInstance.setShiftEnable(enable);\n
"},{"location":"shader-swirl/","title":"Swirl","text":""},{"location":"shader-swirl/#introduction","title":"Introduction","text":"

Swirl post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-swirl/#live-demos","title":"Live demos","text":"
  • Swirl
"},{"location":"shader-swirl/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-swirl/#install-plugin","title":"Install plugin","text":""},{"location":"shader-swirl/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexswirlpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexswirlpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexswirlpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexswirlpipelineplugin').add(camera, config);\n
"},{"location":"shader-swirl/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SwirlPipelinePlugin from 'phaser3-rex-plugins/plugins/swirlpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexSwirlPipeline',\nplugin: SwirlPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexSwirlPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexSwirlPipeline').add(camera, config);\n
"},{"location":"shader-swirl/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import SwirlPostFx from 'phaser3-rex-plugins/plugins/swirlpipeline.js';\nvar config = {\n// ...\npipeline: [SwirlPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(SwirlPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(SwirlPostFx);\n
"},{"location":"shader-swirl/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 swirl effect.
    var pipelineInstance = scene.plugins.get('rexSwirlPipeline').add(gameObject, {\n// center: {\n//    x: windowWidth / 2,\n//    y: windowHeight / 2\n//}\n// radius: 0,\n// rotation: 0,  // or angle: 0,\n\n// name: 'rexSwirlPostFx'\n});\n
    • center.x, center.y : Local position of swirl center.
    • radius : Swirl radius.
    • rotation (angle) : Swirl angle.
  • Apply effect to camera. A camera only can add 1 swirl effect.
    var pipelineInstance = scene.plugins.get('rexSwirlPipeline').add(camera, config);\n
"},{"location":"shader-swirl/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexSwirlPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexSwirlPipeline').remove(camera);\n
"},{"location":"shader-swirl/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexSwirlPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexSwirlPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexSwirlPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexSwirlPipeline').get(camera);\n
"},{"location":"shader-swirl/#radius","title":"Radius","text":"
  • Get
    var radius = pipelineInstance.radius;\n
  • Set
    pipelineInstance.radius = radius;\n// pipelineInstance.radius += value;\n
    or
    pipelineInstance.setRadius(radius);\n
"},{"location":"shader-swirl/#rotation","title":"Rotation","text":"
  • Get
    var rotation = pipelineInstance.rotation;  // radians\n// var angle = pipelineInstance.angle;     // degrees\n
  • Set
    pipelineInstance.rotation = rotation;\npipelineInstance.rotation += value;\n// pipelineInstance.angle = angle;\n// pipelineInstance.angle += value;\n
    or
    pipelineInstance.setRotation(rotation);\n// pipelineInstance.setAngle(angle);\n
"},{"location":"shader-swirl/#center-position","title":"Center position","text":"

Default value is center of window.

  • Get
    var x = pipelineInstance.centerX;\nvar y = pipelineInstance.centerY;\n
  • Set
    pipelineInstance.centerX = x;\npipelineInstance.centerY = y;\n
    or
    pipelineInstance.setCenter(x, y);\n// pipelineInstance.setCenter();   // set to center of window\n
"},{"location":"shader-toonify/","title":"Toonify","text":""},{"location":"shader-toonify/#introduction","title":"Introduction","text":"

Draw outlines and quantize color in HSV domain, post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-toonify/#live-demos","title":"Live demos","text":"
  • Toonify
"},{"location":"shader-toonify/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-toonify/#install-plugin","title":"Install plugin","text":""},{"location":"shader-toonify/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextoonifypipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextoonifypipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rextoonifypipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rextoonifypipelineplugin').add(camera, config);\n
"},{"location":"shader-toonify/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ToonifyPipelinePlugin from 'phaser3-rex-plugins/plugins/toonifypipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexToonifyPipeline',\nplugin: ToonifyPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexToonifyPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexToonifyPipeline').add(camera, config);\n
"},{"location":"shader-toonify/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import ToonifyPostFx from 'phaser3-rex-plugins/plugins/toonifypipeline.js';\nvar config = {\n// ...\npipeline: [ToonifyPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(ToonifyPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(ToonifyPostFx);\n
"},{"location":"shader-toonify/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 toonify effect.
    var pipelineInstance = scene.plugins.get('rexToonifyPipeline').add(gameObject, {\n// edgeThreshold: 0.2,\n// hueLevels: 0,\n// sLevels: 0,\n// vLevels: 0,\n// edgeColor: 0,\n\n// name: 'rexToonifyPostFx'\n});\n
    • edgeThreshold : Threshold of edge. Set 1.1 (or any number larger then 1) to disable this feature.
    • hueLevels : Amount of hue levels. Set 0 to disable this feature.
    • sLevels : Amount of saturation levels. Set 0 to disable this feature.
    • vLevels : Amount of value levels. Set 0 to disable this feature.
    • edgeColor : Color of edge, could be a number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
  • Apply effect to camera. A camera only can add 1 toonify effect.
    var pipelineInstance = scene.plugins.get('rexToonifyPipeline').add(camera, config);\n
"},{"location":"shader-toonify/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexToonifyPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexToonifyPipeline').remove(camera);\n
"},{"location":"shader-toonify/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexToonifyPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexToonifyPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexToonifyPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexToonifyPipeline').get(camera);\n
"},{"location":"shader-toonify/#edge-threshold","title":"Edge threshold","text":"
  • Get
    var edgeThreshold = pipelineInstance.edgeThreshold;\n
  • Set
    pipelineInstance.edgeThreshold = edgeThreshold;\n
    or
    pipelineInstance.setEdgeThreshold(value);\n
    • Set 1.1 (or any number larger then 1) to disable this feature.
"},{"location":"shader-toonify/#hue-levels","title":"Hue levels","text":"
  • Get
    var hueLevels = pipelineInstance.hueLevels;\n
  • Set
    pipelineInstance.hueLevels = hueLevels;\n
    or
    pipelineInstance.setHueLevels(value);\n
    • Set 0 to disable this feature.
"},{"location":"shader-toonify/#saturation-levels","title":"Saturation levels","text":"
  • Get
    var satLevels = pipelineInstance.satLevels;\n
  • Set
    pipelineInstance.satLevels = satLevels;\n
    or
    pipelineInstance.setSatLevels(value);\n
    • Set 0 to disable this feature.
"},{"location":"shader-toonify/#value-levels","title":"Value levels","text":"
  • Get
    var valLevels = pipelineInstance.valLevels;\n
  • Set
    pipelineInstance.valLevels = valLevels;\n
    or
    pipelineInstance.setValLevels(value);\n
    • Set 0 to disable this feature.
"},{"location":"shader-toonify/#edge-color","title":"Edge color","text":"
  • Get
    var color = pipelineInstance.edgeColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    pipelineInstance.setEdgeColor(value);\n
    or
    pipelineInstance.edgeColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"shader-warp-transition/","title":"Warp","text":""},{"location":"shader-warp-transition/#introduction","title":"Introduction","text":"

Warp transition post processing filter.

  • Author: Richard Davey
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-warp-transition/#usage","title":"Usage","text":"

Reference

"},{"location":"shader-warp-transition/#install-plugin","title":"Install plugin","text":""},{"location":"shader-warp-transition/#import-class","title":"Import class","text":"
  • Get minify file from github
  • Add to game config
    import { WarpPostFX } from './dist/WarpPostFX.js';  // Path to your minify file\nvar config = {\n// ...\npipeline: { WarpPostFX }\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(WarpPostFX);\n
    • Apply effect to camera
      camera.setPostPipeline(WarpPostFX);\n
"},{"location":"shader-warp-transition/#remove-effect","title":"Remove effect","text":"
gameObject.removePostPipeline(WarpPostFX); // WarpPostFX class\n
"},{"location":"shader-warp-transition/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = gameObject.getPostPipeline(WarpPostFX); // WarpPostFX class\n
  • Get effect from camera
    var pipelineInstance = camera.getPostPipeline(WarpPostFX); // WarpPostFX class\n
"},{"location":"shader-warp-transition/#set-texture","title":"Set texture","text":"
pipelineInstance.setTexture(textureKey, resizeMode);\n
  • textureKey : The key of the texture to use.
  • resizeMode :
    • 0, or 'stretch' : The target texture is stretched to the size of the source texture.
    • 1, or 'contain' : The target texture is resized to fit the source texture.
    • 2, or 'cover' : The target texture is resized to cover the source texture.
"},{"location":"shader-warp-transition/#progress","title":"Progress","text":"
  • Get
    var progress = pipelineInstance.progress;\n
  • Set
    pipelineInstance.setProgress(value);  // value: 0~1\n
    or
    pipelineInstance.progress = value;  // value: 0~1\n
"},{"location":"shader-warp-transition/#direction","title":"Direction","text":"
  • Get
    var direction = pipelineInstance.direction;  // {x, y}\n
    • Default value is {x:-1, y:1}
  • Set
    pipelineInstance.setDirection(x, y);  // x, y : 1, or -1\n
"},{"location":"shader-warp-transition/#smoothness","title":"Smoothness","text":"
  • Get
    var smoothness = pipelineInstance.smoothness;\n
  • Set
    pipelineInstance.setSmoothness(value);  // value: 0~1\n
    or
    pipelineInstance.smoothness = value;  // value: 0~1\n
"},{"location":"shader-warp-transition/#resize-mode","title":"Resize mode","text":"
  • Get
    var mode = pipelineInstance.resizeMode;\n
  • Set
    pipelineInstance.setResizeMode(mode);\n
    • mode :
      • 0, or 'stretch' : The target texture is stretched to the size of the source texture.
      • 1, or 'contain' : The target texture is resized to fit the source texture.
      • 2, or 'cover' : The target texture is resized to cover the source texture.
"},{"location":"shader-warp/","title":"Warp","text":""},{"location":"shader-warp/#introduction","title":"Introduction","text":"

Warp post processing filter.

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-warp/#live-demos","title":"Live demos","text":"
  • Warp
"},{"location":"shader-warp/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-warp/#install-plugin","title":"Install plugin","text":""},{"location":"shader-warp/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexwarppipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexwarppipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexwarppipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexwarppipelineplugin').add(camera, config);\n
"},{"location":"shader-warp/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import WarpPipelinePlugin from 'phaser3-rex-plugins/plugins/warppipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexWarpPipeline',\nplugin: WarpPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexWarpPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexWarpPipeline').add(camera, config);\n
"},{"location":"shader-warp/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import WarpPostFx from 'phaser3-rex-plugins/plugins/warppipeline.js';\nvar config = {\n// ...\npipeline: [WarpPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(WarpPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(WarpPostFx);\n
"},{"location":"shader-warp/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 warp effect.

    var pipelineInstance = scene.plugins.get('rexWarpPipeline').add(gameObject, {\n// frequencyX: 10,\n// frequencyY: 10,\n\n// amplitudeX: 10,\n// amplitudeY: 10,\n\n// speedX: 0,\n// speedY: 0,\n// speedEnable: \n\n// name: 'rexWarpPostFx'\n});\n

    • frequencyX, frequencyY : Horizontal/vertical frequency, in pixel.
    • amplitudeX, amplitudeY : Horizontal/vertical amplitude, in pixel.
    • speedX, speedY : Horizontal/vertical speed.
    • speedEnable
      • true : Enable speed. Default value if speedX or speedY is not 0.
      • false : Disable speed. Default value if speedX and speedY are both 0.
  • Apply effect to camera. A camera only can add 1 warp effect.

    var pipelineInstance = scene.plugins.get('rexWarpPipeline').add(camera, config);\n

"},{"location":"shader-warp/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexWarpPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexWarpPipeline').remove(camera);\n
"},{"location":"shader-warp/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexWarpPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexWarpPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexWarpPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexWarpPipeline').get(camera);\n
"},{"location":"shader-warp/#frequency","title":"Frequency","text":"

Horizontal/vertical frequency, in pixel.

  • Get
    var frequencyX = pipelineInstance.frequencyX;\nvar frequencyY = pipelineInstance.frequencyY;\n
  • Set
    pipelineInstance.frequencyX = frequencyX;\npipelineInstance.frequencyY = frequencyY;\n// pipelineInstance.frequencyX += value;\n// pipelineInstance.frequencyY += value;\n
    or
    pipelineInstance.setFrequencyX(frequencyX);\npipelineInstance.setFrequencyY(frequencyY);\npipelineInstance.setFrequency(frequencyX, frequencyY);\n
"},{"location":"shader-warp/#amplitude","title":"Amplitude","text":"

Horizontal/vertical amplitude, in pixel.

  • Get
    var amplitudeX = pipelineInstance.amplitudeX;\nvar amplitudeY = pipelineInstance.amplitudeY;\n
  • Set
    pipelineInstance.amplitudeX = amplitudeX;\npipelineInstance.amplitudeY = amplitudeY;\n// pipelineInstance.amplitudeX += value;\n// pipelineInstance.amplitudeY += value;\n
    or
    pipelineInstance.setAmplitudeX(amplitudeX);\npipelineInstance.setAmplitudeY(amplitudeY);\npipelineInstance.setAmplitude(amplitudeX, amplitudeY);\n
"},{"location":"shader-warp/#speed","title":"Speed","text":"

Horizontal/vertical speed.

  • Eanble/resume
    pipelineInstance.setSpeedEnable();\n
  • Pause
    pipelineInstance.setSpeedEnable(false);\n
  • Get
    var speedX = pipelineInstance.speedX;\nvar speedY = pipelineInstance.speedY;\n
  • Set
    pipelineInstance.speedX = speedX;\npipelineInstance.speedY = speedY;\n// pipelineInstance.speedX += value;\n// pipelineInstance.speedY += value;\n
    or
    pipelineInstance.setSpeedX(speedX);\npipelineInstance.setSpeedY(speedY);\npipelineInstance.setSpeed(speedX, speedY);\n
"},{"location":"shader/","title":"Shader","text":""},{"location":"shader/#introduction","title":"Introduction","text":"

A quad with its own shader, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shader/#usage","title":"Usage","text":""},{"location":"shader/#load-glsl","title":"Load GLSL","text":"
scene.load.glsl(key, url);\n

Reference: load glsl

"},{"location":"shader/#add-shader-object","title":"Add shader object","text":"
var shader = scene.add.shader(key, x, y, width, height, textures);\n
  • key : The key of the shader to use from the shader cache, or a BaseShader instance.
  • x, y : Position.
  • width, height : Size.
  • textures : Optional array of texture keys to bind to the iChannel0, iChannel1, iChannel2, iChannel3 uniforms.

Note

Lots of shaders expect textures to be power-of-two sized.

Add shader object from JSON

var shader = scene.make.shader({\nx: 0,\ny: 0,\nkey: '',\n\n// angle: 0,\n// alpha: 1\n// flipX: true,\n// flipY: true,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
  • key : The key of the shader to use from the shader cache, or a BaseShader instance.
    • A string
    • An array of string to pick one element at random
  • x, y, scale.x, scale.y :
    • A number
    • A callback to get return value
      function() { return 0; }\n
    • Random integer between min and max
      { randInt: [min, max] }\n
    • Random float between min and max
      { randFloat: [min, max] }\n
"},{"location":"shader/#custom-class","title":"Custom class","text":"
  • Define class
    class MyShader extends Phaser.GameObjects.Shader {\nconstructor(scene, key, x, y, width, height, textures) {\nsuper(scene, key, x, y, width, height, textures);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var shader = new MyShader(scene, key, x, y, width, height, textures);\n
"},{"location":"shader/#sampler2d-uniform","title":"Sampler2D uniform","text":"
  • Default uniform mappings :
    • resolution (2f) - Set to the size of this shader.
      • uniform vec2 resolution; in GLSL.
    • time (1f) - The elapsed game time, in seconds.
      • uniform float time; in GLSL.
    • mouse (2f) - If a pointer has been bound (with setPointer), this uniform contains its position each frame.
      • uniform vec2 mouse; in GLSL.
    • date (4fv) - A vec4 containing the year, month, day and time in seconds.
      • uniform vec4 date; in GLSL.
    • sampleRate (1f) - Sound sample rate. 44100 by default.
      • uniform float sampleRate; in GLSL.
    • iChannel0...3 (sampler2D) - Input channels 0 to 3. null by default. uniform sampler2D iChannel0; in GLSL.
  • Get uniform object
    var uniform = shader.getUniform(key);\n
    • Texture key
      var textureKey = uniform.textureKey;\n
    • Get texture key of iChannel0, iChannel1, iChannel2, iChannel3 sampler2D uniform.
      var textureKey = shader.getUniform('iChannel0').textureKey;\nvar textureKey = shader.getUniform('iChannel1').textureKey;\nvar textureKey = shader.getUniform('iChannel2').textureKey;\nvar textureKey = shader.getUniform('iChannel3').textureKey;\n
  • Sets a property of a uniform already present on this shader.
    shader.setUniform(key, value);\n
    • key : The key of the uniform to modify. Use dots for deep properties, i.e. resolution.value.x.
  • Sets a sampler2D uniform from texture manager.
    shader.setChannel0(textureKey);\nshader.setChannel1(textureKey);\nshader.setChannel2(textureKey);\nshader.setChannel3(textureKey);\n// shader.setChannel0(textureKey, textureData);\n// shader.setChannel1(textureKey, textureData);\n// shader.setChannel2(textureKey, textureData);\n// shader.setChannel3(textureKey, textureData);\n
    or
    shader.setSampler2D(uniformKey, textureKey, textureIndex);\n// shader.setSampler2D(uniformKey, textureKey, textureIndex, textureData);\n
    • uniformKey : 'iChannel0', 'iChannel1', 'iChannel2', or 'iChannel3'.
    • textureIndex : 0(for iChannel0), 1(for iChannel1), 2(for iChannel2), 3(for iChannel3).
    • textureData : Additional texture data.
    • textureKey: Key from the Texture Manager cache. It cannot be a single frame from a texture, only the full image. Lots of shaders expect textures to be power-of-two sized.
  • Sets a sampler2D uniform from a webgl texture.
    shader.setSampler2DBuffer(uniformKey, texture, width, height, textureIndex);\n// shader.setSampler2DBuffer(uniformKey, texture, width, height, textureIndex, textureData);\n
    • uniformKey : 'iChannel0', 'iChannel1', 'iChannel2', or 'iChannel3'.
    • width, height : The width, height of the texture.
    • textureIndex : 0(for iChannel0), 1(for iChannel1), 2(for iChannel2), 3(for iChannel3).
    • textureData : Additional texture data.
"},{"location":"shader/#other-uniforms","title":"Other uniforms","text":"
  • mouse, a pointer parameter.
    • Get
      var pointer = shader.pointer;\n
    • Set
      shader.setPointer(pointer);\n
      • pointer : {x, y}
  • time, the elapsed game time, in seconds.
    • Get
      var time = shader.getUniform('time').value;\n// var time = shader.uniforms.time.value\n
    • Set
      shader.setUniform('time.value', time);\n
"},{"location":"shader/#output","title":"Output","text":"
  • Render to Display list, by default.
  • Redirect render result to internal webgl texture.
    shader.setRenderToTexture();\nvar texture = shader.glTexture;\n
  • Redirect render result to internal webgl texture, and sample2D from buffer.
    shader.setRenderToTexture(undefined, true);\nvar texture = shader.glTexture;\n
  • Redirect render result to texture manager, for texture-based game object.
    shader.setRenderToTexture(textureKey);\n// var texture = shader.glTexture;\n
  • Redirect render result to texture manager, and Sample2D from buffer.
    shader.setRenderToTexture(textureKey, true);\n// var texture = shader.glTexture;\n
"},{"location":"shader/#texture-routing","title":"Texture routing","text":"
graph TB\n\nTextureManagerIn[\"Texture manager\"] --> |\"shader.setSampler2D()\"| Sampler2D[\"Samplers:<br>iChannel0<br>iChannel1<br>iChannel2<br>iChannel3\"]\nSampler2D--> Shader[\"shader<br>Shader game object\"]\nShader --> DisplayList[\"Display list\"]\nShader --> |\"shader.setRenderToTexture()\"| InternalTexture[\"shader.glTexture\"]\nInternalTexture -.-> |\"Texture key\"| TextureManagerOut[\"Texture manager\"]\nTextureManagerOut -.-> GameObject[\"Image game object\"]\nGameObject -.-> DisplayList\n\nWebGLTexture[\"WebGl texture<br>gameObject.glTexture\"] --> |\"shader.setSampler2DBuffer()\"| Sampler2D\nInternalTexture --> WebGLTexture\n\nsubgraph Output\nDisplayList\nGameObject\nTextureManagerOut\nend\n\nsubgraph Input\nTextureManagerIn\nWebGLTexture\nend
"},{"location":"shader/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shader/#create-mask","title":"Create mask","text":"
var mask = shader.createBitmapMask();\n

See mask

"},{"location":"shader/#baseshader","title":"BaseShader","text":"
var baseShader = new Phaser.Display.BaseShader(key, fragmentSrc, vertexSrc, uniforms);\n
  • key : The key of this shader
  • fragmentSrc : The fragment source for the shader.
  • vertexSrc : The vertex source for the shader.
    • undefined, or '' : Use default vertex source.
  • uniforms : Optional object defining the uniforms the shader uses.
    {\nuniformName : {type: uniformType, value: initValue},\n...\n}\n
    • uniformName : Uniform name in fragment source.
    • uniformType, initValue : Type and initial value of uniform.
      • '1f' : initValue is a single float value.
        • Example : time: { type: '1f', value: 0 }
      • '2f' : initValue is float numbers {x, y}.
        • Example : resolution: { type: '2f', value: { x: this.width, y: this.height } }
      • '3f' : initValue is float numbers {x, y, z}.
        • Example : color: { type: '3f', value: {x: 0, y: 0, z: 0}}
      • '4f' : initValue is float numbers {x, y, z, w}.
"},{"location":"shake-position/","title":"Shake position","text":""},{"location":"shake-position/#introduction","title":"Introduction","text":"

Shake position of game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"shake-position/#live-demos","title":"Live demos","text":"
  • Shake position
  • Shake position on mutliple game objects
"},{"location":"shake-position/#usage","title":"Usage","text":"

Sample code

"},{"location":"shake-position/#install-plugin","title":"Install plugin","text":""},{"location":"shake-position/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexshakepositionplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexshakepositionplugin.min.js', true);\n
  • Add shake-position behavior
    var shakePosition = scene.plugins.get('rexshakepositionplugin').add(gameObject, config);\n
"},{"location":"shake-position/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ShakePositionPlugin from 'phaser3-rex-plugins/plugins/shakeposition-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexShakePosition',\nplugin: ShakePositionPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add shake-position behavior
    var shakePosition = scene.plugins.get('rexShakePosition').add(gameObject, config);\n
"},{"location":"shake-position/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ShakePosition from 'phaser3-rex-plugins/plugins/shakeposition.js';\n
  • Add shake-position behavior
    var shakePosition = new ShakePosition(gameObject, config);\n
"},{"location":"shake-position/#create-instance","title":"Create instance","text":"
var shake = scene.plugins.get('rexShake').add(gameObject, {\n// mode: 1, // 0|'effect'|1|'behavior'\n// duration: 500,\n// magnitude: 10,\n// magnitudeMode: 1, // 0|'constant'|1|'decay'\n// axis: 0,      //0|'both'|'h&v'|1|'horizontal'|'h'|2|'vertical'|'v'\n});\n
  • mode :
    • 'effect', or 0 : Shake position in 'poststep' game event, and restore in 'prestep' game event.
    • 'behavior', or 1 : Shake position in 'preupdate' scene event.
  • duration : Duration of shaking, in millisecond.
  • magnitude : The strength of the shake, in pixels.
  • magnitudeMode :
    • 'constant', or 0 : Constant strength of the shake.
    • 'decay', or 1 : Decay the strength of the shake.
  • axis :
    • 'both','h&v', 'x&y', or 0 : Changing position on all directions.
    • 'horizontal','h', 'x', or 1 : Changing position on horizontal/x axis.
    • 'vertical','v', 'y', or 2 : Changing position on vertical/y axis.
"},{"location":"shake-position/#start-shaking","title":"Start shaking","text":"
shake.shake();\n// shake.shake(duration, magnitude);\n

or

shake.shake({\nduration: 500,\nmagnitude: 10\n});\n
"},{"location":"shake-position/#stop-shakeing","title":"Stop shakeing","text":"
shake.stop();\n
"},{"location":"shake-position/#enable","title":"Enable","text":"
  • Enable/resume (default)
    shake.setEnable();\n
    or
    shake.enable = true;\n
  • Disable/pause
    shake.setEnable(false);\n
    or
    shake.enable = false;\n
"},{"location":"shake-position/#set-updating-mode","title":"Set updating mode","text":"
shake.setMode(mode);\n
  • mode :
    • 'effect', or 0 : Shake position in post-update stage, and restore in pre-update stage.
    • 'behavior', or 1 : Shake position in pre-update stage.
"},{"location":"shake-position/#set-duration","title":"Set duration","text":"
shake.setDuration(duration);\n// shake.duration = duration;\n
"},{"location":"shake-position/#set-magnitude","title":"Set magnitude","text":"
shake.setMagnitude(magnitude);\nshake.magnitude = magnitude;\n
  • magnitude : The strength of the shake, in pixels.
"},{"location":"shake-position/#set-magnitude-mode","title":"Set magnitude mode","text":"
shake.setMagnitudeMode(magnitudeMode);\n// shake.magnitudeMode = magnitudeMode;\n
  • magnitudeMode :
    • 'constant', or 0 : Constant strength of the shake.
    • 'decay', or 1 : Decay the strength of the shake.
"},{"location":"shake-position/#set-axis-mode","title":"Set axis mode","text":"
shake.setAxisMode(axis);\n
  • axis :
    • 'both','h&v', 'x&y', or 0 : Dragging on all directions.
    • 'horizontal','h', 'x', or 1 : Dragging on horizontal/x axis.
    • 'vertical','v', 'y', or 2 : Dragging on vertical/y axis.
"},{"location":"shake-position/#events","title":"Events","text":"
  • On reached target
    shake.on('complete', function(gameObject, shake){});\n
"},{"location":"shake-position/#status","title":"Status","text":"
  • Is shakeing
    var isRunning = shake.isRunning;\n
"},{"location":"shape-arc/","title":"Arc","text":""},{"location":"shape-arc/#introduction","title":"Introduction","text":"

Arc shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-arc/#usage","title":"Usage","text":""},{"location":"shape-arc/#create-shape","title":"Create shape","text":"
var arc = scene.add.arc(x, y, radius, startAngle, endAngle, anticlockwise, fillColor);\n// var arc = scene.add.arc(x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha);\n
"},{"location":"shape-arc/#custom-class","title":"Custom class","text":"
  • Define class
    class MyArc extends Phaser.GameObjects.Arc {\nconstructor(scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor) {\nsuper(scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var arc = new MyArc(scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor);\n
"},{"location":"shape-arc/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = arc.fillColor;\nvar alpha = arc.fillAlpha;\n
    • Set
      arc.setFillStyle(color, alpha);\n
    • Clear
      arc.setFillStyle();\n
  • Stroke color
    • Get
      var color = arc.strokeColor;\n
    • Set
      arc.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      arc.setStrokeStyle();\n

No tint methods

Uses arc.setFillStyle(color, alpha) to change color.

"},{"location":"shape-arc/#alpha","title":"Alpha","text":"
  • Get
    var alpha = arc.alpha;\n
  • Set
    arc.setAlpha(alpha);\n// arc.alpha = alpha;\n
"},{"location":"shape-arc/#angle","title":"Angle","text":"
  • Start angle, in degrees.
    • Get
      var startAngle = arc.startAngle;\n
    • Set
      arc.setStartAngle(startAngle);\n// arc.setStartAngle(startAngle, anticlockwise);\n
      or
      arc.startAngle = startAngle;\n
  • End angle, in degrees.
    • Get
      var endAngle = arc.endAngle;\n
    • Set
      arc.seEndAngle(endAngle);\n
      or
      arc.endAngle = endAngle;\n
  • Anticlockwise (true, or false)
    • Get
      var anticlockwise = arc.anticlockwise;\n
    • Set
      arc.anticlockwise = anticlockwise;\n
"},{"location":"shape-arc/#radius","title":"Radius","text":"
  • Radius
    • Get
      var radius = arc.radius;\n
    • Set
      arc.setRadius(radius);\n
      or
      arc.radius = radius;\n
  • Iterations: Increase this value for smoother arcs, at the cost of more polygons being rendered. Default is 0.01
    • Get
      var iterations = arc.iterations;\n
    • Set
      arc.iterations = iterations;\n
"},{"location":"shape-arc/#display-size","title":"Display size","text":"
  • Get
    var width = arc.displayWidth;\nvar height = arc.displayHeight;\n
  • Set
    arc.setDisplaySize(width, height);\n
    or
    arc.displayWidth = width;\narc.displayHeight = height;\n
"},{"location":"shape-arc/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-arc/#create-mask","title":"Create mask","text":"
var mask = arc.createGeometryMask();\n

See mask

"},{"location":"shape-arc/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-checkbox/","title":"Checkbox","text":""},{"location":"shape-checkbox/#introduction","title":"Introduction","text":"

Checkbox input with drawing checker path animation.

  • Author: Rex
  • Game object
"},{"location":"shape-checkbox/#live-demos","title":"Live demos","text":"
  • Checkbox
"},{"location":"shape-checkbox/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-checkbox/#install-plugin","title":"Install plugin","text":""},{"location":"shape-checkbox/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcheckboxplugin', 'https://raw.githubusercontent.com/rexrainbow/    phaser3-rex-notes/master/dist/rexcheckboxplugin.min.js', true);\n
  • Add checkbox input
    var checkbox = scene.add.rexCheckbox(x, y, width, height, color, config);\n
  • Add checkbox shape (without click input)
    var checkbox = scene.add.rexCheckboxShape(x, y, width, height, color, config);\n
"},{"location":"shape-checkbox/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CheckboxPlugin from 'phaser3-rex-plugins/plugins/checkbox-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCheckboxPlugin',\nplugin: CheckboxPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add checkbox input
    var checkbox = scene.add.rexCheckbox(x, y, width, height, color, config);\n
  • Add checkbox shape (without click input)
    var checkbox = scene.add.rexCheckboxShape(x, y, width, height, color, config);\n
"},{"location":"shape-checkbox/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Checkbox from 'phaser3-rex-plugins/plugins/checkbox.js';\n
  • Add checkbox input
    var checkbox = new Checkbox(scene, x, y, width, height, color, config);\nscene.add.existing(checkbox);\n
  • Add checkbox shape (without click input)
    // import CheckboxShape from 'phaser3-rex-plugins/plugins/checkboxshape.js';\nvar checkbox = new CheckboxShape(scene, x, y, width, height, color, config);\nscene.add.existing(checkbox);\n
"},{"location":"shape-checkbox/#create-checkbox-input","title":"Create checkbox input","text":"
var checkbox = scene.add.rexCheckbox(x, y, width, height, color, config);\n

or

var checkbox = scene.add.rexCheckbox({\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\n\ncolor: 0x005cb2,\nboxFillAlpha: 1,\nuncheckedColor: null,\nuncheckedBoxFillAlpha: 1,\n\nboxLineWidth: 4,\nboxStrokeColor: 0x005cb2,\nboxStrokeAlpha: 1,\nuncheckedBoxStrokeColor: 0x005cb2,\nuncheckedBoxStrokeAlpha: 1,\n\ncheckerColor: 0xffffff,\ncheckerAlpha: 1,\n\n// boxSize: 1,\n// checkerSize: 1,\n\ncircleBox: false,\n\nanimationDuration: 150,\n\nchecked: false, // or value: false,\n\nclick: undefined,\n// click: {\n//     mode: 1,            // 0|'press'|1|'release'\n//     clickInterval: 100  // ms\n//     threshold: undefined\n// },\nreadOnly: false,\n});\n
  • width, height : Size of checkbox.
  • Box fill style
    • color, boxFillAlpha : Box color and alpha of checked
    • uncheckedColor, uncheckedBoxFillAlpha : Box color and alpha of unchecked
  • Box stroke style
    • boxLineWidth, boxStrokeColor, boxStrokeAlpha : Box stroke color and alpha of checked.
    • uncheckedBoxStrokeColor, uncheckedBoxStrokeAlpha : Box stroke color and alpha of unchecked.
  • Checker style
    • checkerColor, checkerAlpha : Checker color and alpha
  • circleBox : Shape of box
    • false : Rectangle shape box. Default behavior.
    • true : Circle shape box
  • boxSize, checkerSize : Size ratio of box, and checker. Default value is 1.
  • animationDuration : Duration of drawing path of checker.
  • checked : Initial value of checked.
  • click : Configuration of click input
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
    • click.threshold : Cancel clicking detecting when dragging distance is larger then this threshold.
      • undefined : Ignore this feature. Default behavior.
  • readOnly : Set ture to disable input.
"},{"location":"shape-checkbox/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCheckbox extends RexPlugins.GameObjects.Checkbox {\nconstructor(scene, x, y, width, height, color, config) {\nsuper(scene, x, y, width, height, color, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var checkbox = new MyCheckbox(scene, x, y, width, height, color, config);\n
"},{"location":"shape-checkbox/#check","title":"Check","text":"
  • Get
    var checked = checkbox.checked;\n// var checked = checkbox.value;\n
  • Set
    • Check
      checkbox.setChecked();\n// checkbox.setChecked(true);\n// checkbox.setValue(true);\n
      or
      checkbox.checked = true;\n// checkbox.value = true;\n
    • Uncheck
      checkbox.setChecked(false);\n// checkbox.setValue(false);\n
      or
      checkbox.checked = false;\n// checkbox.value = false;\n
    • Toggle
      checkbox.toggleChecked();\n// checkbox.setValue(!checkbox.checked);\n
      or
      checkbox.checked = !checkbox.checked;\n// checkbox.value = !checkbox.value;\n
"},{"location":"shape-checkbox/#read-only","title":"Read only","text":"
  • Get
    var readOnly = checkbox.readOnly;\n
  • Set
    checkbox.setReadOnly();\n// checkbox.setReadOnly(true);\n
    or
    checkbox.readOnly = true;\n
"},{"location":"shape-checkbox/#box-fill-style","title":"Box fill style","text":"
  • Get
    var color = checkbox.boxFillColor;\nvar alpha = checkbox.boxFillAlpha;\n
    var color = checkbox.uncheckedBoxFillColor;\nvar alpha = checkbox.uncheckedBoxFillAlpha;\n
  • Set
    checkbox.setBoxFillStyle(color, alpha);\n// checkbox.boxFillColor = color;\n// checkbox.boxFillAlpha = alpha;\n
    checkbox.setUncheckedBoxFillStyle(color, alpha);\n// checkbox.uncheckedBoxFillColor = color;\n// checkbox.uncheckedBoxFillAlpha = alpha;\n
"},{"location":"shape-checkbox/#box-stroke-style","title":"Box stroke style","text":"
  • Get
    var lineWidth = checkbox.boxLineWidth;\nvar color = checkbox.boxStrokeColor;\nvar alpah = checkbox.boxStrokeAlpha;\n
    var lineWidth = checkbox.uncheckedBoxLineWidth;\nvar color = checkbox.uncheckedBoxStrokeColor;\nvar alpah = checkbox.uncheckedBoxStrokeAlpha;\n
  • Set
    checkbox.setBoxStrokeStyle(lineWidth, color, alpha);\n// checkbox.boxLineWidth = lineWidth;\n// checkbox.boxStrokeColor = color;\n// checkbox.boxStrokeAlpha = alpha;\n
    checkbox.setUncheckedBoxStrokeStyle(lineWidth, color, alpha);\n// checkbox.uncheckedBoxLineWidth = lineWidth;\n// checkbox.uncheckedBoxStrokeColor = color;\n// checkbox.uncheckedBoxStrokeAlpha = alpha;\n
"},{"location":"shape-checkbox/#checker-style","title":"Checker style","text":"
  • Get
    var color = checkbox.checkerColor;\nvar alpha = checkbox.checkAlpha;\n
  • Set
    checkbox.setCheckerStyle(color, alpha);\n// checkbox.checkerColor = color;\n// checkbox.checkAlpha = alpha;\n
"},{"location":"shape-checkbox/#checker-animation","title":"Checker animation","text":"
  • Duration
    • Get
      var duration = checkbox.checkerAnimDuration;\n
    • Set
      checkbox.setCheckerAnimDuration(duration);\ncheckbox.checkerAnimDuration = duration;\n
"},{"location":"shape-checkbox/#size","title":"Size","text":"
  • Get
    var width = checkbox.width;\nvar height = checkbox.height;\n
  • Set
    checkbox.setSize(width, height);\n
    or
    checkbox.width = width;\ncheckbox.height = height;\n
"},{"location":"shape-checkbox/#display-size","title":"Display size","text":"
  • Get
    var width = checkbox.displayWidth;\nvar height = checkbox.displayHeight;\n
  • Set
    checkbox.setDisplaySize(width, height);\n
    or
    checkbox.displayWidth = width;\ncheckbox.displayHeight = height;\n
"},{"location":"shape-checkbox/#size-ratio","title":"Size ratio","text":"
  • Get
    var boxSize = checkbox.boxSize;\nvar checkerSize =checkbox.checkerSize;\n
    • boxSize, checkerSize : Size ratio of box, and checker
  • Set
    checkbox.setBoxSize(sizeRatio);\ncheckbox.setCheckerSize(sizeRatio);\n
"},{"location":"shape-checkbox/#events","title":"Events","text":"
  • On value change
    checkbox.on('valuechange', function(value) {\n// value: checked\n})\n
"},{"location":"shape-checkbox/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-checkbox/#create-mask","title":"Create mask","text":"
var mask = checkbox.createGeometryMask();\n

See mask

"},{"location":"shape-checkbox/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-circle/","title":"Circle","text":""},{"location":"shape-circle/#introduction","title":"Introduction","text":"

Circle shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-circle/#usage","title":"Usage","text":""},{"location":"shape-circle/#create-shape-object","title":"Create shape object","text":"
var circle = scene.add.circle(x, y, radius, fillColor);\n// var circle = scene.add.circle(x, y, radius, fillColor, fillAlpha);\n
"},{"location":"shape-circle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCircle extends Phaser.GameObjects.Arc {\nconstructor(scene, x, y, radius, fillColor, fillAlpha) {\nsuper(scene, x, y, radius, 0, 360, false, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var circle = new MyCircle(scene, x, y, radius, fillColor, fillAlpha);\n
"},{"location":"shape-circle/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = circle.fillColor;\nvar alpha = circle.fillAlpha;\n
    • Set
      circle.setFillStyle(color, alpha);\n
    • Clear
      circle.setFillStyle();\n
  • Stroke color
    • Get
      var color = circle.strokeColor;\n
    • Set
      circle.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      circle.setStrokeStyle();\n

No tint methods

Uses circle.setFillStyle(color, alpha) to change color.

"},{"location":"shape-circle/#alpha","title":"Alpha","text":"
  • Get
    var alpha = circle.alpha;\n
  • Set
    circle.setAlpha(alpha);\n// circle.alpha = alpha;\n
"},{"location":"shape-circle/#radius","title":"Radius","text":"
  • Radius
    • Get
      var radius = circle.radius;\n
    • Set
      circle.setRadius(radius);\n
      or
      circle.radius = radius;\n
  • Iterations: Increase this value for smoother arcs, at the cost of more polygons being rendered. Default is 0.01
    • Get
      var iterations = circle.iterations;\n
    • Set
      circle.iterations = iterations;\n
"},{"location":"shape-circle/#display-size","title":"Display size","text":"
  • Get
    var width = circle.displayWidth;\nvar height = circle.displayHeight;\n
  • Set
    circle.setDisplaySize(width, height);\n
    or
    circle.displayWidth = width;\ncircle.displayHeight = height;\n
"},{"location":"shape-circle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-circle/#create-mask","title":"Create mask","text":"
var mask = circle.createGeometryMask();\n

See mask

"},{"location":"shape-circle/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-circularprogress/","title":"Circular progres","text":""},{"location":"shape-circularprogress/#introduction","title":"Introduction","text":"

Circular progress bar shape.

  • Author: Rex
  • Game object
"},{"location":"shape-circularprogress/#live-demos","title":"Live demos","text":"
  • Circular-progress
  • Pie bar
"},{"location":"shape-circularprogress/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-circularprogress/#install-plugin","title":"Install plugin","text":""},{"location":"shape-circularprogress/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcircularprogressplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcircularprogressplugin.min.js', true);\n
  • Add circular-progress object
    var circularProgress = scene.add.rexCircularProgress(x, y, radius, color, value, config);\n
"},{"location":"shape-circularprogress/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CircularProgressPlugin from 'phaser3-rex-plugins/plugins/circularprogress-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCircularProgressPlugin',\nplugin: CircularProgressPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add circular-progress object
    var circularProgress = scene.add.rexCircularProgress(x, y, radius, color, value, config);\n
"},{"location":"shape-circularprogress/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CircularProgress from 'phaser3-rex-plugins/plugins/circularprogress.js';\n
  • Add circular-progress object
    var circularProgress = new CircularProgress(scene, x, y, radius, color, value, config);\nscene.add.existing(image);\n
"},{"location":"shape-circularprogress/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCircularProgressPlugin',\nplugin: CircularProgressPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"shape-circularprogress/#create-instance","title":"Create instance","text":"
var circularProgress = scene.add.rexCircularProgress(x, y, radius, barColor, value, {    trackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nanticlockwise: false,\n// iterations: 128,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},\n});\n

or

var circularProgress = scene.add.rexCircularProgress({\nx: 0,\ny: 0,\nradius: 1,\n\nbarColor: undefined,\ntrackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nanticlockwise: false,\n// iterations: 128,\n\nvalue: 0,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},  });\n
  • x, y : Position of this object.
  • radius : Radius of this circle. Size will be (radius*2, radius*2).
  • barColor : Color of circular bar, in number or css string value.
  • trackColor : Color of circular track, in number or css string value.
  • centerColor : Color of center circle, in number or css string value.
  • thickness : 0 ~ 1, thickness of circular bar. Default value is 0.2 (0.2*radius)
  • startAngle : Start angle of circular bar, in radians. Default value is 270 degrees.
  • anticlockwise : Set true to put anticlockwise circular bar. Default value is false.
  • iterations : Iterations of curve, set larger value to get more smooth rendering result. Default value is 128.
  • value : 0 ~ 1, progress value. Default is 0.
  • easeValue : Parameters of easing value.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • valuechangeCallback : callback function when value changed.
    function(newValue, oldValue, circularProgress) {\n}\n

Add circular-progress from JSON

var circularProgress = scene.make.rexCircularProgress({\nx: 0,\ny: 0,\nradius: 1,\n\nbarColor: undefined,\ntrackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nanticlockwise: false,\n\nvalue: 0,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},  add: true\n});\n
"},{"location":"shape-circularprogress/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCircularProgress extends CircularProgress {\nconstructor(scene, x, y, radius, color, value, config) {\nsuper(scene, x, y, radius, color, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var circularProgress = new MyCircularProgress(scene, x, y, radius, color, value, config);\n
"},{"location":"shape-circularprogress/#progress-value","title":"Progress value","text":"
  • Get value
    var value = circularProgress.getValue(min, max); // value : min ~ max\n
    or
    var value = circularProgress.getValue(); // value: 0 ~ 1\n
    or
    var value = circularProgress.value; // value: 0 ~ 1\n
  • Set value
    circularProgress.setValue(value, min, max); // value: min ~ max\n
    or
    circularProgress.setValue(value); // value: 0 ~ 1\n
    or
    circularProgress.value = value; // value: 0 ~ 1\n
  • Increase value
    circularProgress.addValue(inc, min, max); // inc: min ~ max\n
    or
    circularProgress.addValue(inc); // inc: 0 ~ 1\n
    or
    circularProgress.value += inc; // inc: 0 ~ 1\n
"},{"location":"shape-circularprogress/#ease-progress-value","title":"Ease progress value","text":"
  • Ease value to
    circularProgress.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    circularProgress.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    circularProgress.stopEaseValue();\n
  • Set ease duration
    circularProgress.setEaseValueDuration(duration);\n
  • Set ease function
    circularProgress.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"shape-circularprogress/#radius","title":"Radius","text":"
  • Get
    var radius = circularProgress.radius;\n
  • Set
    circularProgress.setRadius(radius);\n// circularProgress.radius = radius;\n
    • Also resize this game object to (radius*2, radius*2)
"},{"location":"shape-circularprogress/#circular-track","title":"Circular track","text":"
  • Color
    • Get
      var trackColor = circularProgress.trackColor;\n
    • Set
      circularProgress.setTrackColor(trackColor);\n// circularProgress.trackColor = trackColor;\n
  • Thickness : radius*thickness
    circularProgress.setThickness(thickness);\n
    • thickness : 0~1.
"},{"location":"shape-circularprogress/#circular-bar","title":"Circular bar","text":"
  • Color
    • Get
      var barColor = circularProgress.barColor;\n
    • Set
      circularProgress.setBarColor(barColor);\n// circularProgress.barColor = barColor;\n
  • Thickness : radius*thickness
    circularProgress.setThickness(thickness);\n
    • thickness : 0~1.
  • Start angle
    • Get
      var startAngle = circularProgress.startAngle;\n
    • Set
      circularProgress.setStartAngle(startAngle);\ncircularProgress.startAngle = startAngle;\n
      • startAngle : Start angle of circular bar, in radians.
  • Anticlockwise
    • Get
      var anticlockwise = circularProgress.anticlockwise;\n
    • Set
      circularProgress.setAnticlockwise(anticlockwise);\n// circularProgress.anticlockwise = anticlockwise;\n
"},{"location":"shape-circularprogress/#center-circle","title":"Center circle","text":"
  • Color
    • Get
      var centerColor = circularProgress.centerColor;\n
    • Set
      circularProgress.setCenterColor(centerColor);\n// circularProgress.centerColor = centerColor;\n
"},{"location":"shape-circularprogress/#events","title":"Events","text":"
  • On value changed
    circularProgress.on('valuechange', function(newValue, oldValue, circularProgress){\n//\n}, scope);\n
"},{"location":"shape-circularprogress/#alpha","title":"Alpha","text":"
  • Get
    var alpha = circularProgress.alpha;\n
  • Set
    circularProgress.setAlpha(alpha);\n// circularProgress.alpha = alpha;\n
"},{"location":"shape-circularprogress/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-circularprogress/#create-mask","title":"Create mask","text":"
var mask = circularProgress.createGeometryMask();\n

See mask

"},{"location":"shape-circularprogress/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-circularprogress/#compare-with-circular-progress-canvas","title":"Compare with Circular-progress canvas","text":"
  • Circular-progress canvas creates a canvas then draw on that canvas, circular progress shape draw on GRAPHICS pipeline like Shape or Graphics game object.
  • Circular-progress canvas can draw text directly, circular progress shape can't draw any text.
"},{"location":"shape-cover/","title":"Cover","text":""},{"location":"shape-cover/#introduction","title":"Introduction","text":"

Rectangle shape covered full window, and block all touch events.

  • Author: Rex
  • Game object
"},{"location":"shape-cover/#live-demos","title":"Live demos","text":"
  • Cover
"},{"location":"shape-cover/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-cover/#install-plugin","title":"Install plugin","text":""},{"location":"shape-cover/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcoverplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcoverplugin.min.js', true);\n
  • Add cover object
    var cover = scene.add.rexCover(config);\n
"},{"location":"shape-cover/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CoverPlugin from 'phaser3-rex-plugins/plugins/cover-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCoverPlugin',\nplugin: CoverPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add cover object
    var cover = scene.add.rexCover(config);\n
"},{"location":"shape-cover/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Cover from 'phaser3-rex-plugins/plugins/cover.js';\n
  • Add cover object
    var cover = new Cover(scene, config);\nscene.add.existing(cover);\n
"},{"location":"shape-cover/#create-cover-object","title":"Create cover object","text":"
var cover = scene.add.rexCover({\n// color: 0x0,\n// alpha: 0.8\n});\n
  • color : Color of cover.
  • alpha : Alpha value of cover.
"},{"location":"shape-cover/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCover extends RexPlugins.GameObjects.Cover {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var cover = new MyCover(scene, config);\n
"},{"location":"shape-cover/#color","title":"Color","text":"
  • Tint
    • Get
      var tint = cover.tint;\n
    • Set
      cover.tint = tint;\n
  • Alpha
    • Get
      var alpha = cover.alpha;\n
    • Set
      cover.alpha = alpha;\n
  • Fill color
    • Get
      var color = cover.fillColor;\nvar alpha = cover.fillAlpha;\n
    • Set
      cover.setFillStyle(color, alpha);\n
    • Clear
      cover.setFillStyle();\n
"},{"location":"shape-cover/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-cover/#create-mask","title":"Create mask","text":"
var mask = cover.createGeometryMask();\n

See mask

"},{"location":"shape-cover/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-curve/","title":"Curve","text":""},{"location":"shape-curve/#introduction","title":"Introduction","text":"

Curve shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-curve/#usage","title":"Usage","text":""},{"location":"shape-curve/#create-shape-object","title":"Create shape object","text":"
var curve = scene.add.curve(x, y, path, fillColor);\n// var curve = scene.add.curve(x, y, path, fillColor, fillAlpha);\n
  • path : Path object.
"},{"location":"shape-curve/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCurve extends Phaser.GameObjects.Curve {\nconstructor(scene, x, y, path, fillColor, fillAlpha) {\nsuper(scene, x, y, path, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var curve = new MyCurve(scene, x, y, path, fillColor, fillAlpha);\n
"},{"location":"shape-curve/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = curve.fillColor;\nvar alpha = curve.fillAlpha;\n
    • Set
      curve.setFillStyle(color, alpha);\n
    • Clear
      curve.setFillStyle();\n
  • Stroke color
    • Get
      var color = curve.strokeColor;\n
    • Set
      curve.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      curve.setStrokeStyle();\n

No tint methods

Uses curve.setFillStyle(color, alpha) to change color.

"},{"location":"shape-curve/#alpha","title":"Alpha","text":"
  • Get
    var alpha = curve.alpha;\n
  • Set
    curve.setAlpha(alpha);\n// curve.alpha = alpha;\n
"},{"location":"shape-curve/#smoothness","title":"Smoothness","text":"

The number of points used when rendering it. Increase this value for smoother curves, at the cost of more polygons being rendered.

curve.setSmoothness(smoothness);\n
or
curve.smoothness = smoothness;\n

"},{"location":"shape-curve/#display-size","title":"Display size","text":"
  • Get
    var width = curve.displayWidth;\nvar height = curve.displayHeight;\n
  • Set
    curve.setDisplaySize(width, height);\n
    or
    curve.displayWidth = width;\ncurve.displayHeight = height;\n
"},{"location":"shape-curve/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-curve/#create-mask","title":"Create mask","text":"
var mask = curve.createGeometryMask();\n

See mask

"},{"location":"shape-curve/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-custom-progress/","title":"Custom progress","text":""},{"location":"shape-custom-progress/#introduction","title":"Introduction","text":"

Custom progress bar based on custom-shapes.

  • Author: Rex
  • Game object
"},{"location":"shape-custom-progress/#live-demos","title":"Live demos","text":"
  • React-circle-progress-bar
  • Round rectangle
  • Orb
  • Trapezoid Mask
  • Round rectangles mask
  • Slash effect with rexUI
  • Path segment animation
"},{"location":"shape-custom-progress/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-custom-progress/#install-plugin","title":"Install plugin","text":""},{"location":"shape-custom-progress/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcustomprogressplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcustomprogressplugin.min.js', true);\n
  • Add custom shapes object
    var customProgress = scene.add.rexCustomProgress(x, y, width, height, config);\n
"},{"location":"shape-custom-progress/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CustomProgressPlugin from 'phaser3-rex-plugins/plugins/customprogress-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCustomProgressPlugin',\nplugin: CustomProgressPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add custom shapes object
    var customProgress = scene.add.rexCustomProgress(x, y, width, height, config);\n
"},{"location":"shape-custom-progress/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CustomProgress from 'phaser3-rex-plugins/plugins/bbcodetext.js';\n
  • Add custom shapes object
    var customProgress = new CustomProgress(scene, x, y, width, height, config);\nscene.add.existing(customProgress);\n
"},{"location":"shape-custom-progress/#add-custom-shapes-object","title":"Add custom shapes object","text":"
var customProgress = scene.add.rexCustomProgress(x, y, width, height, {\n// type: 'rexCustomProgress',\n\ncreate: [\n{ name: name0, type: shapeType},\n{ name: name1, type: shapeType},\n...\n],\n\n// create: {\n//     shapeType: [name0, name1, ...],\n//     shapeType: number,\n//     shapeType: name,\n// },\n\n// create: function() {\n// \n// },\n\nupdate: function() {\n\n},\n\nvalue: 0,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},\n});\n

or

var customProgress = scene.add.rexCustomProgress({\n// x: 0,\n// y: 0,\n// width: 64,\n// height: 64,\n// type: 'rexCustomProgress',\n\ncreate: [\n{ name: name0, type: shapeType},\n{ name: name1, type: shapeType},\n...\n],\n\n// create: {\n//     shapeType: [name0, name1, ...],\n//     shapeType: number,\n//     shapeType: name,\n// },\n\n// create: function() {\n// \n// },\n\nupdate: function() {\n\n},\n\nvalue: 0,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\n\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • create : Callback to create shapes
    • An array of object with name and type
      { name: name0, type: shapeType }\n
      • shapeType :
        • 'arc' : Create Arc shape.
        • 'circle' : Create Circle shape.
        • 'ellipse' : Create Ellipse shape.
        • 'line' : Create Line shape.
        • 'lines' : Create Lines shape.
        • 'rectangle' : Create Rectangle shape.
        • 'roundRectangle' : Create Round rectangle shape.
        • 'triangle' : Create Triangle shape.
    • A plain object with shapeType: name, or shapeType: number
      • shapeType : arc, circle, ellipse, line, rectangle, triangle
      • nameArray : An array of unique string name for each shape.
      • name : An unique string name of this shape.
      • number : Amount of shapes to create.
    • A callback
      function() {\n// this : This custom shapes game object\nvar shape = this.createShape(shapeType, name);\nthis.addShape(shape);\n}\n
      • this.createShape(shapeType, name) : Crate a shape instance, with an unique name.
      • this.addShape(shape) : Add this shape instance to this custom custom shapes.
  • update : Callback when refresh
    function() {\n// this : This custom shapes game object     \nvar shapes = this.getShapes();\nvar shape = this.getShape(name);\n// ...\n// var isSizeChanged = this.isSizeChanged;\n\n// var fillColor = this.fillColor;\n// var fillAlpha = this.fillAlpha;\n// var lineWidth = this.lineWidth;\n// var strokeColor = this.strokeColor;\n// var strokeAlpha = this.strokeAlpha;\n// ...\n// var value = this.value;\n}\n
    • Shape instances : Change properties of shape instances.
      • this.getShapes() : Return all shapes in an array.
      • this.getShape(name) : Return a shape by the unique string name.
    • Is size changed : this.isSizeChanged
    • Fill style : this.fillColor, this.fillAlpha
    • Stroke style : this.strokeColor, this.strokeAlpha, this.lineWidth
    • Current progress value : this.value
  • value : 0 ~ 1, progress value. Default is 0.
  • easeValue : Parameters of easing value.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • valuechangeCallback : callback function when value changed.
    function(newValue, oldValue, customProgress) {\n}\n
"},{"location":"shape-custom-progress/#set-update-shape-callback","title":"Set update shape callback","text":"

See Shape class

"},{"location":"shape-custom-progress/#size","title":"Size","text":"

See Size

"},{"location":"shape-custom-progress/#styles","title":"Styles","text":"

See Styles

"},{"location":"shape-custom-progress/#recreate-shapes","title":"Recreate shapes","text":"

See Shape class

"},{"location":"shape-custom-progress/#progress-value","title":"Progress value","text":"
  • Get value
    var value = customProgress.getValue(min, max); // value : min ~ max\n
    or
    var value = customProgress.getValue(); // value: 0 ~ 1\n
    or
    var value = customProgress.value; // value: 0 ~ 1\n
  • Set value
    customProgress.setValue(value, min, max); // value: min ~ max\n
    or
    customProgress.setValue(value); // value: 0 ~ 1\n
    or
    customProgress.value = value; // value: 0 ~ 1\n
  • Increase value
    customProgress.addValue(inc, min, max); // inc: min ~ max\n
    or
    customProgress.addValue(inc); // inc: 0 ~ 1\n
    or
    customProgress.value += inc; // inc: 0 ~ 1\n
"},{"location":"shape-custom-progress/#ease-progress-value","title":"Ease progress value","text":"
  • Set ease duration
    customProgress.setEaseValueDuration(duration);\n
  • Set ease function
    customProgress.setEaseValueFunction(ease);\n
    • ease : Ease function.
  • Ease value to
    customProgress.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    customProgress.easeValueTo(value);  // value: 0 ~ 1\n
  • Ease value repeat
    customProgress.easeValueRepeat(from, to);  // from, to: 0 ~ 1\n// customProgress.easeValueRepeat(from, to, repeat, repeatDelay);\n
  • Stop ease
    customProgress.stopEaseValue();\n
"},{"location":"shape-custom-progress/#refresh","title":"Refresh","text":"

Redraw shapes when

  • Value changed : customProgress.setValue(newValue), customProgress.easeValueTo(newValue)
  • Resize : customProgress.resize(width, height)
  • Set dirty : customProgress.setDirty()
  • Set update shape callback : customProgress.setUpdateShapesCallback(callback)
"},{"location":"shape-custom-progress/#shape-class","title":"Shape class","text":"

See Shape class

"},{"location":"shape-custom-progress/#events","title":"Events","text":"
  • On value changed
    customProgress.on('valuechange', function(newValue, oldValue, customProgress){\n//\n}, scope);\n
"},{"location":"shape-custom-progress/#alpha","title":"Alpha","text":"
  • Get
    var alpha = customProgress.alpha;\n
  • Set
    customProgress.setAlpha(alpha);\n// customProgress.alpha = alpha;\n
"},{"location":"shape-custom-progress/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-custom-progress/#create-mask","title":"Create mask","text":"
var mask = customProgress.createGeometryMask();\n

See mask

"},{"location":"shape-custom-progress/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-custom-shapes/","title":"Custom shapes","text":""},{"location":"shape-custom-shapes/#introduction","title":"Introduction","text":"

Custom shapes on shape.

  • Author: Rex
  • Game object
"},{"location":"shape-custom-shapes/#live-demos","title":"Live demos","text":"
  • Speech bubble
  • Jigsaw
  • Checkbox
  • World to localXY
"},{"location":"shape-custom-shapes/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-custom-shapes/#install-plugin","title":"Install plugin","text":""},{"location":"shape-custom-shapes/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcustomshapesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcustomshapesplugin.min.js', true);\n
  • Add custom shapes object
    var customShapes = scene.add.rexCustomShapes(x, y, width, height, config);\n
"},{"location":"shape-custom-shapes/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CustomShapesPlugin from 'phaser3-rex-plugins/plugins/customshapes-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCustomShapesPlugin',\nplugin: CustomShapesPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add custom shapes object
    var customShapes = scene.add.rexCustomShapes(x, y, width, height, config);\n
"},{"location":"shape-custom-shapes/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CustomShapes from 'phaser3-rex-plugins/plugins/bbcodetext.js';\n
  • Add custom shapes object
    var customShapes = new CustomShapes(scene, x, y, width, height, config);\nscene.add.existing(customShapes);\n
"},{"location":"shape-custom-shapes/#add-custom-shapes-object","title":"Add custom shapes object","text":"
var customShapes = scene.add.rexCustomShapes(x, y, width, height, {\n// type: 'rexCustomShapes',\n\ncreate: [\n{ name: name0, type: shapeType},\n{ name: name1, type: shapeType},\n...\n],\n\n// create: {\n//     shapeType: [name0, name1, ...],\n//     shapeType: number,\n//     shapeType: name,\n// },\n\n// create: function() {\n// \n// },\n\nupdate: function() {\n\n},\n});\n

or

var customShapes = scene.add.rexCustomShapes({\n// x: 0,\n// y: 0,\n// width: 64,\n// height: 64,\n// type: 'rexCustomShapes',\n\ncreate: [\n{ name: name0, type: shapeType},\n{ name: name1, type: shapeType},\n...\n],\n\n// create: {\n//     shapeType: [name0, name1, ...],\n//     shapeType: number,\n//     shapeType: name,\n// },\n\n// create: function() {\n// \n// },\n\nupdate: function() {\n\n},\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • create : Callback to create shapes
    • An array of object with name and type
      { name: name0, type: shapeType }\n
      • shapeType :
        • 'arc' : Create Arc shape.
        • 'circle' : Create Circle shape.
        • 'ellipse' : Create Ellipse shape.
        • 'line' : Create Line shape.
        • 'lines' : Create Lines shape.
        • 'rectangle' : Create Rectangle shape.
        • 'roundRectangle' : Create Round rectangle shape.
        • 'triangle' : Create Triangle shape.
    • A plain object with shapeType: name, or shapeType: number
      • shapeType : arc, circle, ellipse, line, rectangle, triangle
      • nameArray : An array of unique string name for each shape.
      • name : An unique string name of this shape.
      • number : Amount of shapes to create.
    • A callback
      function() {\n// this : This custom shapes game object\nvar shape = this.createShape(shapeType, name);\nthis.addShape(shape);\n}\n
      • this.createShape(shapeType, name) : Crate a shape instance, with an unique name.
      • this.addShape(shape) : Add this shape instance to this custom custom shapes.
  • update : Callback when refresh
    function() {\n// this : This custom shapes game object     \nvar shapes = this.getShapes();\nvar shape = this.getShape(name);\n// ...\n// var isSizeChanged = this.isSizeChanged;\n\n// var fillColor = this.fillColor;\n// var fillAlpha = this.fillAlpha;\n// var lineWidth = this.lineWidth;\n// var strokeColor = this.strokeColor;\n// var strokeAlpha = this.strokeAlpha;\n}\n
    • Shape instances : Change properties of shape instances.
      • this.getShapes() : Return all shapes in an array.
      • this.getShape(name) : Return a shape by the unique string name.
    • Is size changed : this.isSizeChanged
    • Fill style : this.fillColor, this.fillAlpha
    • Stroke style : this.strokeColor, this.strokeAlpha, this.lineWidth
"},{"location":"shape-custom-shapes/#set-update-shape-callback","title":"Set update shape callback","text":"
customShapes.setUpdateShapesCallback(callback);\n
  • callback :
    function() {\n// this : This custom shapes game object     \nvar shapes = this.getShapes();\nvar shape = this.getShape(name);\n// ...\n// var isSizeChanged = this.isSizeChanged;\n}\n
    • Shape instances : Change properties of shape instances.
      • this.getShapes() : Return all shapes in an array.
      • this.getShape(name) : Return a shape by the unique string name.
    • Is size changed: this.isSizeChanged
"},{"location":"shape-custom-shapes/#size","title":"Size","text":"

customShapes.setSize(width, height);\n
or
customShapes.resize(width, height);\n
or
customShapes.width = width;\ncustomShapes.height = height;\n

Will set dirty and redraw shapes

"},{"location":"shape-custom-shapes/#styles","title":"Styles","text":"
  • Fill style
    customShapes.setFillStyle(color, alpha);\n
    or
    customShapes.fillColor = color;\ncustomShapes.fillAlpha = alpha;\n
  • Stroke style
    customShapes.setStrokeStyle(lineWidth, color, alpha);\n
    or
    customShapes.lineWidth = lineWidth;\ncustomShapes.strokeColor = color;\ncustomShapes.strokeAlpha = alpha;\n

Will set dirty and redraw shapes. Apply styles to shapes in update callback.

"},{"location":"shape-custom-shapes/#world-position-to-local-position","title":"World position to local position","text":"
var localXY = customShapes.worldToLocalXY(worldX, worldY); // localXY: {x, y}\n

or

var out = customShapes.worldToLocalXY(worldX, worldY, camera, out);\n
"},{"location":"shape-custom-shapes/#recreate-shapes","title":"Recreate shapes","text":"
  • Clear all shapes
    customShapes.clear();\n
  • Add new shape
    customShapes.createShape(shapeType, name);\n
    • shapeType :
      • 'arc' : Create Arc shape.
      • 'circle' : Create Circle shape.
      • 'ellipse' : Create Ellipse shape.
      • 'line' : Create Line shape.
      • 'lines' : Create Lines shape.
      • 'rectangle' : Create Rectangle shape.
      • 'roundRectangle' : Create Round rectangle shape.
      • 'triangle' : Create Triangle shape.
    • name : A string name of this shape.
"},{"location":"shape-custom-shapes/#refresh","title":"Refresh","text":"

Redraw shapes when

  • Resize : customShapes.resize(width, height)
    • customShapes.isSizeChanged will also be true.
  • Set fill color : customShapes.setFillStyle(color, alpha)
  • Set stroke color : customShapes.setStrokeStyle(lineWidth, color, alpha)
  • Set dirty : customShapes.setDirty()
  • Set update shape callback : customShapes.setUpdateShapesCallback(callback)
"},{"location":"shape-custom-shapes/#update-shape-data","title":"Update shape data","text":"

Shape data will be updated during rendering, or call shape.updateData() to update shape data before rendering.

"},{"location":"shape-custom-shapes/#shape-class","title":"Shape class","text":""},{"location":"shape-custom-shapes/#common-properties","title":"Common properties","text":"
  • Style
    • Get
      var fillColor = shape.fillColor;\nvar fillAlpha = shape.fillAlpha;\nvar lineWidth = shape.lineWidth;\nvar strokeColor = shape.strokeColor;\nvar strokeAlpha = shape.strokeAlpha;\n
    • Set
      shape.fillStyle(color, alpha);\nshape.lineStyle(lineWidth, color, alpha);\n
    • Clear
      shape.fillStyle().lineStyle();\n
  • Visible
    • Get
      var visible = shape.visible;\n
    • Set javascript shape.setVisible(visible);
  • Private data
    • Get
      var data = shape.getData(key);\n// var data = shape.getData(key, defaultValue);\n
    • Set
      shape.setData(key, value);\n
      or
      shape.setData({key:value, ...});\n
    • Inc
      shape.incData(key, incValue);\n// shape.incData(key, incValue, defaultValue);\n
    • Mul
      shape.mulData(key, mulValue);\n// shape.mulData(key, mulValue, defaultValue);\n
    • Clear
      shape.clearData();\n
  • Name
    • Get
      var name = shape.name;\n
"},{"location":"shape-custom-shapes/#line","title":"Line","text":"
  • End points
    • Get
      var x0 = line.x0;\nvar y0 = line.y0;\nvar x1 = line.x1;\nvar y1 = line.y1;\n
    • Set
      line.setP0(x, y);\nline.setP1(x, y);\n
      or
      line.x0 = x0;\nline.y0 = y0;\nline.x1 = x1;\nline.y1 = y1;\n
"},{"location":"shape-custom-shapes/#lines","title":"Lines","text":""},{"location":"shape-custom-shapes/#create-path","title":"Create path","text":"
  • Start, clear points data
    lines.start();\n
  • Start at position, clear points data
    lines.startAt(x, y);\n
  • Line to
    • To position
      lines.lineTo(x, y);\n
    • To relative position
      lines.lineTo(x, y, true);\n
    • To vertical position
      lines.verticalLineTo(x);\n
    • To relative vertical position
      lines.verticalLineTo(x, true);\n
    • To horizontal position
      lines.horizontalLineTo(y);\n
    • To relative horizontal position
      lines.horizontalLineTo(y, true);\n
  • Add arc composed of lines
    lines.arc(centerX, centerY, radius, startAngle, endAngle, anticlockwise);\n
    • startAngle, endAngle : Start and end angle in degrees.
  • Add elliptical arc composed of lines
    lines.ellipticalArc(centerX, centerY, radiusX, radiusY, startAngle, endAngle, anticlockwise);\n
    • startAngle, endAngle : Start and end angle in degrees.
  • Add quadratic bezier of lines
    lines.quadraticBezierTo(cx, cy, x, y);\n
    • cx, cy : Control point
    • x, y : End point
  • Add smooth quadratic bezier of lines
    lines.smoothQuadraticBezierTo(x, y);\n
    • x, y : End point
  • Add cubic bezier of lines
    lines.cubicBezierCurveTo(cx0, cy0, cx1, cy1, x, y);\n
    • cx0, cy0 : Control point0
    • cx1, cy1 : Control point1
    • x, y : End point
  • Add smooth cubic bezier of lines
    lines.smoothCubicBezierCurveTo(cx1, cy1, x, y);\n
    • cx1, cy1 : Control point1
    • x, y : End point
  • End commands
    • Close path, to fill color
      lines.close();\n
    • End path, to draw lines only
      lines.end();\n
  • Copy path from another lines
    lines.copyPathFrom(srcLine);\n
    or
    lines.copyPathFrom(srcLine, startT, endT);\n
  • Append path from another lines
    lines.appendPathFrom(srcLine);\n
    or
    lines.appendPathFrom(srcLine, startT, endT);\n
"},{"location":"shape-custom-shapes/#transform","title":"Transform","text":"
  • Offset all points
    lines.offset(x, y);\n
  • Rotation all points
    lines.rotateAround(centerX, centerY, angle);\n
    • angle : Rotate angle in degrees.
"},{"location":"shape-custom-shapes/#display-path-segment","title":"Display path segment","text":"
  1. Create path, under customShapes.isSizeChanged condition.
  2. Display segment of path
    lines.setDisplayPathSegment(startT, endT);\n
    or
    lines.setDisplayPathSegment(endT);  // startT = 0\n
    • startT, endT : 0~1. Start, end position on path, in percentage of path.
      • 0 : Start position of path
      • 1 : End position of path
"},{"location":"shape-custom-shapes/#misc","title":"Misc","text":"
  • Get polygon
    var polygon = lines.toPolygon();\n
    • Can be used in setInteractive method
      shape.setInteractive({\nhitArea: shape.getShapes()[0].toPolygon(),\nhitAreaCallback: Phaser.Geom.Polygon.Contains,\n})\n
  • Position of first or last point
    var p0x = lines.firstPointX;\nvar p0y = lines.firstPointY;\nvar pNx = lines.lastPointX;\nvar pNy = lines.lastPointY;\n
"},{"location":"shape-custom-shapes/#rectangle","title":"Rectangle","text":"
  • Top-left
    • Get
      var left = rectangle.x;\nvar top = rectangle.y;\n
    • Set
      rectangle.setTopLeftPosition(x, y);\n
      or
      rectangle.x = left;\nrectangle.y = top;\n
  • Center
    • Get
      var centerX = rectangle.centerX;\nvar centerY = rectangle.centerY;\n
    • Set
      rectangle.setCenterPosition(x, y);\n
      or
      rectangle.centerX = centerX;\nrectangle.centerY = centerY;\n
      • Will change rectangle.x, rectangle.y
  • Size
    • Get
      var width = rectangle.width;\nvar height = rectangle.height;\n
    • Set
      rectangle.setSize(width, height);\n
      or
      rectangle.width = width;\nrectangle.height = height;\n
"},{"location":"shape-custom-shapes/#round-rectangle","title":"Round rectangle","text":"
  • Top-left
    • Get
      var left = roundRectangle.x;\nvar top = roundRectangle.y;\n
    • Set
      roundRectangle.setTopLeftPosition(x, y);\n
      or
      roundRectangle.x = left;\nroundRectangle.y = top;\n
  • Center
    • Get
      var centerX = roundRectangle.centerX;\nvar centerY = roundRectangle.centerY;\n
    • Set
      roundRectangle.setCenterPosition(x, y);\n
      or
      roundRectangle.centerX = centerX;\nroundRectangle.centerY = centerY;\n
      • Will change roundRectangle.x, roundRectangle.y
  • Size
    • Get
      var width = roundRectangle.width;\nvar height = roundRectangle.height;\n
    • Set
      roundRectangle.setSize(width, height);\n
      or
      roundRectangle.width = width;\nroundRectangle.height = height;\n
  • Radius
    • Get
      var radius = roundRectangle.radius;\n
      or
      var radiusTL = roundRectangle.radiusTL;\nvar radiusTR = roundRectangle.radiusTR;\nvar radiusBL = roundRectangle.radiusBL;\nvar radiusBR = roundRectangle.radiusBR;\n
    • Set
      roundRectangle.setRadius(radius);\n// roundRectangle.radius = radius;\n
      or
      roundRectangle.setRadius({\ntl: radiusTL, tr: radiusTR,\nbl: radiusBL, br: radiusBR,\n});\n// roundRectangle.radiusTL = radiusTL;\n// roundRectangle.radiusTR = radiusTR;\n// roundRectangle.radiusBL = radiusBL;\n// roundRectangle.radiusBR = radiusBR;\n
      • radius :
        • 0 : No round corner
        • > 0 : Convex round corner
        • < 0 : Concave round corner
"},{"location":"shape-custom-shapes/#triangle","title":"Triangle","text":"
  • Vertices
    • Get
      var x0 = triangle.x0;\nvar y0 = triangle.x0;\nvar x1 = triangle.x1;\nvar y1 = triangle.x1;\nvar x2 = triangle.x2;\nvar y2 = triangle.x2;\n
    • Set
      triangle.setP0(x, y);\ntriangle.setP1(x, y);\ntriangle.setP2(x, y);\n
      or
      triangle.x0 = x0;\ntriangle.x0 = y0;\ntriangle.x1 = x1;\ntriangle.x1 = y1;\ntriangle.x2 = x2;\ntriangle.x2 = y2;\n
"},{"location":"shape-custom-shapes/#arc","title":"Arc","text":"
  • Center position
    • Get
      var x = arc.x;\nvar y = arc.y;\n
    • Set
      arc.setCenterPosition(x, y);\n
      or
      arc.x = x;\narc.y = y;\n
  • Radius
    • Get
      var radiusX = arc.radiusX;\nvar radiusY = arc.radiusY;\n
    • Set
      arc.setRadius(radiusX, radiusY);\n// arc.setRadius(radius);\n
      or
      arc.radiusX = radiusX;\narc.radiusY = radiusY;\n
  • Angles
    • Get
      var startAngle = arc.startAngle;\nvar endAngle = arc.endAngle;\nvar anticlockwise = arc.anticlockwise; // boolean        \n
    • Set
      arc.setAngle(startAngle, endAngle);  // anticlockwise = false\n// arc.setAngle(startAngle, endAngle, anticlockwise);\n
      or
      arc.startAngle = startAngle;\narc.endAngle = endAngle;\narc.anticlockwise = anticlockwise; // boolean\n
      • startAngle, endAngle : Start/end angle in degrees.
  • Pie
    • Get
      var pie = arc.pie; // boolean\n
    • Set
      arc.setPie();\n
      or
      arc.pie = true;\n
"},{"location":"shape-custom-shapes/#circle","title":"Circle","text":"
  • Center position
    • Get
      var x = circle.x;\nvar y = circle.y;\n
    • Set
      circle.setCenterPosition(x, y);\n
      or
      circle.x = x;\ncircle.y = y;\n
  • Radius
    • Get
      var radiusX = circle.radiusX;\nvar radiusY = circle.radiusY;\n
    • Set
      circle.setRadius(radiusX, radiusY);\n// arc.setRadius(radius);\n
      or
      circle.radiusX = radiusX;\ncircle.radiusY = radiusY;\n
"},{"location":"shape-custom-shapes/#ellipse","title":"Ellipse","text":"

The same as Circle.

"},{"location":"shape-custom-shapes/#alpha","title":"Alpha","text":"
  • Get
    var alpha = shape.alpha;\n
  • Set
    shape.setAlpha(alpha);\n// shape.alpha = alpha;\n
"},{"location":"shape-custom-shapes/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-custom-shapes/#create-mask","title":"Create mask","text":"
var mask = shape.createGeometryMask();\n

See mask

"},{"location":"shape-custom-shapes/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-custom-shapes/#compare-with-similar-plugins","title":"Compare with similar plugins","text":"
  • Custom Shapes : Draw shapes.
  • Custom Porgress : Similar with custom-shapes, plus a value property
  • Custom Spinner : Similar with custom-progress, plus a value tween task.
"},{"location":"shape-ellipse/","title":"Ellipse","text":""},{"location":"shape-ellipse/#introduction","title":"Introduction","text":"

Ellipse shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-ellipse/#usage","title":"Usage","text":""},{"location":"shape-ellipse/#create-shape-object","title":"Create shape object","text":"
var ellipse = scene.add.ellipse(x, y, width, height, fillColor);\n// var ellipse = scene.add.ellipse(x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-ellipse/#custom-class","title":"Custom class","text":"
  • Define class
    class MyEllipse extends Phaser.GameObjects.Ellipse {\nconstructor(scene, x, y, width, height, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var ellipse = new MyEllipse(scene, x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-ellipse/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = ellipse.fillColor;\nvar alpha = ellipse.fillAlpha;\n
    • Set
      ellipse.setFillStyle(color, alpha);\n
    • Clear
      ellipse.setFillStyle();\n
  • Stroke color
    • Get
      var color = ellipse.strokeColor;\n
    • Set
      ellipse.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      ellipse.setStrokeStyle();\n

No tint methods

Uses ellipse.setFillStyle(color, alpha) to change color.

"},{"location":"shape-ellipse/#alpha","title":"Alpha","text":"
  • Get
    var alpha = ellipse.alpha;\n
  • Set
    ellipse.setAlpha(alpha);\n// ellipse.alpha = alpha;\n
"},{"location":"shape-ellipse/#size","title":"Size","text":"
  • Get
    var width = ellipse.width;\nvar height = ellipse.height;\n
  • Set
    ellipse.setSize(width, height);\n
"},{"location":"shape-ellipse/#display-size","title":"Display size","text":"
  • Get
    var width = ellipse.displayWidth;\nvar height = ellipse.displayHeight;\n
  • Set
    ellipse.setDisplaySize(width, height);\n
    or
    ellipse.displayWidth = width;\nellipse.displayHeight = height;\n
"},{"location":"shape-ellipse/#smoothness","title":"Smoothness","text":"

The number of points used when rendering it. Increase this value for smoother curves, at the cost of more polygons being rendered.

ellipse.setSmoothness(smoothness);\n
or
ellipse.smoothness = smoothness;\n

"},{"location":"shape-ellipse/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-ellipse/#create-mask","title":"Create mask","text":"
var mask = ellipse.createGeometryMask();\n

See mask

"},{"location":"shape-ellipse/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-fullwindowrectangle/","title":"Full window rectangle","text":""},{"location":"shape-fullwindowrectangle/#introduction","title":"Introduction","text":"

Rectangle shape covered full window.

  • Author: Rex
  • Game object
"},{"location":"shape-fullwindowrectangle/#live-demos","title":"Live demos","text":"
  • Cover
"},{"location":"shape-fullwindowrectangle/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-fullwindowrectangle/#install-plugin","title":"Install plugin","text":""},{"location":"shape-fullwindowrectangle/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfullwindowrectangleplugin', 'https://raw.githubusercontent.com/rexrainbow/    phaser3-rex-notes/master/dist/rexfullwindowrectangleplugin.min.js', true);\n
  • Add shape object
    var rect = scene.add.rexFullWindowRectangle(fillColor, fillAlpha);\n
"},{"location":"shape-fullwindowrectangle/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FullWindowRectanglePlugin from 'phaser3-rex-plugins/plugins/fullwindowrectangle-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFullWindowRectanglePlugin',\nplugin: FullWindowRectanglePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add shape object
    var rect = scene.add.rexFullWindowRectangle(fillColor, fillAlpha);\n
"},{"location":"shape-fullwindowrectangle/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import FullWindowRectangle from 'phaser3-rex-plugins/plugins/fullwindowrectangle.js';\n
  • Add shape object
    var rect = new FullWindowRectangle(scene, fillColor, fillAlpha);\nscene.add.existing(rect);\n
"},{"location":"shape-fullwindowrectangle/#create-shape-object","title":"Create shape object","text":"
var rect = scene.add.rexFullWindowRectangle(fillColor, fillAlpha);\n
"},{"location":"shape-fullwindowrectangle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyFullWindowRectangle extends RexPlugins.GameObjects.FullWindowRectangle {\nconstructor(scene, fillColor, fillAlpha) {\nsuper(scene, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var rect = new MyFullWindowRectangle(scene, fillColor, fillAlpha);\n
"},{"location":"shape-fullwindowrectangle/#color","title":"Color","text":"
  • Tint
    • Get
      var tint = rect.tint;\n
    • Set
      rect.tint = tint;\n
  • Alpha
    • Get
      var alpha = rect.alpha;\n
    • Set
      rect.alpha = alpha;\n
  • Fill color
    • Get
      var color = rect.fillColor;\nvar alpha = rect.fillAlpha;\n
    • Set
      rect.setFillStyle(color, alpha);\n
    • Clear
      rect.setFillStyle();\n
"},{"location":"shape-fullwindowrectangle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-fullwindowrectangle/#create-mask","title":"Create mask","text":"
var mask = rect.createGeometryMask();\n

See mask

"},{"location":"shape-fullwindowrectangle/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-grid/","title":"Grid","text":""},{"location":"shape-grid/#introduction","title":"Introduction","text":"

Grid shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-grid/#usage","title":"Usage","text":""},{"location":"shape-grid/#create-shape-object","title":"Create shape object","text":"
var grid = scene.add.grid(x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha);\n
"},{"location":"shape-grid/#custom-class","title":"Custom class","text":"
  • Define class
    class MyGrid extends Phaser.GameObjects.Grid {\nconstructor(scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha) {\nsuper(scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var grid = new MyGrid(scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha);\n
"},{"location":"shape-grid/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = grid.fillColor;\nvar alpha = grid.fillAlpha;\n
    • Set
      grid.setFillStyle(color, alpha);\n
    • Clear
      grid.setFillStyle();\n
  • Stroke color
    • Get
      var color = grid.strokeColor;\n
    • Set
      grid.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      grid.setStrokeStyle();\n
  • Alternating color
    • Get
      var color = grid.altFillColor;\n
    • Set
      grid.setAltFillStyle(color, alpha);\n
    • Clear
      grid.setAltFillStyle();\n
  • Outline color
    • Get
      var color = grid.outlineFillColor;\n
    • Set
      grid.setOutlineStyle(color, alpha;\n
    • Clear
      grid.setOutlineStyle();\n

No tint methods

Uses grid.setFillStyle(color, alpha) to change color.

"},{"location":"shape-grid/#alpha","title":"Alpha","text":"
  • Get
    var alpha = grid.alpha;\n
  • Set
    grid.setAlpha(alpha);\n// grid.alpha = alpha;\n
"},{"location":"shape-grid/#display-size","title":"Display size","text":"
  • Get
    var width = grid.displayWidth;\nvar height = grid.displayHeight;\n
  • Set
    grid.setDisplaySize(width, height);\n
    or
    grid.displayWidth = width;\ngrid.displayHeight = height;\n
"},{"location":"shape-grid/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-grid/#create-mask","title":"Create mask","text":"
var mask = grid.createGeometryMask();\n

See mask

"},{"location":"shape-grid/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-isobox/","title":"Iso box","text":""},{"location":"shape-isobox/#introduction","title":"Introduction","text":"

Iso-box shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-isobox/#usage","title":"Usage","text":""},{"location":"shape-isobox/#create-shape-object","title":"Create shape object","text":"
var isoBox = scene.add.isobox(x, y, width, height, fillTop, fillLeft, fillRight);\n
"},{"location":"shape-isobox/#custom-class","title":"Custom class","text":"
  • Define class
    class MyIsoBox extends Phaser.GameObjects.IsoBox {\nconstructor(scene, x, y, width, height, fillTop, fillLeft, fillRight) {\nsuper(scene, x, y, width, height, fillTop, fillLeft, fillRight);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var isoBox = new MyIsoBox(scene, x, y, width, height, fillTop, fillLeft, fillRight);\n
"},{"location":"shape-isobox/#set-color","title":"Set color","text":"
  • Fill color
    isoBox.setFillStyle(fillTop, fillLeft, fillRight);\n
  • Show face
    isoBox.setFaces(showTop, showLeft, showRight);\n
    • showTop, showLeft, showRight: Set true to show that face

No tint methods

Uses isoBox.setFillStyle(fillTop, fillLeft, fillRight) to change color.

"},{"location":"shape-isobox/#alpha","title":"Alpha","text":"
  • Get
    var alpha = isoBox.alpha;\n
  • Set
    isoBox.setAlpha(alpha);\n// isoBox.alpha = alpha;\n
"},{"location":"shape-isobox/#projection","title":"Projection","text":"
  • Get
    var projection = isoBox.projection;\n
  • Set
    isoBox.setProjection(value)\n
    or
    isoBox.projection = value;\n
"},{"location":"shape-isobox/#display-size","title":"Display size","text":"
  • Get
    var width = isoBox.displayWidth;\nvar height = isoBox.displayHeight;\n
  • Set
    isoBox.setDisplaySize(width, height);\n
    or
    isoBox.displayWidth = width;\nisoBox.displayHeight = height;\n
"},{"location":"shape-isobox/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-isobox/#create-mask","title":"Create mask","text":"
var mask = isoBox.createGeometryMask();\n

See mask

"},{"location":"shape-isobox/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-isotriangle/","title":"Iso triangle","text":""},{"location":"shape-isotriangle/#introduction","title":"Introduction","text":"

Iso-triangle shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-isotriangle/#usage","title":"Usage","text":""},{"location":"shape-isotriangle/#create-shape-object","title":"Create shape object","text":"
var isoTriangle = scene.add.isotriangle(x, y, width, height, reversed, fillTop, fillLeft, fillRight);\n
"},{"location":"shape-isotriangle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyIsoTriangle extends Phaser.GameObjects.IsoTriangle {\nconstructor(scene, x, y, width, height, reversed, fillTop, fillLeft, fillRight) {\nsuper(scene, x, y, width, height, reversed, fillTop, fillLeft, fillRight);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var isoTriangle = new MyIsoTriangle(scene, x, y, width, height, reversed, fillTop, fillLeft, fillRight);\n
"},{"location":"shape-isotriangle/#set-color","title":"Set color","text":"
  • Fill color
    isoTriangle.setFillStyle(fillTop, fillLeft, fillRight);\n
  • Show face
    isoTriangle.setFaces(showTop, showLeft, showRight);\n
    • showTop, showLeft, showRight: Set true to show that face

No tint methods

Uses isoTriangle.setFillStyle(fillTop, fillLeft, fillRight) to change color.

"},{"location":"shape-isotriangle/#alpha","title":"Alpha","text":"
  • Get
    var alpha = isoTriangle.alpha;\n
  • Set
    isoTriangle.setAlpha(alpha);\n// isoTriangle.alpha = alpha;\n
"},{"location":"shape-isotriangle/#projection","title":"Projection","text":"
  • Get
    var projection = isoTriangle.projection;\n
  • Set
    isoTriangle.setProjection(value)\n
    or
    isoTriangle.projection = value;\n
"},{"location":"shape-isotriangle/#reverse","title":"Reverse","text":"
  • Get
    var isReversed = isoTriangle.isReversed;\n
  • Set
    isoTriangle.setReversed(reversed);\n
    or
    isoTriangle.reversed = reversed;\n
  • Set true to render upside down.
"},{"location":"shape-isotriangle/#display-size","title":"Display size","text":"
  • Get
    var width = isoTriangle.displayWidth;\nvar height = isoTriangle.displayHeight;\n
  • Set
    isoTriangle.setDisplaySize(width, height);\n
    or
    isoTriangle.displayWidth = width;\nisoTriangle.displayHeight = height;\n
"},{"location":"shape-isotriangle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-isotriangle/#create-mask","title":"Create mask","text":"
var mask = isoTriangle.createGeometryMask();\n

See mask

"},{"location":"shape-isotriangle/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-line/","title":"Line","text":""},{"location":"shape-line/#introduction","title":"Introduction","text":"

Line shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-line/#usage","title":"Usage","text":""},{"location":"shape-line/#create-shape-object","title":"Create shape object","text":"
var line = scene.add.line(x, y, x1, y1, x2, y2, strokeColor);\n// var line = scene.add.line(x, y, x1, y1, x2, y2, strokeColor, strokeAlpha);\n
"},{"location":"shape-line/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCurve extends Phaser.GameObjects.Line {\nconstructor(scene, x, y, x1, y1, x2, y2, strokeColor) {\nsuper(scene, x, y, x1, y1, x2, y2, strokeColor);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var line = new MyLine(scene, x, y, x1, y1, x2, y2, strokeColor);\n
"},{"location":"shape-line/#set-color","title":"Set color","text":"
  • Fill color
    • Get
      var color = line.fillColor;\nvar alpha = line.fillAlpha;\n
    • Set
      line.setFillStyle(color, alpha);\n
    • Clear
      line.setFillStyle();\n
  • Stroke color
    • Get
      var color = line.strokeColor;\n
    • Set
      line.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      line.setStrokeStyle();\n

No tint methods

Uses line.setFillStyle(color, alpha) to change color.

"},{"location":"shape-line/#alpha","title":"Alpha","text":"
  • Get
    var alpha = line.alpha;\n
  • Set
    line.setAlpha(alpha);\n// line.alpha = alpha;\n
"},{"location":"shape-line/#set-end-points","title":"Set end points","text":"
line.setTo(x1, y1, x2, y2);\n
"},{"location":"shape-line/#line-width","title":"Line width","text":"
line.setLineWidth(startWidth, endWidth);\n
  • endWidth : The end width of the line. Only used in WebGL.
"},{"location":"shape-line/#display-size","title":"Display size","text":"
  • Get
    var width = line.displayWidth;\nvar height = line.displayHeight;\n
  • Set
    line.setDisplaySize(width, height);\n
    or
    line.displayWidth = width;\nline.displayHeight = height;\n
"},{"location":"shape-line/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-line/#create-mask","title":"Create mask","text":"
var mask = line.createGeometryMask();\n

See mask

"},{"location":"shape-line/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-lineprogress/","title":"Line progress","text":""},{"location":"shape-lineprogress/#introduction","title":"Introduction","text":"

Horizontal line progress bar shape.

  • Author: Rex
  • Game object
"},{"location":"shape-lineprogress/#live-demos","title":"Live demos","text":"
  • Line-progress
"},{"location":"shape-lineprogress/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-lineprogress/#install-plugin","title":"Install plugin","text":""},{"location":"shape-lineprogress/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlineprogressplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlineprogressplugin.min.js', true);\n
  • Add line-progress object
    var lineProgress = scene.add.rexLineProgress(x, y, width, height, barColor, value, config);\n
"},{"location":"shape-lineprogress/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LineProgressPlugin from 'phaser3-rex-plugins/plugins/lineprogress-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLineProgressPlugin',\nplugin: LineProgressPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add line-progress object
    var lineProgress = scene.add.rexLineProgress(x, y, width, height, barColor, value, config);\n
"},{"location":"shape-lineprogress/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LineProgress from 'phaser3-rex-plugins/plugins/lineprogress.js';\n
  • Add line-progress object
    var lineProgress = new LineProgress(scene, x, y, width, height, barColor, value, config);\nscene.add.existing(lineProgress);\n
"},{"location":"shape-lineprogress/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLineProgressPlugin',\nplugin: LineProgressPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"shape-lineprogress/#create-instance","title":"Create instance","text":"
var lineProgress = scene.add.rexLineProgress(x, y, width, height, barColor, value, {    trackColor: undefined,\ntrackStrokeColor: undefined,\ntrackStrokeThickness: 2,\n\nskewX:0,\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, lineProgress) {\n},\n});\n

or

var lineProgress = scene.add.rexLineProgress({\nx: 0,\ny: 0,\nwidth: 2,\nheight: 2,\n\nbarColor: undefined,\ntrackColor: undefined,\ntrackStrokeColor: undefined,\ntrackStrokeThickness: 2,\n\nskewX:0,\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvalue: 0,\nvaluechangeCallback: function(newValue, oldValue, lineProgress) {\n},\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • barColor : Fill color of line bar, in number or css string value.
  • trackColor : Fill color of line track, in number or css string value.
  • trackStrokeColor : Stroke color of track, in number or css string value.
  • trackStrokeThickness : Stroke line width of track.
  • skewX : Horizontal skew of track and bar.
  • rtl :
    • false : Bar starts from left side. Default behavior.
    • true : Bar starts from right side.
  • value : 0 ~ 1, progress value. Default is 0.
  • easeValue : Parameters of easing value.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • valuechangeCallback : callback function when value changed.
    function(newValue, oldValue, lineProgress) {\n}\n

Add line-progress from JSON

var lineProgress = scene.make.rexLineProgress({\nx: 0,\ny: 0,\nwidth: 2,\nheight: 2,\n\nbarColor: undefined,\ntrackColor: undefined,\ntrackStrokeColor: undefined,\ntrackStrokeThickness: 2,\n\nskewX:0,\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvalue: 0,\nvaluechangeCallback: function(newValue, oldValue, lineProgress) {\n},\n\nadd: true\n});\n
"},{"location":"shape-lineprogress/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLineProgress extends LineProgress {\nconstructor(scene, x, y, width, height, barColor, value, config) {\nsuper(scene, x, y, width, height, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var lineProgress = new MyLineProgress(scene, x, y, width, height, barColor, value, config);\n
"},{"location":"shape-lineprogress/#progress-value","title":"Progress value","text":"
  • Get value
    var value = lineProgress.getValue(min, max); // value : min ~ max\n
    or
    var value = lineProgress.getValue(); // value: 0 ~ 1\n
    or
    var value = lineProgress.value; // value: 0 ~ 1\n
  • Set value
    lineProgress.setValue(value, min, max); // value: min ~ max\n
    or
    lineProgress.setValue(value); // value: 0 ~ 1\n
    or
    lineProgress.value = value; // value: 0 ~ 1\n
  • Increase value
    lineProgress.addValue(inc, min, max); // inc: min ~ max\n
    or
    lineProgress.addValue(inc); // inc: 0 ~ 1\n
    or
    lineProgress.value += inc; // inc: 0 ~ 1\n
"},{"location":"shape-lineprogress/#ease-progress-value","title":"Ease progress value","text":"
  • Ease value to
    lineProgress.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    lineProgress.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    lineProgress.stopEaseValue();\n
  • Set ease duration
    lineProgress.setEaseValueDuration(duration);\n
  • Set ease function
    lineProgress.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"shape-lineprogress/#line-track","title":"Line track","text":"
  • Color
    • Get
      var trackColor = lineProgress.trackColor;\n
    • Set
      lineProgress.setTrackColor(trackColor);\n// lineProgress.trackColor = trackColor;\n
  • Stroke
    • Get
      var trackStrokeColor = lineProgress.trackStrokeColor;\nvar trackStrokeThickness = lineProgress.trackStrokeThickness;\n
    • Set
      lineProgress.setTrackColor(color);\nlineProgress.setTrackStroke(lineWidth, color);\n
"},{"location":"shape-lineprogress/#line-bar","title":"Line bar","text":"
  • Color
    • Get
      var barColor = lineProgress.barColor;\n
    • Set
      lineProgress.setBarColor(barColor);\n// lineProgress.barColor = barColor;\n
"},{"location":"shape-lineprogress/#horizontal-skew","title":"Horizontal skew","text":"
  • Get
    var skewX = lineProgress.skewX;\n
  • Set
    lineProgress.setSkewX(skewX);\n// lineProgress.skewX = skewX;\n
"},{"location":"shape-lineprogress/#right-to-left","title":"Right-to-left","text":"
  • Get
    var rtl = lineProgress.rtl;\n
  • Set
    lineProgress.setRTL(rtl);\n// lineProgress.rtl = rtl;\n
"},{"location":"shape-lineprogress/#events","title":"Events","text":"
  • On value changed
    lineProgress.on('valuechange', function(newValue, oldValue, lineProgress){\n//\n}, scope);\n
"},{"location":"shape-lineprogress/#alpha","title":"Alpha","text":"
  • Get
    var alpha = lineProgress.alpha;\n
  • Set
    lineProgress.setAlpha(alpha);\n// lineProgress.alpha = alpha;\n
"},{"location":"shape-lineprogress/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-lineprogress/#create-mask","title":"Create mask","text":"
var mask = lineProgress.createGeometryMask();\n

See mask

"},{"location":"shape-lineprogress/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-polygon/","title":"Polygon","text":""},{"location":"shape-polygon/#introduction","title":"Introduction","text":"

Polygon shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-polygon/#usage","title":"Usage","text":""},{"location":"shape-polygon/#create-shape-object","title":"Create shape object","text":"
var polygon = scene.add.polygon(x, y, points, fillColor);\n// var polygon = scene.add.polygon(x, y, points, fillColor, fillAlpha);\n
  • points :
    • An array of number : [x0, y0, x1, y1, ...]
    • An array of points : [{x:x0, y:y0}, {x:x1, y:y1}, ...]
    • A string : 'x0 y0 x1 y1 ...'

Note

Shift given points to align position (0, 0)

"},{"location":"shape-polygon/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPolygon extends Phaser.GameObjects.Polygon {\nconstructor(scene, x, y, points, fillColor) {\nsuper(scene, x, y, points, fillColor);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var polygon = new MyPolygon(scene, x, y, points, fillColor);\n
"},{"location":"shape-polygon/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = polygon.fillColor;\nvar alpha = polygon.fillAlpha;\n
    • Set
      polygon.setFillStyle(color, alpha);\n
    • Clear
      polygon.setFillStyle();\n
  • Stroke color
    • Get
      var color = polygon.strokeColor;\n
    • Set
      polygon.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      polygon.setStrokeStyle();\n

No tint methods

Uses polygon.setFillStyle(color, alpha) to change color.

"},{"location":"shape-polygon/#alpha","title":"Alpha","text":"
  • Get
    var alpha = polygon.alpha;\n
  • Set
    polygon.setAlpha(alpha);\n// polygon.alpha = alpha;\n
"},{"location":"shape-polygon/#smooth","title":"Smooth","text":"

Smooths the polygon over the number of iterations specified.

polygon.smooth(iterations);\n
"},{"location":"shape-polygon/#set-points","title":"Set points","text":"
polygon.setTo(points);\n
  • point :
    • A string containing paired values separated by a single space : '40 0 40 20 100 20 100 80 40 80 40 100 0 50'
    • An array of Point objects : [new Phaser.Point(x1, y1), ...]
    • An array of objects with public x/y properties : [obj1, obj2, ...]
    • An array of paired numbers that represent point coordinates : [x1,y1, x2,y2, ...]
    • An array of arrays with two elements representing x/y coordinates : [[x1, y1], [x2, y2], ...]
"},{"location":"shape-polygon/#display-size","title":"Display size","text":"
  • Get
    var width = polygon.displayWidth;\nvar height = polygon.displayHeight;\n
  • Set
    polygon.setDisplaySize(width, height);\n
    or
    polygon.displayWidth = width;\npolygon.displayHeight = height;\n
"},{"location":"shape-polygon/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-polygon/#create-mask","title":"Create mask","text":"
var mask = polygon.createGeometryMask();\n

See mask

"},{"location":"shape-polygon/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-quad/","title":"Quad","text":""},{"location":"shape-quad/#introduction","title":"Introduction","text":"

Quad shape, offsets can be given on four vertices, and additional points can be added on the four sides.

  • Author: Rex
  • Game object
"},{"location":"shape-quad/#live-demos","title":"Live demos","text":"
  • Ease vertices
  • Ease side-points
"},{"location":"shape-quad/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-quad/#install-plugin","title":"Install plugin","text":""},{"location":"shape-quad/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquadshapeplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquadshapeplugin.min.js', true);\n
  • Add shape object
    var quad = scene.add.rexQuadShape(x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-quad/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuadShapePlugin from 'phaser3-rex-plugins/plugins/quadshape-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuadShapePlugin',\nplugin: QuadShapePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add shape object
    var quad = scene.add.rexQuadShape(x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-quad/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import QuadShape from 'phaser3-rex-plugins/plugins/quadshape.js';\n
  • Add shape object
    var quad = new QuadShape(scene, x, y, width, height, fillColor, fillAlpha);\nscene.add.existing(quad);\n
"},{"location":"shape-quad/#create-shape-object","title":"Create shape object","text":"
var quad = scene.add.rexQuadShape(x, y, width, height, fillColor, fillAlpha);\n

or

var quad = scene.add.rexQuadShape({\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\n\ncolor: undefined,\nalpha: undefined,\n\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: 2,\n\ntlx: 0,\ntly: 0,\ntrx: 0,\ntry: 0,\nblx: 0,\nbly: 0,\nbrx: 0,\nbry: 0,\n\nleftSidePoints: [\n// {t, x, y, key},\n// {t, x, y, key},\n// ...\n],\nrightSidePoints: [\n// {t, x, y, key},\n// {t, x, y, key},\n// ...\n],\ntopSidePoints: [\n// {t, x, y, key},\n// {t, x, y, key},\n// ...\n],\nbottomSidePoints: [\n// {t, x, y, key},\n// {t, x, y, key},\n// ...\n],\n});\n
  • width, height : Size of quadangle.
    • undefined : Set ot undefined to draw a circle.
  • tlx, tly : Offset of top-left vertex.
  • trx, try : Offset of top-right vertex.
  • blx, bly : Offset of bottom-left vertex.
  • brx, bry : Offset of bottom-right vertex.
  • leftSidePoints, rightSidePoints, topSidePoints, bottomSidePoints : A list of points, additional points on left-side/right-side/top-side/bottom-side.
    {\nt, x, y, key\n}\n
    • t : Position in percent of edge.
    • x, y : Offset of this point on edge.
    • key :
      • undefined : Ignore this feature. Default value.
      • A string: Inject key+'\uff38', key+'Y', key+'T' properties into this quad shape game object.
"},{"location":"shape-quad/#custom-class","title":"Custom class","text":"
  • Define class
    class MyQuadShape extends RexPlugins.GameObjects.QuadShape {\nconstructor(scene, x, y, width, height, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var quad = new MyQuadShape(scene, x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-quad/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = quad.fillColor;\nvar alpha = quad.fillAlpha;\n
    • Set
      quad.setFillStyle(color, alpha);\n
    • Clear
      quad.setFillStyle();\n
  • Stroke color
    • Get
      var color = quad.strokeColor;\n
    • Set
      quad.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      quad.setStrokeStyle();\n

No tint methods

Uses quad.setFillStyle(color, alpha) to change color.

"},{"location":"shape-quad/#alpha","title":"Alpha","text":"
  • Get
    var alpha = quad.alpha;\n
  • Set
    quad.setAlpha(alpha);\n// quad.alpha = alpha;\n
"},{"location":"shape-quad/#size","title":"Size","text":"
  • Get
    var width = quad.width;\nvar height = quad.height;\n
  • Set
    quad.setSize(width, height);\n
    or
    quad.width = width;\nquad.height = height;\n
"},{"location":"shape-quad/#display-size","title":"Display size","text":"
  • Get
    var width = quad.displayWidth;\nvar height = quad.displayHeight;\n
  • Set
    quad.setDisplaySize(width, height);\n
    or
    quad.displayWidth = width;\nquad.displayHeight = height;\n
"},{"location":"shape-quad/#position-of-vertices","title":"Position of vertices","text":"
  • Top-left vertex
    • Get
      var x = quad.tlx;\nvar y = quad.tly;\n
    • Set
      quad.setTLPosition(x, y);\n
      or
      quad.tlx = x;\nquad.tly = y;\n
  • Top-right vertex
    • Get
      var x = quad.trx;\nvar y = quad.try;\n
    • Set
      quad.setTRPosition(x, y);\n
      or
      quad.trx = x;\nquad.try = y;\n
  • Bottom-left vertex
    • Get
      var x = quad.blx;\nvar y = quad.bly;\n
    • Set
      quad.setBLPosition(x, y);\n
      or
      quad.blx = x;\nquad.bly = y;\n
  • Bottom-right vertex
    • Get
      var x = quad.brx;\nvar y = quad.bry;\n
    • Set
      quad.setBRPosition(x, y);\n
      or
      quad.brx = x;\nquad.bry = y;\n
"},{"location":"shape-quad/#position-of-side-points","title":"Position of side points","text":"
  • Top side
    quad.insertTopSidePoint(t, x, y);\n// quad.insertTopSidePoint(t, x, y, key);\n// quad.insertTopSidePoint({t, x, y, key});\n
    • t : Position in percent of edge.
    • x, y : Offset of this point on edge.
    • key : - undefined : Ignore this feature. Default value. - A string: Inject key+'\uff38', key+'Y', key+'T' properties into this quad shape game object.
  • Right side
    quad.insertRightSidePoint(t, x, y);\n// quad.insertRightSidePoint(t, x, y, key);\n// quad.insertRightSidePoint({t, x, y, key});\n
    • t : Position in percent of edge.
    • x, y : Offset of this point on edge.
    • key : - undefined : Ignore this feature. Default value. - A string: Inject key+'\uff38', key+'Y', key+'T' properties into this quad shape game object.
  • Bottom side
    quad.insertBottomSidePoint(t, x, y);\n// quad.insertBottomSidePoint(t, x, y, key);\n// quad.insertBottomSidePoint({t, x, y, key});\n
    • t : Position in percent of edge.
    • x, y : Offset of this point on edge.
    • key : - undefined : Ignore this feature. Default value. - A string: Inject key+'\uff38', key+'Y', key+'T' properties into this quad shape game object.
  • Left side
    quad.insertLeftSidePoint(t, x, y);\n// quad.insertLeftSidePoint(t, x, y, key);\n// quad.insertLeftSidePoint({t, x, y, key});\n
    • t : Position in percent of edge.
    • x, y : Offset of this point on edge.
    • key : - undefined : Ignore this feature. Default value. - A string: Inject key+'\uff38', key+'Y', key+'T' properties into this quad shape game object.
"},{"location":"shape-quad/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-quad/#create-mask","title":"Create mask","text":"
var mask = quad.createGeometryMask();\n

See mask

"},{"location":"shape-quad/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-rectangle/","title":"Rectangle","text":""},{"location":"shape-rectangle/#introduction","title":"Introduction","text":"

Rectangle shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-rectangle/#usage","title":"Usage","text":""},{"location":"shape-rectangle/#create-shape-object","title":"Create shape object","text":"
var rect = scene.add.rectangle(x, y, width, height, fillColor);\n// var rect = scene.add.rectangle(x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-rectangle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyRectangle extends Phaser.GameObjects.Rectangle {\nconstructor(scene, x, y, width, height, fillColor) {\nsuper(scene, x, y, width, height, fillColor);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var rect = new MyRectangle(scene, x, y, width, height, fillColor);\n
"},{"location":"shape-rectangle/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = rect.fillColor;\nvar alpha = rect.fillAlpha;\n
    • Set
      rect.setFillStyle(color, alpha);        
    • Clear
      rect.setFillStyle();\n
  • Stroke color
    • Get
      var color = rect.strokeColor;\n
    • Set
      rect.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      rect.setStrokeStyle();\n

No tint methods

Uses rect.setFillStyle(color, alpha) to change color.

"},{"location":"shape-rectangle/#alpha","title":"Alpha","text":"
  • Get
    var alpha = rect.alpha;\n
  • Set
    rect.setAlpha(alpha);\n// rect.alpha = alpha;\n
"},{"location":"shape-rectangle/#size","title":"Size","text":"
  • Get
    var width = rect.width;\nvar height = rect.height;\n
  • Set
    rect.setSize(width, height);\n
    or
    rect.width = width;\nrect.height = height;\n
"},{"location":"shape-rectangle/#display-size","title":"Display size","text":"
  • Get
    var width = rect.displayWidth;\nvar height = rect.displayHeight;\n
  • Set
    rect.setDisplaySize(width, height);\n
    or
    rect.displayWidth = width;\nrect.displayHeight = height;\n
"},{"location":"shape-rectangle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-rectangle/#create-mask","title":"Create mask","text":"
var mask = rect.createGeometryMask();\n

See mask

"},{"location":"shape-rectangle/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-roundrectangle/","title":"Round Rectangle","text":""},{"location":"shape-roundrectangle/#introduction","title":"Introduction","text":"

Round rectangle shape.

  • Author: Rex
  • Game object
"},{"location":"shape-roundrectangle/#live-demos","title":"Live demos","text":"
  • Round rectangle
"},{"location":"shape-roundrectangle/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-roundrectangle/#install-plugin","title":"Install plugin","text":""},{"location":"shape-roundrectangle/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexroundrectangleplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexroundrectangleplugin.min.js', true);\n
  • Add shape object
    var rect = scene.add.rexRoundRectangle(x, y, width, height, radius, fillColor, fillAlpha);\n
"},{"location":"shape-roundrectangle/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RoundRectanglePlugin from 'phaser3-rex-plugins/plugins/roundrectangle-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRoundRectanglePlugin',\nplugin: RoundRectanglePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add shape object
    var rect = scene.add.rexRoundRectangle(x, y, width, height, radius, fillColor, fillAlpha);\n
"},{"location":"shape-roundrectangle/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RoundRectangle from 'phaser3-rex-plugins/plugins/roundrectangle.js';\n
  • Add shape object
    var rect = new RoundRectangle(scene, x, y, width, height, radius, fillColor, fillAlpha);\nscene.add.existing(rect);\n
"},{"location":"shape-roundrectangle/#create-shape-object","title":"Create shape object","text":"
var rect = scene.add.rexRoundRectangle(x, y, width, height, radius, fillColor, fillAlpha);\n

or

var rect = scene.add.rexRoundRectangle({\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\nradius: 0,\n\ncolor: undefined,\nalpha: undefined,\n\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: 2\n});\n
  • width, height : Size of rectangle.
    • undefined : Set ot undefined to draw a circle.
  • radius : Radius of four corners.
    • 0, or undefined : Disable round corner.
    • Number: 4 corners with the same radius.
    • JSON
      • 4 corners with the same radius X/Y
        {\nx: radiusX,\ny: radiusY\n}\n
      • Eeach radius of corner
        {\ntl: radius,\ntr: radius,\nbl: radius,\nbr: radius\n}\n
        or
        {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n}\n
      • Radius and iteration
        {\nradius: radius,\niteration: 0\n}\n
        or
        {\nradius: {x: radiusX, y: radiusY},\niteration: 0\n}\n
        or
        {\nradius: {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n},\niteration: 0\n}\n
        • radius :
          • 0 : No round corner
          • > 0 : Convex round corner
          • < 0 : Concave round corner
        • iteration : Number of interpolation points in each round corner. Default value is 4.
          • 0 : Draw a straight line instead of arc.
"},{"location":"shape-roundrectangle/#deform","title":"Deform","text":"
  • Rectangle, set radius of 4 corners to 0.
    var rect = scene.add.rexRoundRectangle(x, y,  width, height, 0, fillColor, fillAlpha);\n
  • Circle, set width and height to undefined.
    var rect = scene.add.rexRoundRectangle(x, y, undefined, undefined, radius, fillColor, fillAlpha);\n
  • Ellipse, set width and height to undefined, and radiusX/radiusY.
    var rect = scene.add.rexRoundRectangle(x, y, undefined, undefined, {x: radiusX, y: radiusY}, fillColor, fillAlpha);\n
  • Rhombus, set width and height to undefined, and assign iteration to 0
    var rect = scene.add.rexRoundRectangle(x, y, undefined, undefined, {\nradius: radius,\niteration: 0\n}, fillColor, fillAlpha);\n
  • Octagon, assign iteration to 0
    var rect = scene.add.rexRoundRectangle(x, y, width, height, {\nradius: radius,\niteration: 0\n}, fillColor, fillAlpha);\n
"},{"location":"shape-roundrectangle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyRoundRectangle extends RexPlugins.GameObjects.RoundRectangle {\nconstructor(scene, x, y, width, height, radius, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, radius, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var rect = new MyRoundRectangle(scene, x, y, width, height, radius, fillColor, fillAlpha);\n
"},{"location":"shape-roundrectangle/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = rect.fillColor;\nvar alpha = rect.fillAlpha;\n
    • Set
      rect.setFillStyle(color, alpha);\n
    • Clear
      rect.setFillStyle();\n
  • Stroke color
    • Get
      var color = rect.strokeColor;\n
    • Set
      rect.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      rect.setStrokeStyle();\n

No tint methods

Uses rect.setFillStyle(color, alpha) to change color.

"},{"location":"shape-roundrectangle/#alpha","title":"Alpha","text":"
  • Get
    var alpha = rect.alpha;\n
  • Set
    rect.setAlpha(alpha);\n// rect.alpha = alpha;\n
"},{"location":"shape-roundrectangle/#size","title":"Size","text":"
  • Get
    var width = rect.width;\nvar height = rect.height;\n
  • Set
    rect.setSize(width, height);\n
    or
    rect.width = width;\nrect.height = height;\n
"},{"location":"shape-roundrectangle/#display-size","title":"Display size","text":"
  • Get
    var width = rect.displayWidth;\nvar height = rect.displayHeight;\n
  • Set
    rect.setDisplaySize(width, height);\n
    or
    rect.displayWidth = width;\nrect.displayHeight = height;\n
"},{"location":"shape-roundrectangle/#radius","title":"Radius","text":"
  • Get
    var radius = rect.radius;\nvar radiusTL = rect.radiusTL;\nvar radiusTR = rect.radiusTR;\nvar radiusBL = rect.radiusBL;\nvar radiusBR = rect.radiusBR;\n
    or
    var cornerRadius = rect.cornerRadius;\n
    • radius : Number, maximum radius of 4 corners.
    • cornerRadius : JSON object of 4 corners.
      {\ntl: {x : radiusX, y: radiusY, convex : true},\ntr: {x : radiusX, y: radiusY, convex : true},\nbl: {x : radiusX, y: radiusY, convex : true},\nbr: {x : radiusX, y: radiusY, convex : true},\n}\n
  • Set
    rect.setRadius(value);\nrect.setRadiusTL(value);  // number, or {x,y}\nrect.setRadiusTR(value);  // number, or {x,y}\nrect.setRadiusBL(value);  // number, or {x,y}\nrect.setRadiusBR(value);  // number, or {x,y}\n
    or
    rect.radius = radius;\nrect.radiusTL = radius;  // number, or {x,y}\nrect.radiusTR = radius;  // number, or {x,y}\nrect.radiusBL = radius;  // number, or {x,y}\nrect.radiusBR = radius;  // number, or {x,y}\n
    • radius :
      • Number : 4 corners with the same radius.
        • 0 : No round corner
        • > 0 : Convex round corner
        • < 0 : Concave round corner
      • JSON
        • 4 corners with the same radius X/Y
          {\nx: radiusX,\ny: radiusY\n}\n
        • Eeach radius of corner
          {\ntl: radius,\ntr: radius,\nbl: radius,\nbr: radius\n}\n
          or ```javascript { tl: {x : radiusX, y: radiusY}, tr: {x : radiusX, y: radiusY}, bl: {x : radiusX, y: radiusY}, br: {x : radiusX, y: radiusY}, }
"},{"location":"shape-roundrectangle/#iteration","title":"Iteration","text":"
  • Get
    var iteration = rect.iteration;\n
  • Set
    rect.setIteration(value);\n
    or
    rect.iteration = value;\n

Number of interpolation points in each round corner. Default value is 4.

  • 0 : Draw a straight line instead of arc.
"},{"location":"shape-roundrectangle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-roundrectangle/#create-mask","title":"Create mask","text":"
var mask = rect.createGeometryMask();\n

See mask

"},{"location":"shape-roundrectangle/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-spinner/","title":"Spinner","text":""},{"location":"shape-spinner/#introduction","title":"Introduction","text":"

Loading animations on shape.

  • Author: Rex
  • Game object
"},{"location":"shape-spinner/#live-demos","title":"Live demos","text":"
  • Spinners
    • Arrow
    • AIO
  • Custom spinner
  • Loading animation
"},{"location":"shape-spinner/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-spinner/#install-plugin","title":"Install plugin","text":""},{"location":"shape-spinner/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin(\n\"rexspinnerplugin\",\n\"https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexspinnerplugin.min.js\",\n\"rexSpinner\",\n\"rexSpinner\"\n);\n
  • Add spinner object
    var aio = scene.rexSpinner.add.aio(config);\nvar arrow = scene.rexSpinner.add.arrow(config);\nvar downArrow = scene.rexSpinner.add.downArrow(config);\nvar leftArrow = scene.rexSpinner.add.leftArrow(config);\nvar rightArrow = scene.rexSpinner.add.rightArrow(config);\nvar upArrow = scene.rexSpinner.add.upArrow(config);\nvar audio = scene.rexSpinner.add.audio(config);\nvar ball = scene.rexSpinner.add.ball(config);\nvar bars = scene.rexSpinner.add.bars(config);\nvar box = scene.rexSpinner.add.box(config);\nvar clock = scene.rexSpinner.add.clock(config);\nvar cube = scene.rexSpinner.add.cube(config);\nvar dots = scene.rexSpinner.add.dots(config);\nvar facebook = scene.rexSpinner.add.facebook(config);\nvar grid = scene.rexSpinner.add.grid(config);\nvar hearts = scene.rexSpinner.add.hearts(config);\nvar ios = scene.rexSpinner.add.ios(config);\nvar orbit = scene.rexSpinner.add.orbit(config);\nvar oval = scene.rexSpinner.add.oval(config);\nvar pie = scene.rexSpinner.add.pie(config);\nvar puff = scene.rexSpinner.add.puff(config);\nvar radio = scene.rexSpinner.add.radio(config);\nvar rings = scene.rexSpinner.add.rings(config);\nvar spinner = scene.rexSpinner.add.spinner(config);\n
"},{"location":"shape-spinner/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SpinnerPlugin from \"phaser3-rex-plugins/templates/spinner/spinner-plugin.js\";\nvar config = {\n// ...\nplugins: {\nscene: [\n{\nkey: \"rexSpinner\",\nplugin: SpinnerPlugin,\nmapping: \"rexSpinner\",\n},\n// ...\n],\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add spinner object
    var aio = scene.rexSpinner.add.aio(config);\nvar arrow = scene.rexSpinner.add.arrow(config);\nvar downArrow = scene.rexSpinner.add.downArrow(config);\nvar leftArrow = scene.rexSpinner.add.leftArrow(config);\nvar rightArrow = scene.rexSpinner.add.rightArrow(config);\nvar upArrow = scene.rexSpinner.add.upArrow(config);  var audio = scene.rexSpinner.add.audio(config);\nvar ball = scene.rexSpinner.add.ball(config);\nvar bars = scene.rexSpinner.add.bars(config);\nvar box = scene.rexSpinner.add.box(config);\nvar clock = scene.rexSpinner.add.clock(config);\nvar cube = scene.rexSpinner.add.cube(config);\nvar dots = scene.rexSpinner.add.dots(config);\nvar facebook = scene.rexSpinner.add.facebook(config);\nvar grid = scene.rexSpinner.add.grid(config);\nvar hearts = scene.rexSpinner.add.hearts(config);\nvar ios = scene.rexSpinner.add.ios(config);\nvar orbit = scene.rexSpinner.add.orbit(config);\nvar oval = scene.rexSpinner.add.oval(config);\nvar pie = scene.rexSpinner.add.pie(config);\nvar puff = scene.rexSpinner.add.puff(config);\nvar radio = scene.rexSpinner.add.radio(config);\nvar rings = scene.rexSpinner.add.rings(config);\nvar spinner = scene.rexSpinner.add.spinner(config);    
"},{"location":"shape-spinner/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { AIO, Arrow, Audio, Ball, Bars, Box, Clock, Cube, Custom, Dots, Facebook, Grid, Hearts, Ios, Orbit, Oval, Puff, Radio, Rings, Spinner\n} from \"phaser3-rex-plugins/templates/spinner/spinner-components.js\";\n
  • Add spinner object
    var spinner = new Audio(scene, config);\nscene.add.existing(spinner);\n
"},{"location":"shape-spinner/#add-spinner-object","title":"Add spinner object","text":""},{"location":"shape-spinner/#general","title":"General","text":"
var spinner = scene.rexSpinner.add.audio({\n// x: 0,\n// y: 0,\n// width: 64,\n// height: 64,\n// color: 0xffffff,\n\n// duration: 1000,\n// start: true,\n// delay: 0,\n// repeatDelay: 0,\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • color : Fill color, or stroke color. Default value is 0xffffff
  • duration : Duration of animation.
  • start : Start animation when object created.
  • false : Don't play animation at beginning.
  • delay : Delay time in ms before running.
  • repeatDelay : Delay time between 2 periods.
"},{"location":"shape-spinner/#arrow","title":"Arrow","text":"
var spinner = scene.rexSpinner.add.audio({\n// ...\n// direction: 'down'\n});\n
  • direction :
    • 0, 'right' : Arrow from left to right.
    • 1, 'down' : Arrow from up to down. Default behavior.
    • 2, 'left' : Arrow from right to left.
    • 3, 'up' : Arrow from down to up.
"},{"location":"shape-spinner/#aio","title":"AIO","text":"

All-in-one

var spinner = scene.rexSpinner.add.aio({\n// ...\n// animationMode: undefined\n});\n
  • animationMode :
    • undefined : Play random spinner animation.
    • 'leftArrow' : Play leftArrow spinner animation.
    • 'rightArrow' : Play rightArrow spinner animation.
    • 'upArrow' : Play upArrow spinner animation.
    • 'downArrow' : Play dowbArrow spinner animation.
    • 'audio' : Play audio spinner animation.
    • 'ball' : Play ball spinner animation.
    • 'bars' : Play bars spinner animation.
    • 'box' : Play box spinner animation.
    • 'clock' : Play clock spinner animation.
    • 'cube' : Play cube spinner animation.
    • 'dots' : Play dots spinner animation.
    • 'facebook' : Play facebook spinner animation.
    • 'grid' : Play grid spinner animation.
    • 'hearts' : Play hearts spinner animation.
    • 'ios' : Play ios spinner animation.
    • 'oribit' : Play oribit spinner animation.
    • 'oval' : Play oval spinner animation.
    • 'pie' : Play pie spinner animation.
    • 'puff' : Play puff spinner animation.
    • 'radio' : Play radio spinner animation.
    • 'rings' : Play rings spinner animation.
    • 'spinner' : Play spinner spinner animation.
"},{"location":"shape-spinner/#play-animation","title":"Play animation","text":""},{"location":"shape-spinner/#start","title":"Start","text":"
  • Start playing, won't restart when playing
    spinner.start();\n
  • Restart with new duration
    spinner.start(duration);\n
"},{"location":"shape-spinner/#pause","title":"Pause","text":"
spinner.pause();\n
"},{"location":"shape-spinner/#resume","title":"Resume","text":"
spinner.resume();\n
"},{"location":"shape-spinner/#stop","title":"Stop","text":"
spinner.stop();\n
"},{"location":"shape-spinner/#play-animation-manually","title":"Play animation manually","text":"
  1. Set start to false in config
  2. Set progress manually
    spinner.setValue(t);\n
    or
    spinner.value = t;\n
    • t : 0 ~ 1
"},{"location":"shape-spinner/#is-running","title":"Is running","text":"
var isRunning = spinner.isRunning;\n
"},{"location":"shape-spinner/#color","title":"Color","text":"
  • Get
    var color = spinner.color;\n
  • Set
    spinner.setColor(color);\n
    or
    spinner.color = color;\n
    • color : Fill color, or stroke color, in number.
"},{"location":"shape-spinner/#alpha","title":"Alpha","text":"
  • Get
    var alpha = spinner.alpha;\n
  • Set
    spinner.setAlpha(alpha);\n// spinner.alpha = alpha;\n
"},{"location":"shape-spinner/#duration","title":"Duration","text":"
  • Get
    var duration = spinner.duration;\n
  • Set, will apply to next animation playing.
    spinner.setDuration(duration);\n
    or
    spinner.duration = duration;\n
"},{"location":"shape-spinner/#ease","title":"Ease","text":"
  • Get
    var ease = spinner.ease;\n
  • Set, will apply to next animation playing.
    spinner.setEasen(ease);\n
    or
    spinner.ease = ease;\n
"},{"location":"shape-spinner/#set-animation-mode","title":"Set animation mode","text":"

AIO-spinner only

aioSpinner.setAnimationMode(mode);\n
  • mode :
    • undefined : Play random spinner animation.
    • 'leftArrow' : Play leftArrow spinner animation.
    • 'rightArrow' : Play rightArrow spinner animation.
    • 'upArrow' : Play upArrow spinner animation.
    • 'downArrow' : Play dowbArrow spinner animation.
    • 'audio' : Play audio spinner animation.
    • 'ball' : Play ball spinner animation.
    • 'bars' : Play bars spinner animation.
    • 'box' : Play box spinner animation.
    • 'clock' : Play clock spinner animation.
    • 'cube' : Play cube spinner animation.
    • 'dots' : Play dots spinner animation.
    • 'facebook' : Play facebook spinner animation.
    • 'grid' : Play grid spinner animation.
    • 'hearts' : Play hearts spinner animation.
    • 'ios' : Play ios spinner animation.
    • 'oribit' : Play oribit spinner animation.
    • 'oval' : Play oval spinner animation.
    • 'pie' : Play pie spinner animation.
    • 'puff' : Play puff spinner animation.
    • 'radio' : Play radio spinner animation.
    • 'rings' : Play rings spinner animation.
    • 'spinner' : Play spinner spinner animation.
aioSpinner.setRandomAnimationMode();\n
"},{"location":"shape-spinner/#custom-spinner","title":"Custom spinner","text":"
var customSpinner = scene.rexSpinner.add.custom({\n// x: 0,\n// y: 0,\n// width: 64,\n// height: 64,\n// color: 0xffffff,\n\n// duration: 1000,\n// start: true,\n\ncreate: {\n// shapeType: [name0, name1, ...],\n// shapeType: number,\n// shapeType: name,\n},\n\n// create: function() {\n// \n// },\n\nupdate: function() {\n\n},\n})\n
  • create : Callback to create shapes
    • A plain object with shapeType: name, or shapeType: number
      • shapeType :
        • 'arc' : Create Arc shape.
        • 'circle' : Create Circle shape.
        • 'ellipse' : Create Ellipse shape.
        • 'line' : Create Line shape.
        • 'lines' : Create Lines shape.
        • 'rectangle' : Create Rectangle shape.
        • 'roundRectangle' : Create Round rectangle shape.
        • 'triangle' : Create Triangle shape.
      • nameArray : An array of unique string name for each shape.
      • name : An unique string name of this shape.
      • number : Amount of shapes to create.
    • A callback
      function() {\n// this : This spinner game object\nvar shape = this.createShape(shapeType, name);\nthis.addShape(shape);\n}\n
      • this.createShape(shapeType, name) : Crate a shape instance, with an unique name.
      • this.addShape(shape) : Add this shape instance to this custom spinner.
  • update : Callback when porgressing
    function() {\n// this : This spinner game object\nvar centerX = this.centerX;\nvar centerY = this.centerY;\nvar radius = this.radius;\nvar color = this.color;\nvar shapes = this.getShapes();\nvar shape = this.getShape(name);\nvar t = this.value;\n// ...\n}\n
    • this.value : Progress, 0~1.
    • Position :
      • this.centerX, this.centerY : Center position of this spinner. The coordinate of top-left point is (0,0)
      • this.radius : Minimun value of this.centerX, this.centerY, to draw shape at square.
    • Color :
      • this.color : Color property of this spinner.
    • Shape instances : Change properties of shape instances.
      • this.getShapes() : Return all shapes in an array.
      • this.getShape(name) : Return a shape by the unique string name.
"},{"location":"shape-spinner/#shape-class","title":"Shape class","text":"

See Shape class

"},{"location":"shape-spinner/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-spinner/#create-mask","title":"Create mask","text":"
var mask = customSpinner.createGeometryMask();\n

See mask

"},{"location":"shape-spinner/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-star/","title":"Star","text":""},{"location":"shape-star/#introduction","title":"Introduction","text":"

Star shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-star/#usage","title":"Usage","text":""},{"location":"shape-star/#create-shape-object","title":"Create shape object","text":"
var star = scene.add.star(x, y, points, innerRadius, outerRadius, fillColor);\n// var star = scene.add.star(x, y, points, innerRadius, outerRadius, fillColor, fillAlpha);\n
  • points : The number of points on the star. Default is 5.
  • innerRadius : The inner radius of the star. Default is 32.
  • outerRadius : The outer radius of the star. Default is 64.
"},{"location":"shape-star/#custom-class","title":"Custom class","text":"
  • Define class
    class MyStar extends Phaser.GameObjects.Star {\nconstructor(scene, x, y, points, innerRadius, outerRadius, fillColor) {\nsuper(scene, x, y, points, innerRadius, outerRadius, fillColor);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var star = new MyStar(scene, x, y, points, innerRadius, outerRadius, fillColor);\n
"},{"location":"shape-star/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = star.fillColor;\nvar alpha = star.fillAlpha;\n
    • Set
      star.setFillStyle(color, alpha);\n
    • Clear
      star.setFillStyle();\n
  • Stroke color
    • Get
      var color = star.strokeColor;\n
    • Set
      star.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      star.setStrokeStyle();\n

No tint methods

Uses star.setFillStyle(color, alpha) to change color.

"},{"location":"shape-star/#alpha","title":"Alpha","text":"
  • Get
    var alpha = star.alpha;\n
  • Set
    star.setAlpha(alpha);\n// star.alpha = alpha;\n
"},{"location":"shape-star/#radius","title":"Radius","text":"
  • Inner radius
    • Get
      var innerRadius = star.innerRadius;\n
    • Set
      star.setInnerRadius(innerRadius);\n
      or
      star.innerRadius = innerRadius;\n
  • Outer radius
    • Get
      var outerRadius = star.outerRadius;\n
    • Set
      star.setOuterRadius(outerRadius);\n
      or
      star.outerRadius = outerRadius;\n
  • Points
    • Get
      var points = star.points;\n
    • Set
      star.setPoints(points);\n
      or
      star.points = points;\n
"},{"location":"shape-star/#display-size","title":"Display size","text":"
  • Get
    var width = star.displayWidth;\nvar height = star.displayHeight;\n
  • Set
    star.setDisplaySize(width, height);\n
    or
    star.displayWidth = width;\nstar.displayHeight = height;\n
"},{"location":"shape-star/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-star/#create-mask","title":"Create mask","text":"
var mask = star.createGeometryMask();\n

See mask

"},{"location":"shape-star/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-toggleswitch/","title":"Toggle switch","text":""},{"location":"shape-toggleswitch/#introduction","title":"Introduction","text":"

Toggle-switch input.

  • Author: Rex
  • Game object
"},{"location":"shape-toggleswitch/#live-demos","title":"Live demos","text":"
  • Toggle-switch
"},{"location":"shape-toggleswitch/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-toggleswitch/#install-plugin","title":"Install plugin","text":""},{"location":"shape-toggleswitch/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextoggleswitchplugin', 'https://raw.githubusercontent.com/rexrainbow/    phaser3-rex-notes/master/dist/rextoggleswitchplugin.min.js', true);\n
  • Add toggle-switch input
    var toggleSwitch = scene.add.rexToggleSwitch(x, y, width, height, color, config);\n
  • Add toggle-switch shape (without click input)
    var toggleSwitch = scene.add.rexToggleSwitchShape(x, y, width, height, color, config);\n
"},{"location":"shape-toggleswitch/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ToggleSwitchPlugin from 'phaser3-rex-plugins/plugins/toggleswitch-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexToggleSwitchPlugin',\nplugin: ToggleSwitchPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add toggle-switch input
    var toggleSwitch = scene.add.rexToggleSwitch(x, y, width, height, color, config);\n
  • Add toggle-switch shape (without click input)
    var toggleSwitch = scene.add.rexToggleSwitchShape(x, y, width, height, color, config);\n
"},{"location":"shape-toggleswitch/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ToggleSwitch from 'phaser3-rex-plugins/plugins/toggleswitch.js';\n
  • Add toggle-switch input
    var toggleswitch = new ToggleSwitch(scene, x, y, width, height, color, config);\nscene.add.existing(toggleSwitch);\n
  • Add toggle-switch shape (without click input)
    // import ToggleSwitchShape from 'phaser3-rex-plugins/plugins/toggleswitchshape.js';\nvar toggleSwitch = new ToggleSwitchShape(scene, x, y, width, height, color, config);\nscene.add.existing(toggleSwitch);\n
"},{"location":"shape-toggleswitch/#create-toggle-switch-input","title":"Create toggle-switch input","text":"
var toggleSwitch = scene.add.rexToggleSwitch(x, y, width, height, color, config);\n

or

var toggleSwitch = scene.add.rexToggleSwitch({\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\n\ncolor: 0x005cb2,\ntrackFillAlpha: 1,\nfalseValueTrackColor: undefined,\nfalseValueTrackFillAlpha: 1,\n\nthumbColor: 0xffffff,\nthumbAlpha: 1,\n\ntrackWidth: 0.9,\ntrackHeight: 0.5,\ntrackCornerRadius: (trackHeight * 0.5),\n\nthumbHeight: (trackHeight * 0.9),\nthumbWidth: (thumbHeight),\nthumbCornerRadius: (thumbHeight * 0.5),\n\nthumbLeft: 0.3,\nthumbRight: (1 - thumbLeft),\nrtl: false,\n\nanimationDuration: 150,\n\nvalue: false,\n\nclick: undefined,\n// click: {\n//     mode: 1,            // 0|'press'|1|'release'\n//     clickInterval: 100  // ms\n//     threshold: undefined\n// },\nreadOnly: false,\n});\n
  • width, height : Size of toggleswitch.
  • Track fill style
    • color, trackFillAlpha : Track color and alpha when value is true.
    • falseValueTrackColor, falseValueTrackFillAlpha : Track color and alpha when value is false.
      • Default value of falseValueTrackColor is the grayscale of color.
  • Thumb fill style
    • thumbColor, thumbAlpha : Thumb color and alpha
  • Track size
    • trackWidth : Width ration of track. Default value is 0.9.
    • thumbWidth : Height ratio of track. Default value is 0.5.
    • trackCornerRadius : Ratio of track corner. Default value is half of trackHeight.
  • Thumb size
    • thumbWidth : Width ration of thumb. Default value is equal to thumbHeight.
    • thumbHeight : Height ratio of thumb. Default value trackHeight * 0.5.
    • thumbCornerRadius : Ratio of thumb corner. Default value is half of thumbHeight.
  • Thumb position
    • thumbLeft : Thumb position if value is false. Default value is 0.3.
    • thumbRight : Thumb position if value is true. Default value is 1 - thumbLeft.
    • rtl : Moving direction of thumb when when value changes from false to true.
      • false : Thumb moves from left to right. Default behavior.
      • true : Thumb moves from right to left.
  • animationDuration : Duration of drawing path of checker.
  • value : Initial value.
  • click : Configuration of click input
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
    • click.threshold : Cancel clicking detecting when dragging distance is larger then this threshold.
      • undefined : Ignore this feature. Default behavior.
  • readOnly : Set ture to disable input.
"},{"location":"shape-toggleswitch/#custom-class","title":"Custom class","text":"
  • Define class
    class MyToggleSwitch extends RexPlugins.GameObjects.ToggleSwitch {\nconstructor(scene, x, y, width, height, color, config) {\nsuper(scene, x, y, width, height, color, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var toggleSwitch = new MyToggleSwitch(scene, x, y, width, height, color, config);\n
"},{"location":"shape-toggleswitch/#value","title":"Value","text":"
  • Get
    var value = toggleSwitch.value;\n// var value = toggleSwitch.value;\n
  • Set
    toggleSwitch.setValue(value);\n// toggleSwitch.setValue(value, duration);\n
    or
    toggleSwitch.value = value;\n
  • Toggle
    toggleSwitch.toggleValue();\n// toggleSwitch.toggleValue(duration);\n
    or
    toggleSwitch.value = !toggleSwitch.value;\n// toggleSwitch.value = !toggleSwitch.value;\n
"},{"location":"shape-toggleswitch/#read-only","title":"Read only","text":"
  • Get
    var readOnly = toggleSwitch.readOnly;\n
  • Set
    toggleSwitch.setReadOnly();\n// toggleSwitch.setReadOnly(true);\n
    or
    toggleSwitch.readOnly = true;\n
"},{"location":"shape-toggleswitch/#track-fill-style","title":"Track fill style","text":"
  • Get
    var color = toggleSwitch.trackFillColor;\nvar alpha = toggleSwitch.trackFillAlpha;\n
    var color = toggleSwitch.falseValueTrackColor;\nvar alpha = toggleSwitch.falseValueTrackFillAlpha;\n
  • Set
    toggleSwitch.setTrackFillStyle(color, alpha);\n// toggleSwitch.trackFillColor = color;\n// toggleSwitch.trackFillAlpha = alpha;\n
    toggleSwitch.setFalseValueTrackFillStyle(color, alpha);\n// toggleSwitch.falseValueTrackColor = color;\n// toggleSwitch.falseValueTrackFillAlpha = alpha;\n
"},{"location":"shape-toggleswitch/#thumb-fill-style","title":"Thumb fill style","text":"
  • Get
    var color = toggleSwitch.thumbColor;\nvar alpha = toggleSwitch.thumbAlpha;\n
  • Set
    toggleSwitch.setThumbStyle(color, alpha);\n// toggleSwitch.thumbColor = color;\n// toggleSwitch.thumbAlpha = alpha;\n
"},{"location":"shape-toggleswitch/#toggle-animation","title":"Toggle animation","text":"
  • Duration
    • Get
      var duration = toggleSwitch.toggleAnimProgress;\n
    • Set
      toggleSwitch.setToggleAnimationDuration(duration);\ntoggleSwitch.toggleAnimProgress = duration;\n
"},{"location":"shape-toggleswitch/#size","title":"Size","text":"
  • Get
    var width = toggleSwitch.width;\nvar height = toggleSwitch.height;\n
  • Set
    toggleSwitch.setSize(width, height);\n
    or
    toggleSwitch.width = width;\ntoggleSwitch.height = height;\n
"},{"location":"shape-toggleswitch/#display-size","title":"Display size","text":"
  • Get
    var width = toggleSwitch.displayWidth;\nvar height = toggleSwitch.displayHeight;\n
  • Set
    toggleSwitch.setDisplaySize(width, height);\n
    or
    toggleSwitch.displayWidth = width;\ntoggleSwitch.displayHeight = height;\n
"},{"location":"shape-toggleswitch/#track-size-ratio","title":"Track size ratio","text":"
  • Get
    var trackWidth = toggleSwitch.trackWidth;\nvar trackHeight = toggleSwitch.trackHeight;\n
    • trackWidth, trackHeight : Size ratio of track
  • Set
    toggleSwitch.setTrackSize(trackWidth, trackHeight);\n// toggleSwitch.trackWidth = trackWidth;\n// toggleSwitch.trackHeight = trackHeight;\n
"},{"location":"shape-toggleswitch/#track-corner-ratio","title":"Track corner ratio","text":"
  • Get
    var trackRadius = toggleSwitch.trackRadius;\n
    • trackRadius : Corner ratio of track
  • Set
    toggleSwitch.setTrackRadius(trackRadius);\n// toggleSwitch.trackRadius = trackRadius;\n
"},{"location":"shape-toggleswitch/#thumb-size-ratio","title":"Thumb size ratio","text":"
  • Get
    var thumbWidth = toggleSwitch.thumbWidth;\nvar thumbHeight = toggleSwitch.thumbHeight;\n
    • trackWidth, trackHeight : Size ratio of thumb
  • Set
    toggleSwitch.setThumbSize(thumbWidth, thumbHeight);\n// toggleSwitch.thumbWidth = thumbWidth;\n// toggleSwitch.thumbHeight = thumbHeight;\n
"},{"location":"shape-toggleswitch/#thumb-corner-ratio","title":"Thumb corner ratio","text":"
  • Get
    var thumbRadius = toggleSwitch.thumbRadius;\n
    • thumbRadius : Corner ratio of track
  • Set
    toggleSwitch.setThumbRadius(thumbRadius);\n// toggleSwitch.thumbRadius = thumbRadius;\n
"},{"location":"shape-toggleswitch/#thumb-position-ratio","title":"Thumb position ratio","text":"
  • Get
    var thumbLeft = toggleSwitch.thumbLeftX;\nvar thumbRight = toggleSwitch.thumbRightX;\n
    var rtl = toggleSwitch.rtl;\n
  • Set
    toggleSwitch.setThumbPosition(thumbLeft, thumbRight);\n// toggleSwitch.thumbLeftX = thumbLeft;\n// toggleSwitch.thumbRightX = thumbRight;\n
    toggleSwitch.setRTL(rtl);\n// toggleSwitch.rtl = rtl;\n
"},{"location":"shape-toggleswitch/#events","title":"Events","text":"
  • On value change
    toggleSwitch.on('valuechange', function(value) {\n// value: checked\n})\n
"},{"location":"shape-toggleswitch/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-toggleswitch/#create-mask","title":"Create mask","text":"
var mask = toggleSwitch.createGeometryMask();\n

See mask

"},{"location":"shape-toggleswitch/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-triangle/","title":"Triangle","text":""},{"location":"shape-triangle/#introduction","title":"Introduction","text":"

Triangle shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-triangle/#usage","title":"Usage","text":""},{"location":"shape-triangle/#create-shape-object","title":"Create shape object","text":"
var triangle = scene.add.triangle(x, y, x1, y1, x2, y2, x3, y3, fillColor);\n// var triangle = scene.add.triangle(x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha);\n
"},{"location":"shape-triangle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTriangle extends Phaser.GameObjects.Triangle {\nconstructor(scene, x, y, x1, y1, x2, y2, x3, y3, fillColor) {\nsuper(scene, x, y, x1, y1, x2, y2, x3, y3, fillColor);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var triangle = new MyTriangle(scene, x, y, x1, y1, x2, y2, x3, y3, fillColor);\n
"},{"location":"shape-triangle/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = triangle.fillColor;\nvar alpha = triangle.fillAlpha;\n
    • Set
      triangle.setFillStyle(color, alpha);\n
    • Clear
      triangle.setFillStyle();\n
  • Stroke color
    • Get
      var color = triangle.strokeColor;\n
    • Set
      triangle.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      triangle.setStrokeStyle();\n

No tint methods

Uses triangle.setFillStyle(color, alpha) to change color.

"},{"location":"shape-triangle/#alpha","title":"Alpha","text":"
  • Get
    var alpha = triangle.alpha;\n
  • Set
    triangle.setAlpha(alpha);\n// triangle.alpha = alpha;\n
"},{"location":"shape-triangle/#set-vertices","title":"Set vertices","text":"
triangle.setTo(x1, y1, x2, y2, x3, y3);\n
"},{"location":"shape-triangle/#triangle-width","title":"Triangle width","text":"
triangle.setLineWidth(startWidth, endWidth);\n
  • endWidth : The end width of the triangle. Only used in WebGL.
"},{"location":"shape-triangle/#display-size","title":"Display size","text":"
  • Get
    var width = triangle.displayWidth;\nvar height = triangle.displayHeight;\n
  • Set
    triangle.setDisplaySize(width, height);\n
    or
    triangle.displayWidth = width;\ntriangle.displayHeight = height;\n
"},{"location":"shape-triangle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-triangle/#create-mask","title":"Create mask","text":"
var mask = triangle.createGeometryMask();\n

See mask

"},{"location":"shape-triangle/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-triangle2/","title":"Triangle 2","text":""},{"location":"shape-triangle2/#introduction","title":"Introduction","text":"

Trangle shape inside a rectangle bounds.

  • Author: Rex
  • Game object
"},{"location":"shape-triangle2/#live-demos","title":"Live demos","text":"
  • Ease direction
  • Rotate
"},{"location":"shape-triangle2/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-triangle2/#install-plugin","title":"Install plugin","text":""},{"location":"shape-triangle2/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextriangleplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextriangleplugin.min.js', true);\n
  • Add triangle object
    var triangle = scene.add.rexTriangle(x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-triangle2/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TrianglePlugin from 'phaser3-rex-plugins/plugins/triangle-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTrianglePlugin',\nplugin: TrianglePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add triangle object
    var triangle = scene.add.rexTriangle(x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-triangle2/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Triangle from 'phaser3-rex-plugins/plugins/triangle.js';\n
  • Add triangle object
    var triangle = new Triangle(scene, x, y, width, height, fillColor, fillAlpha);\nscene.add.existing(triangle);\n
"},{"location":"shape-triangle2/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTrianglePlugin',\nplugin: TrianglePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"shape-triangle2/#create-instance","title":"Create instance","text":"
var triangle = scene.add.rexTriangle(x, y, width, height, fillColor, fillAlpha);\n

or

var triangle = scene.add.rexTriangle({\nx: 0,\ny: 0,\nwidth: 2,\nheight: 2,\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n\narrowOnly: false,\n\ndirection: 0,\neaseDuration: 0,\npadding: 0,\n// padding: {\n//     left: 0,\n//     right: 0,\n//     top: 0,\n//     bottom: 0,\n// },\n\nradius: undefined,\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • arrowOnly :
    • false : Fill and stroke triangle shape. Default behavior.
    • true : Only stroke arrow of triangle shape.
  • direction : Direction of triangle's arrow.
    • 0, or 'right' : Arrow to right. Default value.
    • 1, or 'down' : Arrow to down.
    • 2, or 'left' : Arrow to left.
    • 3, or 'up' : Arrow to up.
  • easeDuration : Ease duration when direction changed.
    • 0 : No ease transform. Default value.
  • padding : Space around triagnle.
    • A number. Default value is 0.
    • A plain object
      {\nleft:0, right:0, top: 0, bottom: 0\n}\n
  • radius : Put 3 vertices of trangle in a circle.
    • undefined : Disable this mode. Default behavior.
    • 0~1 : Radius in ratio of min(half-width, half-height)
"},{"location":"shape-triangle2/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTriangle extends Triangle {\nconstructor(scene, x, y, width, height, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var triangle = new MyTriangle(scene, x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-triangle2/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = triangle.fillColor;\nvar alpha = triangle.fillAlpha;\n
    • Set
      triangle.setFillStyle(color, alpha);\n
    • Clear
      triangle.setFillStyle();\n
  • Stroke color
    • Get
      var color = triangle.strokeColor;\n
    • Set
      triangle.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      triangle.setStrokeStyle();\n

No tint methods

Uses triangle.setFillStyle(color, alpha) to change color.

"},{"location":"shape-triangle2/#alpha","title":"Alpha","text":"
  • Get
    var alpha = triangle.alpha;\n
  • Set
    triangle.setAlpha(alpha);\n// triangle.alpha = alpha;\n
"},{"location":"shape-triangle2/#size","title":"Size","text":"
  • Get
    var width = triangle.width;\nvar height = triangle.height;\n
  • Set
    triangle.setSize(width, height);\n
    or
    triangle.width = width;\ntriangle.height = height;\n
"},{"location":"shape-triangle2/#display-size","title":"Display size","text":"
  • Get
    var width = triangle.displayWidth;\nvar height = triangle.displayHeight;\n
  • Set
    triangle.setDisplaySize(width, height);\n
    or
    triangle.displayWidth = width;\ntriangle.displayHeight = height;\n
"},{"location":"shape-triangle2/#direction","title":"Direction","text":"
  • Get
    var direction = triangle.direction;\n
    • 0 : Arrow to right. Default value.
    • 1 : Arrow to down.
    • 2 : Arrow to left.
    • 3 : Arrow to up.
  • Set
    triangle.setDirection(direction);\n// triangle.direction = direction;\n
    or
    triangle.setDirection(direction, easeDuration);\n
    • direction :
      • 0, or 'right' : Arrow to right.
      • 1, or 'down' : Arrow to down.
      • 2, or 'left' : Arrow to left.
      • 3, or 'up' : Arrow to up.
    • easeDuration : Override current ease-duration time.
  • Toggle
    triangle.toggleDirection();\n// triangle.direction += 2;\n
    or
    triangle.toggleDirection(easeDuration);\n
"},{"location":"shape-triangle2/#padding","title":"Padding","text":"
  • Get
    var padding = triangle.padding;\n
    • padding :
      { left, right, top, bottom }\n
  • Set
    triangle.setPadding(padding);\n
    or
    triangle.setPadding({\nleft, right, top, bottom\n});\n
    or
    triangle.setPadding({\nx, y\n});\n
"},{"location":"shape-triangle2/#ease-duration","title":"Ease duration","text":"
  • Get
    var easeDuration = triangle.easeDuration;\n
  • Set
    triangle.setEaseDuration(easeDuration);\n
"},{"location":"shape-triangle2/#arrow-only","title":"Arrow only","text":"
  • Get
    var arrowOnly = triangle.arrowOnly;\n
  • Set
    triangle.setArrowOnly(enable);\n// triangle.arrowOnly = enable;\n
"},{"location":"shape-triangle2/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-triangle2/#create-mask","title":"Create mask","text":"
var mask = triangle.createGeometryMask();\n

See mask

"},{"location":"shape-triangle2/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shatter-image/","title":"Image","text":""},{"location":"shatter-image/#introduction","title":"Introduction","text":"

Shatter image to triangle faces.

Reference: Delaunay Triangulation

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"shatter-image/#live-demos","title":"Live demos","text":"
  • Shatter image
"},{"location":"shatter-image/#usage","title":"Usage","text":"

Sample code

"},{"location":"shatter-image/#install-plugin","title":"Install plugin","text":""},{"location":"shatter-image/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexshatterimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexshatterimageplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexShatterImage(x, y, texture, frame, config);\n
"},{"location":"shatter-image/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ShatterImagePlugin from 'phaser3-rex-plugins/plugins/shatterimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexShatterImagePlugin',\nplugin: ShatterImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexShatterImage(x, y, texture, frame, config);\n
"},{"location":"shatter-image/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ShatterImage } from 'phaser3-rex-plugins/plugins/shatterimage.js';\n
  • Add image object
    var image = new ShatterImage(scene, x, y, texture, frame, config);\nscene.add.existing(image);\n
"},{"location":"shatter-image/#create-instance","title":"Create instance","text":"
var image = scene.add.rexShatterImage(x, y, texture, frame, {\n// ringRadiusList: [1 / 27, 3 / 27, 9 / 27],\n// ringRadiusList: function(width, height) {\n//    return [1 / 27, 3 / 27, 9 / 27];\n// },\n\n// samplesPerRing: 12\n// variation: 0.25,    \n});\n

or

var image = scene.add.rexShatterImage({\n// x: 0,\n// y: 0,\nkey,\n// frame: null,\n\n// ringRadiusList: [1 / 27, 3 / 27, 9 / 27],\n// ringRadiusList: function(width, height) {\n//    return [1 / 27, 3 / 27, 9 / 27];\n// },\n\n// samplesPerRing: 12,\n// variation: 0.25,\n\n});\n
  • ringRadiusList :
    • A list of number. Default value is [1 / 27, 3 / 27, 9 / 27]
    • A callback to return a list of number
      function(width, height) {\nreturn [1 / 27, 3 / 27, 9 / 27];\n}\n

Add perspectiveimage from JSON

var perspectiveimage = scene.make.rexShatterImage({\nx: 0,\ny: 0,\nkey: null,\nframe: null,\n\n// ringRadiusList: [1 / 27, 3 / 27, 9 / 27],\n// ringRadiusList: function(width, height) {\n//    return [1 / 27, 3 / 27, 9 / 27];\n// },\n\n// samplesPerRing: 12,\n// variation: 0.25,\n\n\nadd: true\n});\n
"},{"location":"shatter-image/#custom-class","title":"Custom class","text":"
  • Define class
    class MyShatterImage( extends ShatterImage( {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyShatterImage(scene, x, y, texture, frame, config);\n
"},{"location":"shatter-image/#shatter-image","title":"Shatter image","text":"
image.shatter(centerX, centerY);\n// image.shatter();\n

or

image.shatter(centerX, centerY, {\n// ringRadiusList:\n// samplesPerRing: \n// variation\n});\n

or

image.shatter({\n// centerX: \n// centerY: \n// ringRadiusList:\n// samplesPerRing: \n// variation\n});\n
  • centerX, centerY : Center position of shatter.
    • undefined : Default value is center of image.

Shatter image into triangle faces.

"},{"location":"shatter-image/#position-of-shatter-center","title":"Position of Shatter center","text":"
var shatterCenter = image.shatterCenter; // {x, y}\n
"},{"location":"shatter-image/#faces","title":"Faces","text":"
var faces = image.faces;\n

Faces will be sorted nearby shatter-center to far away.

"},{"location":"shatter-image/#properties","title":"Properties","text":"
  • Alpha
    • Get
      var alpha = face.alpha;\n
    • Set
      face.alpha = alpha;\n
      or
      face.setAlpha(value);\n
  • Tint color
    • Get
      var color = face.tint;\n
    • Set
      face.tint = color;\n
      or
      face.setTint(color);\n
  • Angle
    • Get
      var radians = face.rotation;\n// var degree = face.angle;\n
    • Set
      face.rotation = radians;\n// face.angle = degree;\n
      or
      face.setRotation(radians);\n// face.setAngle(degree);\n
  • Center position
    • Get
      var x = face.x;\nvar y = face.y;\n
      • x : 0(left) ~ 1(right)
      • y : 1(top) ~ 0(bottom)
    • Set
      face.x = x;\nface.y = y;\n
      or
      face.translate(x, y);\n
      • x : 0(left) ~ 1(right)
      • y : 1(top) ~ 0(bottom)
"},{"location":"shatter-image/#update-properties","title":"Update properties","text":"
  • Start updating
    image.startUpdate();\n
    or
    image.ignoreDirtyCache = true;\n
  • Stop updating
    image.stopUpdate();\n
    or
    image.ignoreDirtyCache = false;\n
"},{"location":"shatter-image/#tween-properties","title":"Tween properties","text":"
image.startUpdate();\nscene.tweens.add({\ntargets: image.faces,\nalpha: 0,\nangle: function () { return -90 + Math.random() * 180; },\ny: '-=0.5',\nease: 'Linear',       // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\ndelay: scene.tweens.stagger(20),\nrepeat: 0,            // -1: infinity\nyoyo: false,\nonComplete: function () {\nimage.stopUpdate()\n}\n});\n
"},{"location":"shatter-image/#reset-image","title":"Reset image","text":"

Display original image with 2 faces.

image.resetImage();\n
"},{"location":"shatter-image/#tint-color","title":"Tint color","text":"
  • Get
    var color = image.tint;\n
  • Set
    image.tint = color;\n
    or
    image.setTint(color);\n
"},{"location":"shatter-image/#other-properties","title":"Other properties","text":"

See Mesh game object, game object

"},{"location":"shatter-image/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"shatter-image/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shatter-rendertexture/","title":"Render texture","text":""},{"location":"shatter-rendertexture/#introduction","title":"Introduction","text":"

Shatter render texture to triangle faces.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"shatter-rendertexture/#live-demos","title":"Live demos","text":"
  • RenderTexture
"},{"location":"shatter-rendertexture/#usage","title":"Usage","text":"

Sample code

"},{"location":"shatter-rendertexture/#install-plugin","title":"Install plugin","text":""},{"location":"shatter-rendertexture/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexshatterimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexshatterimageplugin.min.js', true);\n
  • Add render texture object
    var image = scene.add.rexShatterRenderTexture(x, y, width, height, config);\n
"},{"location":"shatter-rendertexture/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ShatterImagePlugin from 'phaser3-rex-plugins/plugins/shatterimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexShatterImagePlugin',\nplugin: ShatterImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add render texture object
    var image = scene.add.rexShatterRenderTexturege(x, y, width, height, config);\n
"},{"location":"shatter-rendertexture/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ShatterRenderTexture } from 'phaser3-rex-plugins/plugins/shatterimage.js';\n
  • Add render texture object
    var image = new ShatterRenderTexture(scene, x, y, width, height, config);\nscene.add.existing(image);\n
"},{"location":"shatter-rendertexture/#create-instance","title":"Create instance","text":"
var image = scene.add.rexShatterRenderTexturege(x, y, width, height, {\n// gridWidth: 32,\n// girdHeight: 32\n});\n

or

var image = scene.add.rexShatterRenderTexturege({\n// x: 0,\n// y: 0,\n// width: 32,\n// height: 32,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

Add prespective render texture from JSON

var image = scene.make.rexShatterRenderTexturege({\nx: 0,\ny: 0,    width: 32,\nheight: 32,\n\n// gridWidth: 32,\n// girdHeight: 32,\n\nadd: true\n});\n
"},{"location":"shatter-rendertexture/#custom-class","title":"Custom class","text":"
  • Define class
    class MyShatterRenderTexturege extends ShatterRenderTexturege {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyShatterRenderTexturege(scene, x, y, width, height, config);\n
"},{"location":"shatter-rendertexture/#internal-render-texture","title":"Internal render texture","text":"
var rt = image.rt;\n
  • rt : Render texture
"},{"location":"shatter-rendertexture/#paste-texture","title":"Paste texture","text":"
  • Paste game object
    image.rt.draw(gameObject, x, y);\n// image.rt.draw(gameObject, x, y, alpha, tint);\n
  • gameObject : a game object, or an array of game objects
  • Paste game objects in a group
    image.rt.draw(group, x, y);\n// image.rt.draw(group, x, y, alpha, tint);\n
  • Paste game objects in a scene
    image.rt.draw(scene.children, x, y);\n// image.rt.draw(scene.children, x, y, alpha, tint);\n
  • Paste texture
    image.rt.draw(key, x, y);\n// image.rt.draw(key, x, y, alpha, tint);\n
    or
    image.rt.drawFrame(key, frame, x, y);\n// image.rt.drawFrame(key, frame, x, y, alpha, tint);\n
    • key : The key of the texture to be used, as stored in the Texture Manager.
"},{"location":"shatter-rendertexture/#erase","title":"Erase","text":"
image.rt.erase(gameObject, x, y);\n
  • gameObject : a game object, or an array of game objects
"},{"location":"shatter-rendertexture/#clear","title":"Clear","text":"
image.rt.clear();\n
"},{"location":"shatter-rendertexture/#fill","title":"Fill","text":"
image.rt.fill(rgb, alpha);\n// image.rt.fill(rgb, alpha, x, y, width, height);\n
"},{"location":"shatter-rendertexture/#other-properties","title":"Other properties","text":"

See Shatter image game object, Mesh game object, game object

"},{"location":"shatter-rendertexture/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"shatter-rendertexture/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"ship/","title":"Ship","text":""},{"location":"ship/#introduction","title":"Introduction","text":"

Move game object as a space ship by cursor keys.

  • Author: Rex
  • Arcade behavior of game object
"},{"location":"ship/#usage","title":"Usage","text":"

Sample code

"},{"location":"ship/#install-plugin","title":"Install plugin","text":""},{"location":"ship/#load-minify-file","title":"Load minify file","text":"
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexshipplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexshipplugin.min.js', true);\n
  • Add ship behavior
    var ship = scene.plugins.get('rexshipplugin').add(gameObject, config);\n
"},{"location":"ship/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine and install plugin in configuration of game
    import ShipPlugin from 'phaser3-rex-plugins/plugins/ship-plugin.js';\nvar config = {\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexShip',\nplugin: ShipPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add ship behavior
    var ship = scene.plugins.get('rexShip').add(gameObject, config);\n
"},{"location":"ship/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Import class
    import Ship from 'phaser3-rex-plugins/plugins/ship.js';\n
  • Add ship behavior
    var ship = new Ship(gameObject, config);\n
"},{"location":"ship/#create-instance","title":"Create instance","text":"
var ship = scene.plugins.get('rexShip').add(gameObject, {\n// maxSpeed: 200,\n// acceleration: 200,\n// drag: 0.99,\n// turnSpeed: 300,\n// wrap: true,\n// padding: 0,\n// enable: true,\n// cursorKeys: scene.input.keyboard.createCursorKeys()\n});\n
  • Movement
    • maxSpeed
    • acceleration
    • drag
  • Rotation
    • turnSpeed : Angular velocity
  • Wrap
    • wrap : Set true to enable wrap mode. Default value is true.
    • padding
  • enable : set false to disable moving.
  • cursorKeys : CursorKey object, using keyboard's cursorKeys by default.
"},{"location":"ship/#set-max-speed","title":"Set max speed","text":"
ship.setMaxSpeed(speed);\n
"},{"location":"ship/#set-acceleration","title":"Set acceleration","text":"
ship.setAcceleration(acc);\n
"},{"location":"ship/#set-drag","title":"Set drag","text":"
ship.setDrag(drag);\n
"},{"location":"ship/#set-turn-speed","title":"Set turn speed","text":"
ship.setTurnSpeed(angularVelocity);\n
"},{"location":"ship/#set-wrap-mode","title":"Set wrap mode","text":"
ship.setWrapMode(wrap, padding);\n
  • wrap : Set true to enable wrap mode.
"},{"location":"skew-image/","title":"Image","text":""},{"location":"skew-image/#introduction","title":"Introduction","text":"

Skewable Image.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"skew-image/#live-demos","title":"Live demos","text":"
  • Skew image
"},{"location":"skew-image/#usage","title":"Usage","text":"

Sample code

"},{"location":"skew-image/#install-plugin","title":"Install plugin","text":""},{"location":"skew-image/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquadimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquadimageplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexSkewImage(x, y, texture, frame);\n
"},{"location":"skew-image/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuadImagePlugin from 'phaser3-rex-plugins/plugins/quadimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuadImagePlugin',\nplugin: QuadImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexSkewImage(x, y, texture, frame);\n
"},{"location":"skew-image/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { SkewImage } from 'phaser3-rex-plugins/plugins/quadimage.js';\n
  • Add image object
    var image = new SkewImage(scene, x, y, texture, frame);\nscene.add.existing(image);\n
"},{"location":"skew-image/#create-instance","title":"Create instance","text":"
var image = scene.add.rexSkewImage(x, y, texture, frame);\n

or

var image = scene.add.rexSkewImage({\n// x: 0,\n// y: 0,\nkey,\n// frame: null,\n});\n

Add quadimage from JSON

var quadimage = scene.make.rexSkewImage({\nx: 0,\ny: 0,\n\nkey: null,\nframe: null,\n\nadd: true\n});\n
"},{"location":"skew-image/#custom-class","title":"Custom class","text":"
  • Define class
    class MySkewImage extends SkewImage {\nconstructor(scene, x, y, texture, frame) {\nsuper(scene, x, y, texture, frame);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MySkewImage(scene, x, y, texture, frame);\n
"},{"location":"skew-image/#skew","title":"Skew","text":"
  • Set
    image.setSkewX(skewXRad);\nimage.setSkewXDeg(skewXDeg);\n
    image.setSkewY(skewXRad);\nimage.setSkewYDeg(skewXDeg);\n
    image.setSkew(skewXRad, skewYRad);\nimage.setSkewDeg(skewXDeg, skewYDeg);\n
    image.skewX = skewXRad;\nimage.skewXDeg = skewXDeg;\n
    image.skewY = skewYRad;\nimage.skewYDeg = skewYDeg;\n
  • Get
    var skewXRad = image.skewX;\nvar skewXDeg = image.skewXDeg;\n
    var skewYRad = image.skewY;\nvar skewYDeg = image.skewYDeg;\n
"},{"location":"skew-image/#other-properties","title":"Other properties","text":"

See Mesh game object, game object

"},{"location":"skew-image/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"skew-image/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"skew-rendertexture/","title":"Render texture","text":""},{"location":"skew-rendertexture/#introduction","title":"Introduction","text":"

Skewable render texture.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"skew-rendertexture/#live-demos","title":"Live demos","text":""},{"location":"skew-rendertexture/#usage","title":"Usage","text":""},{"location":"skew-rendertexture/#install-plugin","title":"Install plugin","text":""},{"location":"skew-rendertexture/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquadimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquadimageplugin.min.js', true);\n
  • Add render texture object
    var image = scene.add.rexSkewRenderTexture(x, y, width, height);\n
"},{"location":"skew-rendertexture/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuadImagePlugin from 'phaser3-rex-plugins/plugins/quadimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuadImagePlugin',\nplugin: QuadImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add render texture object
    var image = scene.add.rexSkewRenderTexturege(x, y, width, height);\n
"},{"location":"skew-rendertexture/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { SkewRenderTexture } from 'phaser3-rex-plugins/plugins/quadimage.js';\n
  • Add render texture object
    var image = new SkewRenderTexture(scene, x, y, width, height);\nscene.add.existing(image);\n
"},{"location":"skew-rendertexture/#create-instance","title":"Create instance","text":"
var image = scene.add.rexSkewRenderTexturege(x, y, width, height);\n

or

var image = scene.add.rexSkewRenderTexturege({\n// x: 0,\n// y: 0,\n// width: 32,\n// height: 32,\n});\n

Add prespective render texture from JSON

var image = scene.make.rexSkewRenderTexturege({\nx: 0,\ny: 0,    width: 32,\nheight: 32,\n\nadd: true\n});\n
"},{"location":"skew-rendertexture/#custom-class","title":"Custom class","text":"
  • Define class
    class MySkewRenderTexturege extends SkewRenderTexturege {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MySkewRenderTexturege(scene, x, y, width, height);\n
"},{"location":"skew-rendertexture/#internal-render-texture","title":"Internal render texture","text":"
var rt = image.rt;\n
  • rt : Render texture
"},{"location":"skew-rendertexture/#paste-texture","title":"Paste texture","text":"
  • Paste game object
    image.rt.draw(gameObject, x, y);\n// image.rt.draw(gameObject, x, y, alpha, tint);\n
  • gameObject : a game object, or an array of game objects
  • Paste game objects in a group
    image.rt.draw(group, x, y);\n// image.rt.draw(group, x, y, alpha, tint);\n
  • Paste game objects in a scene
    image.rt.draw(scene.children, x, y);\n// image.rt.draw(scene.children, x, y, alpha, tint);\n
  • Paste texture
    image.rt.draw(key, x, y);\n// image.rt.draw(key, x, y, alpha, tint);\n
    or
    image.rt.drawFrame(key, frame, x, y);\n// image.rt.drawFrame(key, frame, x, y, alpha, tint);\n
    • key : The key of the texture to be used, as stored in the Texture Manager.
"},{"location":"skew-rendertexture/#erase","title":"Erase","text":"
image.rt.erase(gameObject, x, y);\n
  • gameObject : a game object, or an array of game objects
"},{"location":"skew-rendertexture/#clear","title":"Clear","text":"
image.rt.clear();\n
"},{"location":"skew-rendertexture/#fill","title":"Fill","text":"
image.rt.fill(rgb, alpha);\n// image.rt.fill(rgb, alpha, x, y, width, height);\n
"},{"location":"skew-rendertexture/#other-properties","title":"Other properties","text":"

See Skew image game object, Mesh game object, game object

"},{"location":"skew-rendertexture/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"skew-rendertexture/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"slider/","title":"Slider","text":""},{"location":"slider/#introduction","title":"Introduction","text":"

Drag thumb on a slider bar.

  • Author: Rex
  • Behavior of game object
"},{"location":"slider/#live-demos","title":"Live demos","text":"
  • Slider
  • Color picker
"},{"location":"slider/#usage","title":"Usage","text":"

Sample code

"},{"location":"slider/#install-plugin","title":"Install plugin","text":""},{"location":"slider/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexsliderplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexsliderplugin.min.js', true);\n
  • Add slider behavior
    var slider = scene.plugins.get('rexsliderplugin').add(gameObject, config);\n
"},{"location":"slider/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SliderPlugin from 'phaser3-rex-plugins/plugins/slider-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexSlider',\nplugin: SliderPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add slider behavior
    var slider = scene.plugins.get('rexSlider').add(gameObject, config);\n
"},{"location":"slider/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Slider from 'phaser3-rex-plugins/plugins/slider.js';\n
  • Add slider behavior
    var slider = new Slider(gameObject, config);\n
"},{"location":"slider/#create-instance","title":"Create instance","text":"
var slider = scene.plugins.get('rexSlider').add(gameObject, {\n// endPoints: [\n//     {x:0, y:0},\n//     {x:0, y:0}\n// ],\n// value: 0,\n// enable: true,\n\n// valuechangeCallback: null,\n// valuechangeCallbackScope: null\n});\n
  • endPoints : An array of 2 end-points ([{x,y}, {x,y}])
  • value : Initial value between 0 to 1
  • enable : Set true to drag thumb
  • valuechangeCallback , valuechangeCallbackScope : Bind this callback to valuechange event
"},{"location":"slider/#set-end-points","title":"Set end-points","text":"
slider.setEndPoints(p0x, p0y, p1x, p1y);\n// slider.setEndPoints(p0, p1); // p0, p1: {x, y}\n// slider.setEndPoints(points); // points: [p0, p1]\n
"},{"location":"slider/#get-value","title":"Get value","text":"
var value = slider.value;          // value: between 0 to 1\n// var value = slider.getValue();  // value: between 0 to 1\n// var value = slider.getValue(min, max);  // value: between min to max\n
"},{"location":"slider/#set-value","title":"Set value","text":"
slider.value = newValue;       // newValue: between 0 to 1\n// slider.setValue(newValue);  // newValue: between 0 to 1\n// slider.setValue(newValue, min, max);  // newValue: between min to max\n
slider.addValue(inc);  // inc: between 0 to 1\n// slider.addValue(inc, min, max);  // inc: between min to max\n

Fires valuechange event if new value is not equal to current value.

"},{"location":"slider/#events","title":"Events","text":"
  • Value changed
    slider.on('valuechange', function(newValue, prevValue){ /* ... */ });\n
    • newValue: between 0 to 1
    • prevValue: between 0 to 1
"},{"location":"slider/#drag","title":"Drag","text":""},{"location":"slider/#drag-enable","title":"Drag enable","text":"
  • Get
    var enable = slider.enable;\n
  • Set
    slider.setEnable(enable);  // enable: true, or false\nslider.enable = enable;\n
  • Toggle
    slider.toggleEnable();\n
"},{"location":"slider/#is-dragging","title":"Is dragging","text":"
var isDragging = slider.isDragging;\n
"},{"location":"snap/","title":"Snap","text":""},{"location":"snap/#introduction","title":"Introduction","text":"

Snap a value to nearest grid slice, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"snap/#usage","title":"Usage","text":""},{"location":"snap/#round","title":"Round","text":"
var out = Phaser.Math.Snap.To(value, gap);\n// var out = Phaser.Math.Snap.To(value, gap, start);\n

Example: set gap to 5

  • Set value to 12, return 10
  • Set value to 14, return 15
"},{"location":"snap/#ceil","title":"Ceil","text":"
var out = Phaser.Math.Snap.Ceil(value, gap);\n// var out = Phaser.Math.Snap.Ceil(value, gap, start);\n

Example: set gap to 5

  • Set value to 12, return 15
  • Set value to 14, return 15
"},{"location":"snap/#floor","title":"Floor","text":"
var out = Phaser.Math.Snap.Floor(value, gap);\n// var out = Phaser.Math.Snap.Floor(value, gap, start);\n

Example: set gap to 5

  • Set value to 12, return 10
  • Set value to 14, return 10
"},{"location":"snapshot/","title":"Snapshot","text":""},{"location":"snapshot/#introduction","title":"Introduction","text":"

Get snapshot image, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"snapshot/#usage","title":"Usage","text":""},{"location":"snapshot/#get-snapshot-image","title":"Get snapshot image","text":"
  • Whole canvas
    game.renderer.snapshot(callback);\n// game.renderer.snapshot(callback, type, encoderOptions);\n
  • A rectangle area
    game.renderer.snapshotArea(x, y, width, height, callback);\n// game.renderer.snapshot(x, y, width, height, callback, type, encoderOptions);\n
    • x, y, width, height : Top-left position and size based on game viewport. (not the world)
  • A pixel
    game.renderer.snapshotPixel(x, y, callback);\n

Parameters:

  • type : 'image/png'
  • encoderOptions : 0.92
  • callback :
    function(image){ /* ... */};\n
    • image : Image element
"},{"location":"sprite/","title":"Sprite","text":""},{"location":"sprite/#introduction","title":"Introduction","text":"

Display of both static and animated images, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"sprite/#usage","title":"Usage","text":""},{"location":"sprite/#load-texture","title":"Load texture","text":"

Texture for static image

scene.load.image(key, url);\n

Reference: load image

"},{"location":"sprite/#load-atlas","title":"Load atlas","text":"

Atlas for animation images

scene.load.atlas(key, textureURL, atlasURL);\n

Reference: load atlas

"},{"location":"sprite/#add-sprite-object","title":"Add sprite object","text":"
var sprite = scene.add.sprite(x, y, key);\n// var sprite = scene.add.sprite(x, y, key, frame);\n

Add sprite from JSON

var sprite = scene.make.sprite({\nx: 0,\ny: 0,\nkey: '',\n// frame: '',\n\n// angle: 0,\n// alpha: 1\n// flipX: true,\n// flipY: true,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n\n// anims: {\n// key: ,\n// repeat: ,\n// ...\n// },\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
  • key :
    • A string
    • An array of string to pick one element at random
  • x, y, scale.x, scale.y :
    • A number
    • A callback to get return value
      function() { return 0; }\n
    • Random integer between min and max
      { randInt: [min, max] }\n
    • Random float between min and max
      { randFloat: [min, max] }\n
"},{"location":"sprite/#custom-class","title":"Custom class","text":"
  • Define class
    class MySprite extends Phaser.GameObjects.Sprite {\nconstructor(scene, x, y, texture, frame) {\nsuper(scene, x, y, texture, frame);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var sprite = new MySprite(scene, x, y, key);\n
"},{"location":"sprite/#texture","title":"Texture","text":"

See game object - texture

"},{"location":"sprite/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"sprite/#create-mask","title":"Create mask","text":"
var mask = sprite.createBitmapMask();\n

See mask

"},{"location":"sprite/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"sprite/#animation","title":"Animation","text":""},{"location":"sprite/#create-animation","title":"Create animation","text":"
  • Global animation for all sprites
    scene.anims.create(config);\n
  • Private animation for this sprite
    sprite.anims.create(config);\n

config : See Add animation section.

"},{"location":"sprite/#create-aseprite-animation","title":"Create Aseprite animation","text":"
  • Global Aseprite animation for all sprites
    scene.anims.createFromAseprite(key, tags);\n
  • Private Aseprite animation for this sprite
    sprite.anims.createFromAseprite(key, tags);\n
"},{"location":"sprite/#remove-animation","title":"Remove animation","text":"
  • Remove from global animation manager
    scene.anims.remove(key);\n
    or
    sprite.anims.globalRemove(key);\n
  • Remove from private animation state
    sprite.anims.remove(key);\n
"},{"location":"sprite/#get-animation","title":"Get animation","text":"
  • Get global animation object
    var anim = scene.anims.get(key);\n
  • Get private animation object
    var anim = sprite.anims.get(key);\n
"},{"location":"sprite/#has-animation","title":"Has animation","text":"
  • Has global animation object
    var hasAnim = scene.anims.exists(key);\n
  • Get private animation object
    var hasAnim = sprite.anims.exists(key);\n
"},{"location":"sprite/#play-animation","title":"Play animation","text":"
  • Play
    sprite.play(key);\n// sprite.play(key, ignoreIfPlaying);\n
    • key : Animation key string, or animation config
      • String key of animation
      • Animation config, to override default config
        {\nkey,\nframeRate,\nduration,\ndelay,\nrepeat,\nrepeatDelay,\nyoyo,\nshowOnStart,\nhideOnComplete,\nstartFrame,\ntimeScale\n}\n
  • Play in reverse
    sprite.playReverse(key);\n// sprite.playReverse(key, ignoreIfPlaying);\n
    • key : Animation key string, or animation config
  • Play after delay
    sprite.playAfterDelay(key, delay);\n
    • key : Animation key string, or animation config
  • Play after repeat
    sprite.playAfterRepeat(key, repeatCount);\n
    • key : Animation key string, or animation config
"},{"location":"sprite/#chain","title":"Chain","text":"
  • Chain next animation
    sprite.chain(key);\n
    • key : Animation key string, or animation config
  • Chain next and next animation
    sprite.chain(key0).chain(key1);\n
    • key0, key1 : Animation key string, or animation config
"},{"location":"sprite/#stop","title":"Stop","text":"
  • Immediately stop
    sprite.stop();\n
  • Stop after delay
    sprite.stopAfterDelay(delay);\n
  • Stop at frame
    sprite.stopOnFrame(frame);\n
    • frame : Frame object in current animation.
      var currentAnim = sprite.anims.currentAnim;\nvar frame = currentAnim.getFrameAt(index);\n
  • Stop after repeat
    sprite.stopAfterRepeat(repeatCount);\n
"},{"location":"sprite/#restart","title":"Restart","text":"
sprite.anims.restart();\n// sprite.anims.restart(includeDelay, resetRepeats);\n
"},{"location":"sprite/#time-scale","title":"Time scale","text":"
  • Get
    var timeScale = sprite.anims.globalTimeScale;\n
  • Set
    sprite.anims.globalTimeScale = timeScale;\n

See also Global time scale

"},{"location":"sprite/#properties","title":"Properties","text":"
  • Has started
    var hasStarted = sprite.anims.hasStarted;\n
  • Is playing
    var isPlaying = sprite.anims.isPlaying;\n
  • Is paused
    var isPaused = sprite.anims.isPaused;\n
  • Total frames count
    var frameCount = sprite.anims.getTotalFrames();\n
  • Delay
    var delay = sprite.anims.delay;\n
  • Repeat
    • Total repeat count
      var repeatCount = sprite.anims.repeat;\n
    • Repeat counter
      var repeatCount = sprite.anims.repeatCounter;\n
    • Repeat delay
      var repeatDelay = sprite.anims.repeatDelay;\n
    • Yoyo
      var repeatDelay = sprite.anims.yoyo;\n
  • Current animation key
    var key = sprite.anims.getName();\n
    • key : Return '' if not playing any animation.
  • Current frame name
    var frameName = sprite.anims.getFrameName();\n
    • frameName : Return '' if not playing any animation.
  • Current animation
    var currentAnim = sprite.anims.currentAnim;\n
  • Current frame
    var currentFrame = sprite.anims.currentFrame;\n
"},{"location":"sprite/#events","title":"Events","text":"
  • On start
    sprite.on('animationstart', function(currentAnim, currentFrame, sprite){});\n
    sprite.on('animationstart-' + key, function(currentAnim, currentFrame, sprite){});\n
  • On restart
    sprite.on('animationrestart', function(currentAnim, currentFrame, sprite){});\n
    sprite.on('animationrestart-' + key, function(currentAnim, currentFrame, sprite){});\n
  • On complete
    sprite.on('animationcomplete', function(currentAnim, currentFramee, sprite){});\n
    sprite.on('animationcomplete-' + key, function(currentAnim, currentFramee, sprite){});\n
  • On stop
    sprite.on('animationstop', function(currentAnim, currentFrame, sprite){});\n
    sprite.on('animationstop-' + key, function(currentAnim, currentFrame, sprite){});\n
  • On update
    sprite.on('animationupdate', function(currentAnim, currentFrame, sprite){});\n
    sprite.on('animationupdate-' + key, function(currentAnim, currentFrame, sprite){});\n
  • On repeat
    sprite.on('animationrepeat', function(currentAnim, currentFrame, sprite){});\n
    sprite.on('animationrepeat-' + key, function(currentAnim, currentFrame, sprite){});\n
"},{"location":"statemanager/","title":"State manager","text":""},{"location":"statemanager/#introduction","title":"Introduction","text":"

Another version of Finite state machine.

  • Author: Rex
  • Object
"},{"location":"statemanager/#usage","title":"Usage","text":"

Sample code

"},{"location":"statemanager/#install-plugin","title":"Install plugin","text":""},{"location":"statemanager/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexstatemanagerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexstatemanagerplugin.min.js', true);\n
  • Add StateManager object
    var states = scene.plugins.get('rexstatemanagerplugin').add(config);\n
"},{"location":"statemanager/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import StateManagerPlugin from 'phaser3-rex-plugins/plugins/statemanager-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexStateManager',\nplugin: StateManagerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add StateManager object
    var states = scene.plugins.get('rexStateManager').add(config);\n
"},{"location":"statemanager/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import StateManager from 'phaser3-rex-plugins/plugins/statemanager.js';\n
  • Add StateManager object
    var states = new StateManager(config);\n
"},{"location":"statemanager/#create-instance","title":"Create instance","text":"
var states = scene.plugins.get('rexStateManager').add({\neventEmitter: undefined\n});\n
  • eventEmitter
    • undefined : Create a private event emitter, default value.
    • false : Don't add any event emitter, i.e. no event will be fired.
    • Event emitter object : Fire event through this event emitter.
"},{"location":"statemanager/#custom-class","title":"Custom class","text":"
  • Define class
    class MyStates extends StateManager {\nconstructor(config) {\nsuper(config);\n\nthis.addStates({\nA: {\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {}\n},\n// ...\n});\n}\n}\n
  • Create instance
    var states = new MyStates(config);\n
"},{"location":"statemanager/#add-new-state","title":"Add new state","text":"

states.addState(name, {\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {}\n})\n
states.addState({\nname: 'A',\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {}\n})\n

or

states.addStates({\n'A' : {\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {}\n},\n// ...\n})\n
states.addStates([\n{\nname: 'A',\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {}\n},\n// ...\n]);\n

"},{"location":"statemanager/#read-state","title":"Read state","text":"
  • Current state
    var curState = state.state;\n
  • Previous state
    var preState = state.prevState;\n
"},{"location":"statemanager/#start-at-state","title":"Start at state","text":"

Set new state without triggering any state-changing callbacks or events.

state.start(newState);\n
"},{"location":"statemanager/#next-state","title":"Next state","text":"
graph TB\n\nnext[\"states.next()\"] --> next_A[\"stateA.next()<br>return 'B'\"]\n\nnext_A --> eventStateChange[\"states.emit('statechange', states)<br>states.prevState -> states.state\"]\n\nsubgraph State changing\n\neventStateChange --> exit_A[\"stateA.exit()\"]\nexit_A --> eventExitA[\"states.emit('exit_A', states)\"]\n\neventExitA --> enter_B[\"stateB.enter()\"]\nenter_B --> eventEnterB[\"states.emit('enter_B', states)\"]\n\nsubgraph Exit\nexit_A\neventExitA\nend\n\nsubgraph Enter\nenter_B\neventEnterB\nend\n\nend\n\ngoto[\"states.goto('B')\"] --> eventStateChange\n\nsubgraph Request\n\nsubgraph Next\nnext\nnext_A\nend\n\nsubgraph Goto\ngoto\nend\n\nend
"},{"location":"statemanager/#request","title":"Request","text":"
  • Get next state by callback
    states.next();    // nextState = stateA.next()    \n
  • Goto state
    states.goto(nextState);\n// states.state = nextState;\n
"},{"location":"statemanager/#state-changing","title":"State-changing","text":"

These callbacks or events will be triggered if state is changing.

For example, state is changing from 'A' to 'B'.

  1. event statechange
    states.on('statechange', function(states) {\nconsole.log( states.prevState + '->' + states.state );\n});\n
  2. callback stateA.exit
  3. event exit_A
    states.on('exit_A', function(states) {\n/*...*/\n});\n
  4. callback stateB.enter
  5. event enter_B
    states.on('enter_B', function(states) {\n/*...*/\n});\n
"},{"location":"statemanager/#enable","title":"Enable","text":"
states.setEnable();\n// states.setEnable(false); // disable\n

or

states.toggleEnable();\n

states.next() and states.goto() will be ignored if disabled.

"},{"location":"statemanager/#update","title":"Update","text":"
  • Start
    states.startUpdate();\nstates.startPreUpdate();\nstates.startPostUpdate();\n// Assume that `scene` is assigned in config of constructor\n
    or
    states.startUpdate(scene);\nstates.startPreUpdate(scene);\nstates.startPostUpdate(scene);\n
    • scene : Scene object
  • Stop
    states.stopUpdate();\nstates.stopPreUpdate();\nstates.stopPostUpdate();\n
  • Get scene
    var scene = states.getScene();\n// var scene = states._scene;\n
"},{"location":"statemanager/#remove-state","title":"Remove state","text":"
  • Remve a state
    states.removeState(stateName);\n
  • Remve all states
    states.removeAllStates();\n
"},{"location":"step/","title":"Step","text":""},{"location":"step/#introduction","title":"Introduction","text":"

Interpolate points between previous position and current position with fixed step length.

  • Author: Rex
  • Behavior of game object
"},{"location":"step/#live-demos","title":"Live demos","text":"
  • Step
"},{"location":"step/#usage","title":"Usage","text":"

Sample code

"},{"location":"step/#install-plugin","title":"Install plugin","text":""},{"location":"step/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexstepplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexstepplugin.min.js', true);\n
  • Add step behavior
    var step = scene.plugins.get('rexstepplugin').add(gameObject, config);\n
"},{"location":"step/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import StepPlugin from 'phaser3-rex-plugins/plugins/step-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexStep',\nplugin: StepPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add move-to behavior
    var step = scene.plugins.get('rexStep').add(gameObject, config);\n
"},{"location":"step/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Step from 'phaser3-rex-plugins/plugins/step.js';\n
  • Add move-to behavior
    var step = new Step(gameObject, config);\n
"},{"location":"step/#create-instance","title":"Create instance","text":"
var step = scene.plugins.get('rexStep').add(gameObject, {\n// enable: true,\n// stepLength: 5,    \n});\n
  • enable : Set true to fire step event for each interpolate point.
  • stepLength : Fixed length between each interpolate point.
"},{"location":"step/#enable","title":"Enable","text":"
  • Enable (default)
    step.setEnable();\n
    or
    step.enable = true;\n
  • Disable
    step.setEnable(false);\n
    or
    step.enable = false;\n
"},{"location":"step/#set-step-length","title":"Set step length","text":"
step.setStepLength(stepLength);\n// step.stepLength = stepLength;\n
"},{"location":"step/#events","title":"Events","text":"
  • On each interpolate point
    step.on('step', function(gameObject, step, x, y){\n\n}, scope);\n
    • Invoke step.cancelStep() to cancel interpolation.
  • On interpolate points between previous position and current position
    step.on('steps', function(gameObject, step, points){\n\n}, scope);\n
    • points : Array of point {x, y}
"},{"location":"step/#inject-methods","title":"Inject methods","text":"
  • Inject methods into game object
    scene.plugins.get('rexStep').injectMethods(gameObject);\n
  • Inject methods into class of game object
    scene.plugins.get('rexStep').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexStep').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into class of game object
    scene.plugins.get('rexStep').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexStep').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into root class of game object
    scene.plugins.get('rexStep').injectMethodsToRootClass(e);\n// scene.plugins.get('rexStep').injectMethods(Phaser.GameObjects.GameObject.prototype);\n
"},{"location":"step/#injected-methods","title":"Injected methods","text":"
  • Step start
    gameObject.stepStart(stepLength);\n// gameObject.stepStart({stepLength});\n
  • Step stop
    gameObject.stepStop();\n
  • Events
    • Step
      gameObject.on('step.step', function(gameObject, x, y) { });\n
"},{"location":"structs-list/","title":"List","text":""},{"location":"structs-list/#introduction","title":"Introduction","text":"

An ordered list, built-in data structure of phaser.

  • Author: Richard Davey
"},{"location":"structs-list/#usage","title":"Usage","text":""},{"location":"structs-list/#create-instance","title":"Create instance","text":"
var list = new Phaser.Structs.List();\n
"},{"location":"structs-list/#add-child","title":"Add child","text":"
list.add(child);\n
list.addAt(child, index);\n
"},{"location":"structs-list/#exist","title":"Exist","text":"
var hasChild = list.exists(child);\n
"},{"location":"structs-list/#get-child","title":"Get child","text":"
var firstChild = list.first;\nvar nextChild = list.next;\nvar prevChild = list.previous;\nvar lastChild = list.last;\n
var child = list.getByName(name);\n
var child = list.getRandom(startIndex, length);\n
var child = list.getFirst(property, value, startIndex, endIndex);\n// value: the value to test the property against. Must pass a strict (`===`) comparison check.\n
var child = list.getAll(property, value, startIndex, endIndex);\n// value: the value to test the property against. Must pass a strict (`===`) comparison check.\n
var child = list.count(property, value);\n// value: the value to test the property against. Must pass a strict (`===`) comparison check.\n
"},{"location":"structs-list/#get-children","title":"Get children","text":"
var children = list.list;\n
"},{"location":"structs-list/#sort-children","title":"Sort children","text":"
  • Sort by property
    list.sort(property);\n// list.sort(property, handler);\n
    • property : The property to lexically sort by.
    • handler :
      function (childA, childB) {\nreturn 0; // 0, 1, -1\n}\n
"},{"location":"structs-list/#remove-child","title":"Remove child","text":"
list.remove(child);\n
list.removeAt(index);\n
list.removeBetween(startIndex, endIndex);\n
list.removeAll();\n
"},{"location":"structs-list/#order-of-child","title":"Order of child","text":"
list.moveTo(child, index);\n
list.bringToTop(child);\n
list.sendToBack(child);\n
list.moveUp(child);\n
list.moveDown(child);\n
list.moveAbove(child1, child2);  // Move child1 above child2\n
list.moveBelow(child1, child2);  // Move child1 below child2\n
list.swap(child1, child2);\n
list.reverse();\n
list.shuffle();\n
"},{"location":"structs-list/#replace-child","title":"Replace child","text":"
list.replace(oldChild, newChild);\n
"},{"location":"structs-list/#set-properties","title":"Set properties","text":"
list.setAll(property, value, startIndex, endIndex);\n
"},{"location":"structs-list/#for-each-child","title":"For each child","text":"
  • Iterate current children list
    list.each(callback);\n// list.each(callback, context);\n// list.iterate(callback, context, arg0, arg1, ...);\n
    • callback :
      function(child, arg0, arg1, ...) {\n\n}\n
"},{"location":"structs-list/#children-counts","title":"Children counts","text":"
var size = list.length;\n
"},{"location":"structs-set/","title":"Set","text":""},{"location":"structs-set/#introduction","title":"Introduction","text":"

A collection of unique elements, built-in data structure of phaser.

  • Author: Richard Davey
"},{"location":"structs-set/#usage","title":"Usage","text":""},{"location":"structs-set/#create-instance","title":"Create instance","text":"
var set = new Phaser.Structs.Set();\n

or

var set = new Phaser.Structs.Set(elements);\n
"},{"location":"structs-set/#add-an-element","title":"Add an element","text":"
set.set(element);\n
"},{"location":"structs-set/#remove-an-element","title":"Remove an element","text":"
set.delete(element);\n
"},{"location":"structs-set/#remove-all-elements","title":"Remove all elements","text":"
set.clear();\n
"},{"location":"structs-set/#has-element","title":"Has element","text":"
set.contains(element);\n
"},{"location":"structs-set/#get-elements","title":"Get elements","text":"
var elements = set.entries;\n

or get a shallow copy of elements

var elements = set.getArray();\n
"},{"location":"structs-set/#element-counts","title":"Element counts","text":"
var size = set.size;\n
"},{"location":"structs-set/#for-each-element","title":"For each element","text":"
  • For when you know this Set will be modified during the iteration.
    set.each(function(element, index) {\n// return false;  // return false to cancel iteration\n}, scope)\n
  • For when you absolutely know this Set won't be modified during the iteration.
    set.iterate(function(element, index) {\n// return false;  // return false to cancel iteration\n}, scope)\n
"},{"location":"structs-set/#set-operations","title":"Set operations","text":"
  • C = A | B
    var setC = setA.union(setB);\n
  • C = A & B
    var setC = setA.intersect(setB);\n
  • C = A - B
    var setC = setA.difference(setB);\n
"},{"location":"tagplayer/","title":"Tag player","text":""},{"location":"tagplayer/#introduction","title":"Introduction","text":"

Text commands to control sprites, texts, sound effect or backgroun music.

  • Author: Rex
  • Member of scene
"},{"location":"tagplayer/#live-demos","title":"Live demos","text":"
  • Sprite
  • Textbox
  • Custom game object
  • Viewport-coordinate
"},{"location":"tagplayer/#usage","title":"Usage","text":"

Sample code

"},{"location":"tagplayer/#install-plugin","title":"Install plugin","text":""},{"location":"tagplayer/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextagplayerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextagplayerplugin.min.js', true);\n
  • Add tag-player object
    var tagPlayer = scene.plugins.get('rextagplayerplugin').add(scene, config);\n
"},{"location":"tagplayer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TagPlayerPlugin from 'phaser3-rex-plugins/plugins/tagplayer-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTagPlayerPlugin',\nplugin: TagPlayerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add tag-player object
    var tagPlayer = scene.plugins.get('rexTagPlayerPlugin').add(scene, config);\n
"},{"location":"tagplayer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TagPlayer from 'phaser3-rex-plugins/plugins/tagplayer.js';\n
  • Add tag-player object
    var tagPlayer = new TagPlayer(scene, config);\n
"},{"location":"tagplayer/#create-instance","title":"Create instance","text":"
var tagPlayer = scene.plugins.get('rexTagPlayerPlugin').add(scene, {\nparser: {\ndelimiters: '[]',\ncomment: '//',\n// translateTagNameCallback: undefined,\n}\n\nsprites: {\n// createGameObject: 'sprite',\n// fade: 500,  \n// fade: {mode: 'tint', time: 500},\n// viewportCoordinate: false,\n// symbols: undefined,  // { key:value }\n}, // sprites: false,\n\ntexts: {\n// createGameObject: undefined,        \n// fade: 500,\n// fade: {mode: 'tint', time: 500},\n// viewportCoordinate: false,\n// symbols: undefined,  // { key:value }\n}\n// texts: false,\n\nlayers: undefined, // []\n\nsounds: {\nbgm: {\ninitial: undefinied,\nloop: true,\nfade: 500\n},\nbgm2: {\ninitial: undefinied,\nloop: true,\nfade: 500\n}\n},\n\nclickTarget: scene,\n});\n
  • parser : Configuration of parser.
    • parser.delimiters : Delimiters of tag.
      • A single string with 2 characters. Default value is '[]'.
      • A array with 2 strings. e.x. ['[[',']]'].
    • parser.comment : Start word of a comment line. Default value is '//'.
      • null, or false : No comment line.
    • parser.translateTagNameCallback : Callback to translate tag-name
      • undefined : Use original tag-name. Default behavior.
      • A function, return new tag name.
        function(tagName) {\nreturn newTagName;\n}\n
  • sprites : Configuration of sprites.
    • sprites.createGameObject :
      • 'sprite' : Create sprite game object. Default behavior.
      • 'image' : Create image game object.
      • Callback to return a game object
        function(scene, a, b, c) {\n// return gameObject;\n}\n
        • a, b, c : Parameters pass from [sprite.name=a,b,c]
    • sprites.fade :
      • 0 : No fade-in or fade-out when adding or removing a sprite.
      • A number : Duration of fading. Default value is 500.
      • A plain object contains mode, time
        • sprite.fade.mode : Fade mode
          • 'tint', or 0 : Fade-in or fade-out via tint property.
          • 'alpha', or 1 : Fade-in or fade-out via alpha property.
          • 'revealUp', or 2 : Reveal up for fade-in.
          • 'revealDown', or 3 : Reveal down for fade-in.
          • 'revealLeft', or 4 : Reveal left for fade-in.
          • 'revealRight', or 5 : Reveal right for fade-in.
        • sprite.fade.time : Duration of fading. Default value is 500.
    • sprites.viewportCoordinate : Apply viewportCoordinate behavior to sprite game object.
      • true : Attach vpx, vpy, vp to sprite game object.
        • vpx, vpy : Number between 0~1. Proportion of viewport.
        • vp : Viewport in rectangle
      • false : Do nothing, default behavior.
    • sprites.symbols : Convert string value to number value when Set or Ease property of game object.
      • A plain object contains string key and number value.
    • false, null : No sprite manager
  • texts : Configuration of texts.
    • texts.createGameObject :
      • undefined, or 'text' : Create text game object. Default behavior.
      • Callback to return a game object
        function(scene, a, b, c) {\n// return gameObject;\n}\n
        • a, b, c : Parameters pass from [text.name=a,b,c]
    • texts.fade :
      • 0 : No fade-in or fade-out when adding or removing a text game object.
      • A number : Duration of fading. Default value is 500.
      • A plain object contains mode, time
        • texts.fade.mode : Fade mode
          • 'tint', or 0 : Fade-in or fade-out via tint property.
          • 'alpha', or 1 : Fade-in or fade-out via alpha property.
          • 'revealUp', or 2 : Reveal up for fade-in.
          • 'revealDown', or 3 : Reveal down for fade-in.
          • 'revealLeft', or 4 : Reveal left for fade-in.
          • 'revealRight', or 5 : Reveal right for fade-in.
        • texts.fade.time : Duration of fading. Default value is 500.
    • texts.viewportCoordinate : Apply viewportCoordinate behavior to text game object.
      • true : Attach vpx, vpy, vp to sprite game object.
        • vpx, vpy : Number between 0~1. Proportion of viewport.
        • vp : Viewport in rectangle
      • false : Do nothing, default behavior.
    • texts.symbols : Convert string value to number value when Set or Ease property of game object.
      • A plain object contains string key and number value.
    • false, null : No text manager
  • layers :
    • undefined : Don't create layerManger.
    • Array of string : Pre-create layer game objects in layerManger.
  • sounds : Configuration of sound effect, or background music.
    • sounds.bgm.initial, sounds.bgm2.initial : Initial music instance created by scene.sound.add(key) before starting playing content.
      • undefined : No initial music instance, default value.
    • sounds.bgm.loop, sounds.bgm2.loop :
      • true : Loop background music, default behavior.
      • false : Play background music once.
    • sounds.bgm.fade, sounds.bgm2.fade :
      • 0 : No fade-in or fade-out when starting or stopping a background music.
      • A number : Fade-in or fade-out (cross-fade) when starting or stopping a background music. Default value is 500.
  • clickTarget : Click target.
    • scene : Any pointer down on this scene. Default target.
"},{"location":"tagplayer/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTagPlayer extends TagPlayer {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\n}\n// ...\n}\n
  • Create instance
    var tagPlayer = new MyTagPlayer(scene, config);\n
"},{"location":"tagplayer/#game-object-manager","title":"Game object manager","text":"
tagPlayer.addGameObjectManager({\nname: goType,\ncreateGameObject: function(scene, ...) {\nreturn gameObject\n},\n\n// fade: 500,\n// fade: {mode: 'tint', time: 500},\n\n// viewportCoordinate: false,\n// viewportCoordinate: { viewport: new Phaser.Geom.Rectangle() },\n\n// defaultLayer: layerName,\n\n// symbols: undefined,  // { key:value },\n})\n
  • name : Name of this game object manager, a string.
  • createGameObject : Callback to return a game object
    function(scene, a, b, c) {\n// return gameObject;\n}\n
    • a, b, c : Parameters pass from [goType.name=a,b,c]
  • fade : Tint-fade (if game object has tint property) or alpha-fade game object when creating or destroying a game object.
    • 0 : No fade-in or fade-out when adding or removing a game object.
    • A number : Duration of fading. Default value is 500.
    • A plain object contains mode, time
      • fade.mode : Fade mode
        • 'tint', or 0 : Fade-in or fade-out via tint property.
        • 'alpha', or 1 : Fade-in or fade-out via alpha property.
        • 'revealUp', or 2 : Reveal up for fade-in.
        • 'revealDown', or 3 : Reveal down for fade-in.
        • 'revealLeft', or 4 : Reveal left for fade-in.
        • 'revealRight', or 5 : Reveal right for fade-in.
      • fade.time : Duration of fading. Default value is 500.
  • viewportCoordinate : Apply viewportCoordinate behavior to sprite game object.
    • false : Do nothing, default behavior.
    • true, or an object :
      • viewport :
        • undefined : Rectangle of display area under main camera of current scene. Default value.
        • A rectangle
  • defaultLayer : Put this game object into layer inside of layerManager.
  • symbols : Convert string value to number value when Set or Ease property of game object.
    • A plain object contains string key and number value.
"},{"location":"tagplayer/#built-in-commands","title":"Built-in commands","text":"

goType : name parameter in config of tagPlayer.addGameObjectManager method

  • Add game object : [goType.name=a,b,c]
    • Tint-fade-in, or alpha-fade-in if fade is not 0
  • Remove game object : [/goType.name]
    • Tint-fade-out, or alpha-fade-out if fade is not 0
  • Remove all game objects : [/goType]
    • Tint-fade-out, or alpha-fade-out if fade is not 0
  • Call method : [goType.name.methodName=value0,value1,value2]
  • Set property : [goType.name.x=value], [goType.name.alpha=value], ....
  • Ease property :
    [goType.name.prop.easeMode=value,duration]\n[goType.name.prop.easeMode=value,duration,repeat]\n[goType.name.prop.easeMode=value,duration,easeFunction,repeat]\n[goType.name.prop.easeMode=value]\n
    • prop : Any number property of this sprite.
    • easeMode : One of these modes
      • to, toLeft, toRight, toUp, toDown
      • yoyo, yoyoLeft, yoyoRight, yoyoUp, yoyoDown
      • from, fromLeft, fromRight, fromUp, fromDown
    • duration : Default value is 1000
    • easeFunction : Default value is 'Linear'
    • repeat : Default value is 0
  • Wait ease task of game object's number property : [wait=goType.name.prop]
    • Also fire event 'wait.' + goType
      tagPlayer.on('wait.' + goType, function(name, prop) {\n})\n
  • Wait a game objects are destroyed : [wait=goType.name]
    • Also fire event 'wait.' + goType
      tagPlayer.on('wait.' + goType, function(name, prop) {\n// prop parameter are `undefined` here\n})\n
  • Wait all game objects are destroyed : [wait=goType]
    • Also fire event 'wait.' + goType
      tagPlayer.on('wait.' + goType, function(name, prop) {\n// name and prop parameter are `undefined` here\n})\n
  • Wait boolean data in game object's data manager set to true/false : [wait=goType.name.dataKey]/[wait=goType.name.!dataKey]
    • Also fire event 'wait.' + goType
      tagPlayer.on('wait.' + goType, function(name, prop) {\n})\n
"},{"location":"tagplayer/#execute-commands","title":"Execute commands","text":"
tagPlayer.play(commands);\n

or

tagPlayer.playPromise(commands)\n.then(function(){\n// Typing content complete\n})\n
"},{"location":"tagplayer/#pause","title":"Pause","text":"
  • Pause
    tagPlayer.pause();\n
  • Pause until event
    tagPlayer.pauseUntilEvent(eventEmitter, eventName);\n
  • Is paused (not playing)
    var isPaused = !tagPlayer.isPlaying;\n

Invoke this method during tag-start,tag-end, or content events to suspend parsing.

"},{"location":"tagplayer/#resume","title":"Resume","text":"
tagPlayer.resume();\n
"},{"location":"tagplayer/#time-scale","title":"Time scale","text":"

Time scale of typing, typing animation, sprite animation and easing of sprite's properties.

  • Get
    var timeScale = tagPlayer.timeScale;\n
  • Set
    tagPlayer.setTimeScale(timeScale);    
    tagPlayer.timeScale = timeScale;\n
"},{"location":"tagplayer/#events","title":"Events","text":"
  • On typing content complete
    tagPlayer.on('complete', function() {\n\n})\n
"},{"location":"tagplayer/#tags-of-content","title":"Tags of content","text":""},{"location":"tagplayer/#sprite","title":"Sprite","text":"
  • Add sprite : [sprite.name=textureKey,frameKey]
    • Tint-fade-in if sprite.fade is not 0
  • Remove sprite : [/sprite.name]
    • Tint-fade-out if sprite.fade is not 0
  • Remove all sprites : [/sprite]
    • Tint-fade-out if sprite.fade is not 0
  • Call method : [sprite.name.methodName=value0,value1,value2]
  • Set property : [sprite.name.x=value], [sprite.name.alpha=value], ....
  • Ease property :
    [sprite.name.prop.easeMode=value,duration]\n[sprite.name.prop.easeMode=value,duration,repeat]\n[sprite.name.prop.easeMode=value,duration,easeFunction,repeat]\n[sprite.name.prop.easeMode=value]\n
    • prop : Any number property of this sprite.
    • easeMode : One of these modes
      • to, toLeft, toRight, toUp, toDown
      • yoyo, yoyoLeft, yoyoRight, yoyoUp, yoyoDown
      • from, fromLeft, fromRight, fromUp, fromDown
    • duration : Default value is 1000
    • easeFunction : Default value is 'Linear'
    • repeat : Default value is 0
  • Set texture : [sprite.name.texture=textureKey,frameKey]
  • Play animation : [sprite.name.play=animationKey], or [sprite.name.play=animationKey0,animationKey1,...]
    • Can play animation without adding sprite first.
  • Stop animation : [/sprite.name.play], or [sprite.name.stop]
  • Pause animation : [sprite.name.pause]
"},{"location":"tagplayer/#text","title":"Text","text":"
  • Add text : [text.name]
    • Tint-fade-in if text.fade is not 0
  • Remove text : [/text.name]
    • Tint-fade-out if text.fade is not 0
  • Remove all texts : [/text]
    • Tint-fade-out if text.fade is not 0
  • Call method : [text.name.methodName=value0,value1,value2]
  • Set property : [text.name.x=value], [text.name.alpha=value], ....
  • Ease property :
    [sprite.name.prop.easeMode=value,duration]\n[sprite.name.prop.easeMode=value,duration,repeat]\n[sprite.name.prop.easeMode=value,duration,easeFunction,repeat]\n[sprite.name.prop.easeMode=value]\n
    • prop : Any number property of this sprite.
    • easeMode : One of these modes
      • to, toLeft, toRight, toUp, toDown
      • yoyo, yoyoLeft, yoyoRight, yoyoUp, yoyoDown
      • from, fromLeft, fromRight, fromUp, fromDown
    • duration : Default value is 1000
    • easeFunction : Default value is 'Linear'
    • repeat : Default value is 0
  • Set text
    [text.name.text]\ncontent\\\\n\nnewline\\\\n\nnewline\n
  • Typing text
    [text.name.typing]\n// [text.name.typing=speed]\ncontent\\\\n\nnewline\\\\n\nnewline\n
"},{"location":"tagplayer/#sound-effect","title":"Sound effect","text":"
  • Play : [se=key], [se2=key]
    • Sound effect will be destroyed when complete
  • Play with fade in volume : [se=key,1000], [se2=key,1000]
  • Fade in volume : [se.fadein=1000], [se2.fadein=1000]
  • Fade out volume : [se.fadeout=1000], [se2.fadeout=1000]
  • Fade out volume then stop : [se.fadeout=1000,stop], [se2.fadeout=1000,stop]
  • Set volume : [se.volume=1], [se2.volume=1]
"},{"location":"tagplayer/#background-music","title":"Background music","text":"
  • Play, stop : [bgm=key], [/bgm], [bgm2=key], [/bgm2]
    • Previous background music will be stopped and destroyed.
    • Cross fade to next background music if sounds.bgm.fade/sounds.bgm2.fade is not 0
  • Play with fade in volume : [bgm=key,1000], [bgm2=key,1000]
  • Pause, resume : [bgm.pause], [/bgm.pause], [bgm2.pause], [/bgm2.pause]
  • Fade in volume : [bgm.fadein=1000], [bgm2.fadein=1000]
  • Fade out volume : [bgm.fadeout=1000], [bgm2.fadeout=1000]
  • Fade out volume then stop : [bgm.fadeout=1000,stop], [bgm2.fadeout=1000,stop]
  • Cross fade to another background music : [bgm.cross=key,10000], [bgm2.cross=key,10000]
  • Set volume : [bgm.volume=1], [bgm2.volume=1]
  • Mute : [bgm.mute], [bgm2.mute], [bgm.unmute], [bgm2.unmute]
"},{"location":"tagplayer/#camera","title":"Camera","text":"
  • Fade-in effect : [camera.fadein], [camera.fadein=1000], or [camera.fadein=duration,red,green,blue]
  • Fade-out effect : [camera.fadeout], [camera.fadeout=1000], or [camera.fadeout=duration,red,green,blue]
  • Flash effect : [camera.flash], [camera.flash=1000], or [camera.flash=duration,red,green,blue]
  • Shake effect : [camera.shake], [camera.shake=1000], or [camera.shake=duration,intensity]
  • Zoom
    • Set zoom : [camera.zoom=2]
    • Zoom to : [camera.zoom.to=1,1000], or [camera.zoom.to=zoomValue,duration,Cubic]
  • Rotate
    • Set angle : [camera.rotate=90], angle in degrees
    • Rotate to : [camera.rotate.to=0,1000], or [camera.rotate.to=deg,duration,Cubic], angle in degrees
  • Scroll
    • Scroll x,y : [camera.scroll=0,200]
    • Scroll x,y to : [camera.scroll.to=0,200,1000], or [camera.rotate.to=x,y,duration,Cubic]
"},{"location":"tagplayer/#wait-conditions","title":"Wait conditions","text":"
  • Wait click : [wait=click], [click]
    • Also fire event 'wait.click'
       tagPlayer.on('wait.click', function() {\n})\n
  • Wait key-down : [wait=enter], [wait=space], ....
    • Also fire event 'wait.keydown'
       tagPlayer.on('wait.keydown', function(keyName) {\n})\n
  • Wait time : [wait=1000]
    • Also fire event 'wait.time'
       tagPlayer.on('wait.time', function(time) {\n})\n
  • Wait sound effect : [wait=se], [wait=se2]
    • Also fire event 'wait.music'
       tagPlayer.on('wait.music', function(music) {\n// var key = music.key;\n})\n
  • Wait background music : [wait=bgm], [wait=bgm2]
    • Also fire event 'wait.music'
       tagPlayer.on('wait.music', function(music) {\n// var key = music.key;\n})\n
  • Wait camera effect : [wait=camera.fadein], [wait=camera.fadeout], [wait=camera.flash], [wait=camera.shake], [wait=camera.zoom], [wait=camera.rotate], [wait=camera.scroll]
    • Also fire event 'wait.camera'
       tagPlayer.on('wait.camera', function(effectName) {\n// effectName : 'camera.fadein', 'camera.fadeout', 'camera.flash', 'camera.shake', 'camera.zoom', 'camera.rotate', 'camera.scroll'\n})\n
  • Wait ease task of sprite's property : [wait=sprite.name.prop]
    • Also fire event 'wait.sprite'
      tagPlayer.on('wait.sprite', function(name, prop) {\n})\n
  • Wait a sprite are destroyed : [wait=sprite.name]
    • Also fire event 'wait.sprite'
      tagPlayer.on('wait.sprite', function(name, prop) {\n// prop parameter are `undefined` here\n})\n
  • Wait all sprites are destroyed : [wait=sprite]
    • Also fire event 'wait.sprite'
      tagPlayer.on('wait.sprite', function(name, prop) {\n// name and prop parameter are `undefined` here\n})\n
  • Wait boolean data in sprite's data manager set to true/false : [wait=sprite.name.dataKey]/[wait=sprite.name.!dataKey]
    • Also fire event 'wait.sprite'
      tagPlayer.on('wait.sprite', function(name, prop) {\n})\n
  • Wait callback : [wait], or [wait=xxx] (xxx is any string which not been used in above case)
    • Fire event 'wait'
      tagPlayer.on('wait', function(callback) {\n// Invoke `callback()` to continue typing\n})\n
    • Fire event 'wait.xxx'
      tagPlayer.on('wait.xxx', function(callback) {\n// Invoke `callback()` to continue typing\n})\n
  • Combine conditions : [wait=cond0|cond1|...]
    • Wait click, or enter key down : [wait=click|enter]
    • Wait click, enter key down, or 100ms : [wait=click|enter|1000]
"},{"location":"tagplayer/#custom-tag","title":"Custom tag","text":"

Assume that adding a custom tag : [custom=10,20][/custom]

  • On parse/execute a +custom tag, will add a custom command child
    tagPlayer.on('+custom', function(parser, a, b) {\n// console.log('Parse +custom tag:', a, b)\n})\n
    • a, b, ... : Parameters after =
    • Set content callback, will invoke this callback when getting a content
      var callback = function(content) {\n// ...\n}\ntagPlayer.setContentCallback(callback, scope);\n
  • On parse/execute a -custom tag, will add a custom command child
    tagPlayer.on('-custom', function(parser) {\n// console.log('Parse -custom tag')\n})\n
    • Clear content callback
      tagPlayer.setContentCallback();\n
"},{"location":"tagplayer/#content","title":"Content","text":"

These lines will be skipped :

  • Empty line, which only has space characters.
  • Comment line, start with '//'.

New line symbol '\\n' will be removed, use \\\\n to insert a new line character.

Content will pass to one of these callback/event

  1. Set content callback
    tagPlayer.setContentCallback(callback, scope);\n
    • Clear content callback
      tagPlayer.setContentCallback();\n
  2. On parse/execute a content, after a [custom] tag.
    tagPlayer.on('custom#content', function(content) {   })\n
  3. On parse/execute a content, after any tag.
    tagPlayer.on('content', function(content) {   })\n
"},{"location":"tagplayer/#game-objects","title":"Game objects","text":"
  • Get game object by name
    var gameObject = tagPlayer.getGameObject(goType, name);\n
  • Get all game objects of a game object manager
    var gameObjects = tagPlayer.getGameObject(goType);\n
    • gameObjects : {name: gameObject}
  • Add existed game object into game object manager
    tagPlayer.addGameObject(goType, name, gameObject);\n
"},{"location":"tagplayer/#data","title":"Data","text":"
  • Get
    var value = tagPlayer.getData(key);\nvar values = tagPlayer.getData(keys); // keys: an array of keys\nvar value = tagPlayer.data.values[key];\n
  • Set
    tagPlayer.setData(key, value);\ntagPlayer.incData(key, value);    tagPlayer.setData(obj); // obj: {key0:value0, key1:value1, ...}\ntagPlayer.data.values[key] = value;\ntagPlayer.data.values[key] += inc;\n
    or
    tagPlayer.toggleData(key);\n
  • Enable
    tagPlayer.setDataEnabled();\n
  • Events :
    • Set data evant
      tagPlayer.on('setdata', function(tagPlayer, key, value){ /* ... */ });\n
    • Change data event
      tagPlayer.on('changedata', function(tagPlayer, key, value, previousValue){ /* ... */ });\n
      tagPlayer.on('changedata-' + key, function(tagPlayer, value, previousValue){ /* ... */ });\n

See data manager

Note

Ensure data manager is created before binding any data-changed events.

"},{"location":"tagtext/","title":"Tag Text","text":""},{"location":"tagtext/#introduction","title":"Introduction","text":"

Displays text with multi-color, font face, or font size with tags.

  • Author: Rex
  • Game object
"},{"location":"tagtext/#live-demos","title":"Live demos","text":"
  • Tag text
"},{"location":"tagtext/#usage","title":"Usage","text":"

Sample code

"},{"location":"tagtext/#install-plugin","title":"Install plugin","text":""},{"location":"tagtext/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextagtextplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextagtextplugin.min.js', true);\n
  • Add text object
    var txt = scene.add.rexTagText(x, y, content, config);\n
"},{"location":"tagtext/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TagTextPlugin from 'phaser3-rex-plugins/plugins/tagtext-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTagTextPlugin',\nplugin: TagTextPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text object
    var txt = scene.add.rexTagText(x, y, content, config);\n
"},{"location":"tagtext/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TagText from 'phaser3-rex-plugins/plugins/tagtext.js';\n
  • Add text object
    var txt = new TagText(scene, x, y, content, config);\nscene.add.existing(txt);\n
"},{"location":"tagtext/#add-text-object","title":"Add text object","text":"
var tags = {\ntag0: {\ncolor: 'red'\n},\ntag1: {\ncolor: 'blue'\n}\n};\nvar txt = scene.add.rexTagText(x, y, '<class=\"tag0\">h</class>ello', {tags:tags});\n// var txt = scene.add.rexTagText(x, y, '<class=\"tag0\">h</class>ello', { fontFamily: 'Arial', fontSize: 64, color: '#00ff00', tags:tags });\n
  • tags : {tagName:tag}, see Properties of tag.

Default style

{\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\nbackgroundColor2: null,\nbackgroundHorizontalGradient: true,\nbackgroundStrokeColor: null,\nbackgroundStrokeLineWidth: 2,\n\nbackgroundCornerRadius: 0,\n// 0   : no round corner, \n// > 0 : convex round corner\n// < 0 : concave round corner\n\nbackgroundCornerIteration: null, color: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},\nunderline: {\ncolor: '#000',\nthickness: 0,\noffset: 0\n},\nstrikethrough: {\ncolor: '#000',\nthickness: 0,\noffset: 0\n},    // align: 'left',  // Equal to halign\nhalign: 'left', // 'left'|'center'|'right'\nvalign: 'top',  // 'top'|'center'|'bottom'\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\nmaxLines: 0,\nlineSpacing: 0,\nfixedWidth: 0,\nfixedHeight: 0,\nlineSpacing: 0,\ntestString: '|M\u00c9qgy',\n\nwrap: {\nmode: 'none'     // 0|'none'|1|'word'|2|'char'|'character'\nwidth: null\n},\n// wordWrap: { width: 0 },   // Compatible with Text game object\n\n// rtl: false,\nmetrics: false,\n// metrics: {\n//     ascent: 0,\n//     descent: 0,\n//     fontSize: 0\n// },\n\n// images: {\n//    key: { y:-8 }\n// }\n\ntags: {\n//tag0: {\n//  color: 'red'\n//},\n//tag1: {\n//  color: 'blue'\n//}\n}\n}\n
var txt = scene.add.rexTagText({\nx: 0,\ny: 0,\ntext: '',\nstyle: {\nfontSize: '64px',\nfontFamily: 'Arial',\ncolor: '#ffffff',\nalign: 'center',\nbackgroundColor: '#ff00ff',\ntags: {}\n}\n})\n

or

var txt = scene.make.rexTagText({\nx: 100,\ny: 100,\npadding: {\nleft: 64,\nright: 16,\ntop: 20,\nbottom: 40\n//x: 32,    // 32px padding on the left/right\n//y: 16     // 16px padding on the top/bottom\n},\ntext: 'Text\\nGame Object\\nCreated from config',\nstyle: {\nfontSize: '64px',\nfontFamily: 'Arial',\ncolor: '#ffffff',\nalign: 'center',\nbackgroundColor: '#ff00ff',\ntags: {}\n},\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
  • Alignment
    • halign, or align : Horizontal alignment.
      • left, center, right
    • valign : Vertical alignment.
      • top, center, bottom
  • images : See Image
"},{"location":"tagtext/#properties-of-tag","title":"Properties of tag","text":"
{\nfontFamily: 'Courier',   // or 'family', 'font-family'\nfontSize: '16px',        // or 'size', 'font-size'\nfontStyle: 'bold italic',// or 'style', 'font-style'\ncolor: 'red',            // or 'font-color'\nstroke: {\ncolor: 'blue',\nthickness: 1\n},\nshadow: {\ncolor: 'black',\noffsetX: 2,\noffsetY: 2,\nblur: 2\n},\nunderline: {            // or 'u'\ncolor: 'blue',\nthickness: 3,\noffset: -1\n},\nstrikethrough: {        // or 's'\ncolor: 'red',\nthickness: 3,\noffset: -1\n},    y: 0,\nimg: textureKey,\narea: areaKey,\n}\n
"},{"location":"tagtext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyText extends TagText {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyText(scene, x, y, '<class=\"tag0\">h</class>ello', {tags:tags});\n
"},{"location":"tagtext/#add-tag","title":"Add tag","text":"
  • Add a tag
    txt.addTag(name, prop);\n
    • name : Tag name.
    • prop : See Properties of tag
  • Add tags
    txt.addTags({\nname: prop\n});\n
"},{"location":"tagtext/#wrap","title":"Wrap","text":"
  • Wrap by word or character.
    var txt = scene.make.text({\nx: 400,\ny: 100,\ntext: 'The sky above the port was the color of television, tuned to a dead channel.',\norigin: { x: 0.5, y: 0.5 },\nstyle: {\nfont: 'bold 25px Arial',\nfill: 'white',\nwrap: {\nmode: 'word'     // 0|'none'|1|'word'|2|'char'|'character'\nwidth: 300\n}\n}\n});\n
  • Wrap mode
    • Get
      var mode = txt.style.wrapMode;\n
    • Set
      txt.setWrapMode(mode);\n
      • 'none', or 0 : No wrap
      • 'word', or 1 : Word wrap
      • 'character', or 2 : Character wrap
  • Wrap width
    • Get
      var width = txt.style.wrapWidth;\n
    • Set
      txt.setWrapWidth(width);\n// txt.setWordWrapWidth(width);\n
"},{"location":"tagtext/#content","title":"Content","text":"
  • Get source text
    var curContent = txt.text;\n
  • Get plain text
    var plainText = txt.getPlainText();\n
  • Get sub-string
    var text = txt.getText(start, end);\n
  • Set
    txt.setText('<class=\"name1\">wor</class>ld');\n// txt.text = '<class=\"name1\">wor</class>ld';\n
  • Append
    txt.appendText(text);\n// txt.text += '\\n' + text;\n
    or
    txt.appendText(text, false);\n// txt.text += text;\n
"},{"location":"tagtext/#set-style","title":"Set style","text":"
txt.setStyle(style);\ntxt.setFont(font);  // font: {fontFamily, fontSize, fontStyle}\ntxt.setFontFamily(family);\ntxt.setFontSize(size);\ntxt.setFontStyle(style);\n
"},{"location":"tagtext/#color","title":"Color","text":"
  • Text color
    • Get
      var color = txt.style.color;\n
    • Set
      txt.setColor(color);\n
      or
      txt.setFill(color);\n
  • Stroke color, thickness
    • Get
      var color = txt.style.stroke;\nvar thickness = txt.style.strokeThickness;\n
    • Set
      txt.setStroke(color, thickness);\n
    • Clear
      txt.setStroke();\n
  • Underline color, thickness
    • Get
      var color = txt.style.underlineColor;\nvar thickness = txt.style.underlineThickness;\nvar offset = txt.style.underlineOffset;\n
    • Set
      txt.setUnderline(color, thickness, ofset);\ntxt.setUnderlineColor(color);\ntxt.setUnderlineThinkness(thickness);\ntxt.setUnderlineOffset(ofset);\n
  • Strikethrough color, thickness
    • Get
      var color = txt.style.strikethroughColor;\nvar thickness = txt.style.strikethroughThickness;\nvar offset = txt.style.strikethroughOffset;\n
    • Set
      txt.setStrikethrough(color, thickness, ofset);\ntxt.setStrikethroughColor(color);\ntxt.setStrikethroughThinkness(thickness);\ntxt.setStrikethroughOffset(ofset);\n
  • Background
    • Color, or gradient color
      • Get
        var color = txt.style.backgroundColor;\nvar color2 = txt.style.backgroundColor2;\nvar isHorizontalGradient = txt.style.backgroundHorizontalGradient;\n
      • Set
        txt.setBackgroundColor(color);\n// txt.setBackgroundColor(color, color2, isHorizontalGradient);\n
    • Stroke color
      • Get
        var color = txt.style.backgroundStrokeColor;\nvar lineWidth = txt.style.backgroundStrokeLineWidth;\n
      • Set
        txt.setBackgroundStrokeColor(color, lineWidth);\n
    • Round rectangle
      • Get
        var radius = txt.style.backgroundCornerRadius;\nvar iteration = txt.style.backgroundCornerIteration;\n
      • Set
        txt.setBackgroundCornerRadius(radius);\n// txt.setBackgroundCornerRadius(radius, iteration);\n
        • radius :
          • 0 : No round corner
          • > 0 : Convex round corner
          • < 0 : Concave round corner
        • iteration :
          • undefined : Round rectangle
          • 0 : Octagon
  • Shadow
    • Get
      var color = txt.style.shadowColor;\nvar offsetX = txt.style.shadowOffsetX;\nvar offsetY = txt.style.shadowOffsetY;\nvar blur = txt.style.shadowBlur;\nvar stroke = txt.style.shadowStroke;\nvar enabled = txt.style.shadowFill;\n
    • Set
      txt.setShadow(x, y, color, blur, shadowStroke, shadowFill);\ntxt.setShadowOffset(x, y);\ntxt.setShadowColor(color);\ntxt.setShadowBlur(blur);\ntxt.setShadowStroke(enabled);\ntxt.setShadowFill(enabled);\n
"},{"location":"tagtext/#image","title":"Image","text":"
  • Uses texture key as image key by default.
  • Add image render information
    txt.addImage(imgKey, {\nkey: textureKey,\nframe: frameName,\nwidth: undefined,\nheight: undefined,\ny: 0,\nleft: 0,\nright: 0\n});\n
    • imgKey : Image key used in text content, i.e. [img=imgKey].
    • key : Texture key.
    • frame : Frame name.
    • width : Render width, set undefined to use the cut width of frame.
    • height : Render height, set undefined to use the cut height of frame.
    • y : Extra offset y.
    • left : Left padding space.
    • Right : Right padding space.
  • Add some image render informations
    txt.addImage(data);\n
    • data : {imgKey, config}
"},{"location":"tagtext/#hit-area-of-words","title":"Hit area of words","text":""},{"location":"tagtext/#hitting-events","title":"Hitting events","text":"
  • Pointer down
    txt.on('areadown', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areadown-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
  • Pointer up
    txt.on('areaup', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areaup-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
"},{"location":"tagtext/#draw-hit-areas","title":"Draw hit-areas","text":"
txt.drawAreaBounds(graphics, color);\n
  • graphics : Graphics game object
  • color : Default value is 0xffffff
"},{"location":"tagtext/#line-spacing","title":"Line spacing","text":"

This value is added to the height of the font when calculating the overall line height.

  • Get
    var lineSpacing = txt.style.lineSpacing;\n
  • Set
    txt.setLineSpacing(value);\n
"},{"location":"tagtext/#padding","title":"Padding","text":"
  • Get
    var left = txt.padding.left;\nvar top = txt.padding.top;\nvar right = txt.padding.right;\nvar bottom = txt.padding.bottom;\n
  • Set
    txt.setPadding(left, top, right, bottom);\n// txt.setPadding(padding); // padding: {left, top, right, bottom}\n
"},{"location":"tagtext/#max-lines","title":"Max lines","text":"
  • Get
    var maxLines = txt.style.maxLines;\n
  • Set
    txt.setMaxLines(max);\n
"},{"location":"tagtext/#fixed-size","title":"Fixed size","text":"
  • Get
    var width = txt.style.fixedWidth;\nvar height = txt.style.fixedHeight;\n
  • Set
    txt.setFixedSize(width, height);\n
"},{"location":"tagtext/#left-margin-of-text","title":"Left margin of text","text":"
var leftMargin = txt.measureTextMargins(testString).left;\n
  • testString : Measure left margin of this text.
"},{"location":"tagtext/#shift-start-position-of-text","title":"Shift start position of text","text":"
txt.setXOffset(value);\n
"},{"location":"tagtext/#resolution","title":"Resolution","text":"
  • Get
    var resolution = txt.style.resolution;\n
  • Set
    txt.setResolution(resolution);\n
"},{"location":"tagtext/#inline-style","title":"Inline style","text":"

Define style inline text.

  • <style='color:red'>Some text</style>
  • <style='size:30px'>Some text</style>
  • <style='y:-12;size:20px'>Some text</style>
  • <style='stroke:blue 1px'>Some text</style> (color thickness)
  • <style='shadow:blue 2px 2px 2px'>Some text</style> (color offsetX offsetY blur)
  • <style='underline:blue 3px -1px'>Some text</style> (color thickness offset)
  • <style='strikethrough:blue 3px -1px'>Some text</style> (color thickness offset)

Or mix them

  • <style='color:red;size:30px'>Some text</style>
"},{"location":"tagtext/#test-string","title":"Test string","text":"

Set the test string to use when measuring the font.

txt.setTestString(text);\n
"},{"location":"tagtext/#save-texture","title":"Save texture","text":"
txt.generateTexture(key);\n// txt.generateTexture(key, x, y, width, height);\n
"},{"location":"tagtext/#rtl","title":"RTL","text":"
  • Set rtl in style config when creating this text game object
  • Change rtl during runtime
    txt.setRTL(rtl).setText(newContent);\n
    • Invoke setRTL method before setting new content.
"},{"location":"tagtext/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"tagtext/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"tagtext/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"tcrp-player/","title":"Player","text":""},{"location":"tcrp-player/#introduction","title":"Introduction","text":"

Player of T ime-C ommand-R ecorder-P layer, to run commands on time.

  • Author: Rex
  • Member of scene
"},{"location":"tcrp-player/#live-demos","title":"Live demos","text":"
  • Replay drawing
"},{"location":"tcrp-player/#usage","title":"Usage","text":"

Sample code

"},{"location":"tcrp-player/#install-plugin","title":"Install plugin","text":""},{"location":"tcrp-player/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextcrpplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextcrpplugin.min.js', true);\n
  • Create instance
    var player = scene.plugins.get('rextcrpplugin').addPlayer(scene, config);\n
"},{"location":"tcrp-player/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TCRPPlugin from 'phaser3-rex-plugins/plugins/tcrp-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTCRP',\nplugin: TCRPPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var player = scene.plugins.get('rexTCRP').addPlayer(scene, config);\n
"},{"location":"tcrp-player/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TCRP from 'phaser3-rex-plugins/plugins/tcrp.js';\n
  • Create instance
    var player = new TCRP.Player(scene, config);\n
"},{"location":"tcrp-player/#create-instance","title":"Create instance","text":"
var player = scene.plugins.get('rexTCRP').addPlayer(scene, {\n// timeUnit: 0,        // 'ms'|0|'s'|'sec'|1\n// dtMode: 0,          // 'abs'|'absolute'|0|'inc'|'increment'|1\n// commands: [],       // [[time, command], [time, command], ...]\n// timeScale: 1,\n// scope: undefined\n});\n
  • scene : A scene object, or a game object.
  • timeUnit : see next section
  • dtMode : see next section
  • commands : see next section
  • timeScale
"},{"location":"tcrp-player/#load-commands","title":"Load commands","text":"
player.load(commands, scope, {\n// timeUnit: 0,        // 'ms'|0|'s'|'sec'|1\n// dtMode: 0           // 'abs'|'absolute'|0|'inc'|'increment'|1\n});\n
  • Commands : see also Run commands
    [\n[time, command],\n[time, command],\n...\n]\n
    • Format of each row :
      [time, fnName, param0, param1, ...]\n// [time, callback, param0, param1, ...]\n
      [time, [fnName, param0, param1, ...]]\n// [time, [callback, param0, param1, ...]]\n
      [time, [command0, command1, ...]]\n
  • timeUnit: time-unit of time
    • 'ms', or 0 : time in millisecond
    • 's', 'sec', or 1 : time in second
  • dtMode: mode of counting time
    • 'abs', 'absolute', or 0 : timeout = time
    • 'inc', 'increment', 1 : timeout = time + previous-time
"},{"location":"tcrp-player/#clear-all-commands","title":"Clear all commands","text":"
player.clear();\n
"},{"location":"tcrp-player/#append-command","title":"Append command","text":"
player.append(time, fn, param0, param1, ...);\n
  • time : Delay time
  • fn :
    • A function (callback) object.
    • A string , to get function (callback) object from scope.
  • param0, param1 ... : Parameters of callback.
"},{"location":"tcrp-player/#start-playing","title":"Start playing","text":"
player.start();\n// player.start(startAt);  // Start-at time in ms\n
"},{"location":"tcrp-player/#events","title":"Events","text":"
  • Start
    player.on('start', function(scene, player){});\n
  • Pause
    player.on('pause', function(scene, player){});\n
  • Resume
    player.on('resume', function(scene, player){});\n
  • Stop
    player.on('stop', function(scene, player){});\n
  • Complete
    player.on('complete', function(scene, player){});\n
  • Run command
    player.on('runcommand', function(commands, scope){});\n
"},{"location":"tcrp-player/#pause-resume-stop-playing","title":"Pause, Resume, stop playing","text":"
player.pause();\nplayer.resume();\nplayer.stop();\n
"},{"location":"tcrp-player/#seek-elapsed-time","title":"Seek elapsed time","text":"
player.seek(time);   // Elapsed time in ms\n
"},{"location":"tcrp-player/#seek-to-next-command","title":"Seek to next command","text":"
player.seekToNext();\n

Seek to time of next command. i.e. run next command immediately.

"},{"location":"tcrp-player/#state-of-player","title":"State of player","text":"
var isPlaying = player.isPlaying;\nvar completed = player.completed;\nvar now = player.now;\n
"},{"location":"tcrp-player/#time-scale","title":"Time-scale","text":"
  • Set
    player.setTimeScale(value);\n// player.timeScale = value;\n
  • Get
    var timeScale = player.timeScale;\n
"},{"location":"tcrp-recoder/","title":"Recoder","text":""},{"location":"tcrp-recoder/#introduction","title":"Introduction","text":"

Recorder of T ime-C ommand-R ecorder-P layer, to store commands with time.

  • Author: Rex
  • Member of scene
"},{"location":"tcrp-recoder/#live-demos","title":"Live demos","text":"
  • Replay drawing
"},{"location":"tcrp-recoder/#usage","title":"Usage","text":"

Sample code

"},{"location":"tcrp-recoder/#install-plugin","title":"Install plugin","text":""},{"location":"tcrp-recoder/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextcrpplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextcrpplugin.min.js', true);\n
  • Create instance
    var recorder = scene.plugins.get('rextcrpplugin').addRecorder(scene);\n
"},{"location":"tcrp-recoder/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TCRPPlugin from 'phaser3-rex-plugins/plugins/tcrp-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTCRP',\nplugin: TCRPPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var recorder = scene.plugins.get('rexTCRP').addRecorder(scene);\n
"},{"location":"tcrp-recoder/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TCRP from 'phaser3-rex-plugins/plugins/tcrp.js';\n
  • Create instance
    var recorder = new TCRP.Recorder(scene);\n
"},{"location":"tcrp-recoder/#create-instance","title":"Create instance","text":"
var recorder = scene.plugins.get('rexTCRP').addRecorder(scene);\n
  • Destroy when scene stopped

or

var recorder = scene.plugins.get('rexTCRP').addRecorder(gameObject);\n
  • Destroy when game object destroyed
"},{"location":"tcrp-recoder/#start-recording","title":"Start recording","text":"
recorder.start();\n// recorder.start(startAt);  // start-at time in ms\n
"},{"location":"tcrp-recoder/#push-commands","title":"Push commands","text":"
recorder.addCommand([fnName, param0, param1, ...]);\n// recorder.addCommand([command0, command1, ...]);\n// recorder.addCommand([fnName, param0, param1, ...], offset);  // time-offset in ms\n

See also Run commands

"},{"location":"tcrp-recoder/#get-commands","title":"Get commands","text":"
var commands = recorder.getCommands();        // Get a shallow copy of commands\n// var commands = recorder.getCommands(true); // Get reference of commands\n

Format of return commands:

[\n[time, [command]],\n[time, [command0,command1]],\n...\n]\n
"},{"location":"tcrp-recoder/#clear-commands","title":"Clear commands","text":"
recorder.clear();\n
"},{"location":"tcrp-recoder/#pause-resume-stop-recording","title":"Pause, Resume, stop recording","text":"
recorder.pause();\nrecorder.resume();\nrecorder.stop();\n
"},{"location":"tcrp-recoder/#seek-elapsed-time","title":"Seek elapsed time","text":"
recorder.seek(time);   // elapsed time in ms\n
"},{"location":"tcrp-recoder/#state-of-recorder","title":"State of recorder","text":"
var isRecording = recorder.isRecording;\nvar now = recorder.now;\n
"},{"location":"tcrp-recoder/#time-scale","title":"Time-scale","text":"
  • Set
    recorder.setTimeScale(value);\n// recorder.timeScale = value;\n
  • Get
    var timeScale = recorder.timeScale;\n
"},{"location":"tcrp-recoder/#events","title":"Events","text":"
  • Start
    recorder.on('start', function(scene, recorder){});\n
  • Pause
    recorder.on('pause', function(scene, recorder){});\n
  • Resume
    recorder.on('resume', function(scene, recorder){});\n
  • Stop
    recorder.on('stop', function(scene, recorder){});\n
"},{"location":"text/","title":"Text","text":""},{"location":"text/#introduction","title":"Introduction","text":"

Drawing text on canvas, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"text/#usage","title":"Usage","text":""},{"location":"text/#add-text-object","title":"Add text object","text":"
var txt = scene.add.text(x, y, 'hello');\n// var txt = scene.add.text(x, y, 'hello', { fontFamily: 'Arial', fontSize: 64, color: '#00ff00' });\n

Default style

{\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},\nalign: 'left',  // 'left'|'center'|'right'|'justify'\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\nmaxLines: 0,\nlineSpacing: 0,\nfixedWidth: 0,\nfixedHeight: 0,\nrtl: false,\ntestString: '|M\u00c9qgy',\nwordWrap: {\nwidth: null,\ncallback: null,\ncallbackScope: null,\nuseAdvancedWrap: false\n},\nmetrics: false,\n// metrics: {\n//     ascent: 0,\n//     descent: 0,\n//     fontSize: 0\n// },\n}\n

Add text from JSON

var txt = scene.make.text({\nx: 100,\ny: 100,\npadding: {\nleft: 64,\nright: 16,\ntop: 20,\nbottom: 40\n//x: 32,    // 32px padding on the left/right\n//y: 16     // 16px padding on the top/bottom\n},\ntext: 'Text\\nGame Object\\nCreated from config',\nstyle: {\nfontSize: '64px',\nfontFamily: 'Arial',\ncolor: '#ffffff',\nalign: 'center',  // 'left'|'center'|'right'|'justify'\nbackgroundColor: '#ff00ff'\n},\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
"},{"location":"text/#custom-class","title":"Custom class","text":"
  • Define class
    class MyText extends Phaser.GameObjects.Text {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyText(scene, x, y, 'hello');\n
"},{"location":"text/#word-wrap","title":"Word wrap","text":"
  • Wrap by width
    var txt = scene.make.text({\nx: 400,\ny: 100,\ntext: 'The sky above the port was the color of television, tuned to a dead channel.',\norigin: { x: 0.5, y: 0.5 },\nstyle: {\nfont: 'bold 25px Arial',\nfill: 'white',\nwordWrap: { width: 300 }\n},\n// origin: {x: 0.5, y: 0.5},\n});\n
  • Wrap by callback
    var txt = scene.make.text({\nx: 400,\ny: 300,\ntext: 'The sky above the port was the color of television, tuned to a dead channel.',\norigin: 0.5,\nstyle: {\nfont: 'bold 30px Arial',\nfill: 'white',\nwordWrap: { callback: wordWrap, scope: this }\n},\n// origin: {x: 0.5, y: 0.5},\n});\n\nfunction wordWrap (text, textObject)\n{\n// First parameter will be the string that needs to be wrapped\n// Second parameter will be the Text game object that is being wrapped currently\n\n// This wrap just puts each word on a separate line, but you could inject your own\n// language-specific logic here.\nvar words = text.split(' ');\n\n// You can return either an array of individual lines or a string with line breaks (e.g. \\n) in\n// the correct place.\nreturn words;\n}\n
  • Wrap width
    • Get
      var width = txt.style.wordWrapWidth;\nvar useAdvancedWrap = txt.style.wordWrapUseAdvanced;\n
    • Set
      txt.setWordWrapWidth(width);\n// txt.setWordWrapWidth(width, useAdvancedWrap);\n
  • Wrap callback
    • Get
      var callback = txt.style.wordWrapCallback;\nvar scope = txt.style.wordWrapCallbackScope;\n
    • Set
      txt.setWordWrapCallback(callback, scope);\n
"},{"location":"text/#content","title":"Content","text":"
  • Get
    var content = txt.text;\n
  • Set
    txt.setText(text);\n// txt.text = text;\n
  • Append
    txt.appendText(text);\n// txt.text += '\\n' + text;\n
    or
    txt.appendText(text, false);\n// txt.text += text;\n
"},{"location":"text/#set-style","title":"Set style","text":"
txt.setStyle(style);\ntxt.setFont(font);\ntxt.setFontFamily(family);\ntxt.setFontSize(size);\ntxt.setFontStyle(style);\n
"},{"location":"text/#set-align","title":"Set align","text":"
txt.setAlign(align);\n
  • align : 'left', 'center', 'right', 'justify'
"},{"location":"text/#color","title":"Color","text":"
  • Text color
    • Get
      var color = txt.style.color;\n
    • Set
      txt.setColor(color);\n
      or
      txt.setFill(color);\n
  • Stroke color, thickness
    • Get
      var color = txt.style.stroke;\nvar thickness = txt.style.strokeThickness;\n
    • Set
      txt.setStroke(color, thickness);\n
    • Clear
      txt.setStroke();\n
  • Background color
    • Get
      var color = txt.style.backgroundColor;\n
    • Set
      txt.setBackgroundColor(color);\n
  • Shadow
    • Get
      var color = txt.style.shadowColor;\nvar offsetX = txt.style.shadowOffsetX;\nvar offsetY = txt.style.shadowOffsetY;\nvar blur = txt.style.shadowBlur;\nvar stroke = txt.style.shadowStroke;\nvar enabled = txt.style.shadowFill;\n
    • Set
      txt.setShadow(x, y, color, blur, shadowStroke, shadowFill);\ntxt.setShadowOffset(x, y);\ntxt.setShadowColor(color);\ntxt.setShadowBlur(blur);\ntxt.setShadowStroke(enabled);\ntxt.setShadowFill(enabled);\n
"},{"location":"text/#line-spacing","title":"Line spacing","text":"

This value is added to the height of the font when calculating the overall line height.

  • Get
    var lineSpacing = txt.lineSpacing;\n
  • Set
    txt.setLineSpacing(value);\n
"},{"location":"text/#letter-spacing","title":"Letter spacing","text":"
  • Get
    var letterSpacing = txt.letterSpacing;\n
  • Set
    txt.setLetterSpacing(value);\n
  • value : Positive or negative value.

Note

Enabling this feature will cause Phaser to render each character in this Text object one by one, rather than use a draw for the whole string. This makes it extremely expensive when used with either long strings, or lots of strings in total.

"},{"location":"text/#padding","title":"Padding","text":"
  • Get
    var left = txt.padding.left;\nvar top = txt.padding.top;\nvar right = txt.padding.right;\nvar bottom = txt.padding.bottom;\n
  • Set
    txt.setPadding(left, top, right, bottom);\n// txt.setPadding(padding); // padding: {left, top, right, bottom}\n
"},{"location":"text/#max-lines","title":"Max lines","text":"
  • Get
    var maxLines = txt.style.maxLines;\n
  • Set
    txt.setMaxLines(max);\n
"},{"location":"text/#fixed-size","title":"Fixed size","text":"
  • Get
    var width = txt.style.fixedWidth;\nvar height = txt.style.fixedHeight;\n
  • Set
    txt.setFixedSize(width, height);\n
"},{"location":"text/#test-string","title":"Test string","text":"

Set the test string to use when measuring the font.

txt.style.setTestString(text);\n
"},{"location":"text/#rtl","title":"RTL","text":"
  • Set rtl in style config when creating this text game object
  • Change rtl during runtime
    txt.setRTL(rtl).setText(newContent);\n
    • Invoke setRTL method before setting new content.
"},{"location":"text/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"text/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"text/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"textedit/","title":"Edit","text":""},{"location":"textedit/#introduction","title":"Introduction","text":"

Create an input text object above a text object to edit string content.

  • Author: Rex
  • Behavior of text object
"},{"location":"textedit/#live-demos","title":"Live demos","text":"
  • Text edit
  • Text area
  • Number edit
  • With rexui-Label
  • Text game object inside container
"},{"location":"textedit/#usage","title":"Usage","text":"

Sample code

"},{"location":"textedit/#install-plugin","title":"Install plugin","text":""},{"location":"textedit/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextexteditplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextexteditplugin.min.js', true);\n
  • Open editor
    • Add text-edit behavior, will open editor under 'pointerdown' event.
      var editor = scene.plugins.get('rextexteditplugin').add(textGameObject, config);\n
    • Open editor directly
      var editor = scene.plugins.get('rextexteditplugin').edit(textGameObject, config);\n
"},{"location":"textedit/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TextEditPlugin from 'phaser3-rex-plugins/plugins/textedit-plugin.js';\nvar config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTextEdit',\nplugin: TextEditPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Open editor
    • Add text-edit behavior, will open editor under 'pointerdown' event.
      var editor = scene.plugins.get('rexTextEdit').add(textGameObject, config);\n
    • Open editor directly
      var editor = scene.plugins.get('rexTextEdit').edit(textGameObject, config);\n
"},{"location":"textedit/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import { TextEdit, Edit } from 'phaser3-rex-plugins/plugins/textedit.js';\n
  • Open editor
    • Add text-edit behavior, will open editor under 'pointerdown' event.
      var editor = new TextEdit(textGameObject, config);\n
    • Open editor directly
      var editor = Edit(textGameObject, config);\n
"},{"location":"textedit/#open-text-editor","title":"Open text editor","text":"

Open editor directly.

var editor = scene.plugins.get('rexTextEdit').edit(textObject, {\n// inputType: 'text',   // 'text'|'password'|'textarea'|...\n// type: 'text',    // 'text'|'password'|'textarea'|...\n\n// enterClose: true,\n// selectAll: false,\n\n// onOpen: undefined,\n// onTextChanged: undefined,\n// onClose: undefined,\n\n// text: '',\n});\n// var editor = scene.plugins.get('rexTextEdit').edit(textObject, config, onClose);\n
  • textObject : Text object, bbcode text object, or tag text object.
  • config :
    • config.inputType, or config.type :
      • 'text' (default), or
      • 'password'
      • 'number'
    • config.onOpen : Callback invoked when input text is created.
      function (textObject) {\n}\n
    • config.onTextChanged : Callback invoked when input text changed.
      function (textObject, text) {\ntextObject.text = text;\n}\n
    • config.onClose : Callback invoked when input text is closed. This parameter is valid only when onClose parameter is not given.
      function (textObject) {\n}\n
    • enterClose :
      • true : Close input text when enter-key was pressed. Default value is true if inputType is not 'textarea'.
      • false : If inputType is set to 'textarea', default value will be false.
    • config.selectAll : Set true to select all text.
    • config.text : Initial string content. Default is the string content of textObject.
    • More configuration parameters...
  • onClose : Callback invoked when input text is closed.
    var callback = function(textObject) {\n}\n

Create a text editor (input element) above text object.

  • Size, font size, font family, font color, background color, background corner radius, padding-left, padding-right of text editor will be assigned from text object.
  • Text object will be invisible when text editor is opened.
  • Store reference of text editor at textObject._editor.
  • Text editor will be closed when
    • Press enter key and enterClose is set, or
    • Touch outside of editor, or
    • Open another text editor, or
    • Call editor.close()

Limitation of text game object

Don't assign height property of text game object. Because that text input element does not have vertical align setting, text will always align to middle/center.

"},{"location":"textedit/#create-instance","title":"Create instance","text":"

Add text-edit behavior, will open editor under 'pointerdown' event.

var editor = scene.plugins.get('rexTextEdit').add(textGameObject, {\n// type: 'text',   //'text','password','number'\n// enterClose: true,\n// selectAll: false,\n\n// onOpen: undefined,\n// onTextChanged: undefined,\n// onClose: undefined,\n\n// text: '',\n});\n
"},{"location":"textedit/#open-editor","title":"Open editor","text":"
editor.open(config);\n// editor.open(config, onClose);\n
  • config
    • config.type :
      • text (default), or
      • password
    • config.text : Initial string content.
    • config.onTextChanged : Callback invoked when input text changed.
      function (textObject, text) {\ntextObject.text = text;\n}\n
    • More configuration parameters...
  • onClose : Callback invoked when text editor is closed.
    var callback = function(textObject) {\n}\n

Create a text editor (input element) above text object.

  • Size, font size, font family, font color, background color of text editor will be equal to text object.
  • Text object will be invisible when text editor is opened.
"},{"location":"textedit/#is-opened","title":"Is opened","text":"
var isOpened = editor.isOpened;\n
"},{"location":"textedit/#close-editor","title":"Close editor","text":"
editor.close();\n

Text editor will be closed when

  • Press enter key, or
  • Touch outside of editor, or
  • Open another text editor, or
  • Call editor.close()
"},{"location":"textedit/#get-dom","title":"Get DOM","text":"
var inputText = editor.inputText.node;\n
"},{"location":"textedit/#bypass-key-input","title":"Bypass key input","text":"

See InputText/Bypass key input

"},{"location":"textedit/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"

See dom-element's Interactive with other game objects

"},{"location":"textpage/","title":"Page","text":""},{"location":"textpage/#introduction","title":"Introduction","text":"

Display text page by page on text object, bbcode text object, or tag text object.

  • Author: Rex
  • Behavior of text object
"},{"location":"textpage/#live-demos","title":"Live demos","text":"
  • BBCode text + page + typing
"},{"location":"textpage/#usage","title":"Usage","text":"

Sample code

"},{"location":"textpage/#install-plugin","title":"Install plugin","text":""},{"location":"textpage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextextpageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextextpageplugin.min.js', true);\n
  • Add page behavior
    var page = scene.plugins.get('rextextpageplugin').add(textGameObject, config);\n
"},{"location":"textpage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TextPagePlugin from 'phaser3-rex-plugins/plugins/textpage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTextPage',\nplugin: TextPagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add page behavior
    var page = scene.plugins.get('rexTextPage').add(textGameObject, config);\n
"},{"location":"textpage/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TextPage from 'phaser3-rex-plugins/plugins/textpage.js';\n
  • Add page behavior
    var page = new TextPage(textGameObject, config);\n
"},{"location":"textpage/#create-instance","title":"Create instance","text":"
var page = scene.plugins.get('rexTextPage').add(textGameObject, {\n// text: '',              // content in string or array\n// maxLines: undefined,\n// pageBreak: '\\f\\n',\n});\n
  • textObject : Text object, bbcode text object, tag text object, or bitmap text object
  • text : content in string or array, optional
  • maxLines : Max lines of a page.
    • undefined : Default value. For Text object, bbcode text object, tag text object
      • Use style property maxLines.
      • Count number of lines if it has fixedHeight setting.
    • A number : Max lines of a page, for bitmap text object
  • pageBreak : Symbol of page-break. Default value is '\\f\\n'. String after this page-break symbol will be placed to a new page.
"},{"location":"textpage/#set-content","title":"Set content","text":"
  • Set content
    page.setText(content);\n
    • content : String, number, or string array. Can insert pageBreak symbol.
  • Append content
    page.appendText(content);\n
    • content : String, number, or string array. Can insert pageBreak symbol.
  • Clear content
    page.clearText()\n
  • Append page
    page.appendPage(content);   // content in string or array\n
    • content : String, number, or string array. Don't insert pageBreak symbol.
"},{"location":"textpage/#show-page","title":"Show page","text":"
  • Display current page
    page.showPage();\n
  • Display next page
    page.showNextPage();\n
  • Display previous page
    page.showPreviousPage();\n
  • Display first page
    page.showFirstPage();\n
  • Display last page
    page.showLastPage();\n
  • Display page by index
    page.showPage(index);\n
  • Display page by line index
    page.showPageNyLineIndex(index);\n

Note

Initial page index is -1, so user could call page.showNextPage() to display first page.

"},{"location":"textpage/#get-lines-of-page","title":"Get lines of page","text":""},{"location":"textpage/#page-by-page","title":"Page by page","text":"
  • Get lines of current page
    var lines = page.getPage();\n
  • Get lines of next page
    var lines = page.getNextPage();\n
  • Get lines of previous page
    var lines = page.getPreviousPage();\n
  • Get lines of first page
    var lines = page.getFirstPage();\n
  • Get lines of last page
    var lines = page.getLastPage();\n
  • Get lines of page by page index
    var lines = page.getPage(index);\n
"},{"location":"textpage/#page-of-line","title":"Page of line","text":"
  • Get line of page by line index
    var lines = page.getPageByLineIndex(index);\n
  • Get page of next line
    var lines = page.getPageOfNextLine(index);\n
  • Get page of previous line
    var lines = page.getPageOfPreviousLine(index);\n
"},{"location":"textpage/#other-properties","title":"Other properties","text":""},{"location":"textpage/#page-by-page_1","title":"Page by page","text":"
  • Is last page
    var isLastPage = page.isLastPage;\n
  • Is first page
    var isFirstPage = page.isFirstPage;\n
  • Current page index
    var pageIndex = page.pageIndex;\n
  • Number of pages
    var pageIndex = page.pageCount;\n
"},{"location":"textpage/#page-of-line_1","title":"Page of line","text":"
  • Is last line
    var isLastLine = page.isLastLine;\n
  • Is first line
    var isFirstLine = page.isFirstLine;\n
  • Start line index
    var startLineIndex = page.startLineIndex;\n
  • End line index
    var endLineIndex = page.endLineIndex;\n
  • Number of lines
    var totalLinesCount = page.totalLinesCount;\n
"},{"location":"textplayer/","title":"Text player","text":""},{"location":"textplayer/#introduction","title":"Introduction","text":"

Typing characters on dynamic text, waiting click or key enter, play sound effect or backgroun music.

  • Author: Rex
  • Game object
"},{"location":"textplayer/#live-demos","title":"Live demos","text":"
  • BBCode
  • Play
  • Sprite control
  • Show page
  • Fast typing
  • Custom game object
  • Fade out page
  • Choices
    • Custonm tag
    • Choice dailog
  • Resolution
"},{"location":"textplayer/#usage","title":"Usage","text":"

Sample code

"},{"location":"textplayer/#install-plugin","title":"Install plugin","text":""},{"location":"textplayer/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextextplayerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextextplayerplugin.min.js', true);\n
  • Add text-player object
    var txt = scene.add.rexTextPlayer(config);\n
"},{"location":"textplayer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TextPlayerPlugin from 'phaser3-rex-plugins/plugins/textplayer-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTextPlayerPlugin',\nplugin: TextPlayerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text-player object
    var txt = scene.add.rexTextPlayer(config);\n
"},{"location":"textplayer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TextPlayer from 'phaser3-rex-plugins/plugins/textplayer.js';\n
  • Add text-player object
    var txt = new TextPlayer(scene, config);\nscene.add.existing(txt);\n
"},{"location":"textplayer/#create-instance","title":"Create instance","text":"
var txt = scene.add.rexTextPlayer({\nx: 0, y: 0,\nwidth: undefined, height: undefined,\nresolution: 1,\n\npadding: 0,  // {left: 0, right: 0, top: 0, bottom: 0}\n\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\n\ninnerBounds: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\noffsetX: 0,\noffsetY: 0,\nleftSpace: 0,\nrightSpace: 0,\n},\n\nparser: {\ndelimiters: '[]',\ncomment: '//',\n// translateTagNameCallback: undefined,\n}\n\nwrap: {\ncallback: undefined, // Default wrapping callback is dynamicText.runWordWrap()\nlineHeight:\n// maxLines: \npadding: { top: 0, left: 0, right: 0, bottom: 0 },\nletterSpacing: 0,\nwrapMode: 'word',  // 1|'word'|2|'char'|'character'|3|'mix'\nhAlign: 0, // 0|'left'|1|'center'|2|'right'|3|'justify'|'justify-left'|4|'justify-center'|5| justify-right'\nvAlign: 0, // 0|'top'|1|'center'|2|'bottom'\n\n},\n\ntyping: {\nspeed: 250,\nonTypingStart: function (children) {\nfor (var i = 0, cnt = children.length; i < cnt; i++) {\nchildren[i].setVisible(false);\n}\n},  // Default: set all children invisible\nanimation: undefined,  // Default: no typing animation, only invoke onStart callback\nanimation: {\nduration: 1000,\nyoyo: false,\nonStart: function(child) {\nchild.setVisible();\n},\nonProgress: function(child, t) {\n\n},\nonComplete: function(child) {\n\n}\n},\n\n// skipSpace: false,\n\n// minSizeEnable: false,\n\nfadeOutPage: undefined,  // Default: no fade-out-page animation\nfadeOutPage: function(children) {\nreturn eventEmitter;\nreturn promise;\n},\n\n},\n\nimages: {\n// key: {width, height}\n// key: {key, frame, width, height}\n},\n\nsprites: {\n// createCallback: 'sprite',\n// createCallback: function(scene, ...) { return gameObject; },\n\n// fade: 500,\n// fade: {mode: 'tint', time: 500},\n\n// viewportCoordinate: false,\n// viewportCoordinate: { viewport: new Phaser.Geom.Rectangle() },\n\n}, layers: undefined, // []\n\nsounds: {\nbgm: {\ninitial: undefinied,\nloop: true,\nfade: 500\n},\nbgm2: {\ninitial: undefinied,\nloop: true,\nfade: 500\n}\n},\n\nclickTarget: this,  // This text player    \nnextPageInput: null,\n// ignoreNextPageInput: false,\n\ntext: undefined\n});\n
  • x, y : Position of this text-player game object.
  • width : Fixed width.
    • A number : Width of this text-player game object.
      • Wrap-width is width - padding.left - padding.right.
    • undefined : Width of this text-player game object will be set after invoked runWordWrap method.
  • height : Fixed height.
    • A number : Height of this text-player game object.
    • undefined : Height of this text-player game object will be set after invoked runWordWrap method.
  • resolution : The resolution the content is rendered to its internal canvas at. Default value is 1.
  • padding : Padding of bounds.
    • A number
    • padding.left, padding.right, padding.top, padding.bottom
  • background : Properties of background round-rectangle.
    • background.color : Fill color.
      • null : No filling.
    • background.color2 : Gradient fill color.
      • null : No gradient filling.
    • background.horizontalGradient : Horizontal or vertical gradient filling.
      • true : Horizontal gradient filling.
      • false : Vertical gradient filling.
    • background.stroke : Stroke color.
      • null : No stroke.
    • background.strokeThickness : Line width of stroke.
    • background.cornerRadius : Corner-radius of round rectangle.
      • 0 : No round corner
      • > 0 : Convex round corner
      • < 0 : Concave round corner
    • background.cornerIteration : Iteration of corner-radius.
      • null : Draw corner-radius via arc directly.
      • A number : Draw corner-radius via lines
  • innerBounds : Properties of inner-bounds.
    • innerBounds.color : Fill color.
      • null : No filling.
    • innerBounds.color2 : Gradient fill color.
      • null : No gradient filling.
    • innerBounds.horizontalGradient : Horizontal or vertical gradient filling.
      • true : Horizontal gradient filling.
      • false : Vertical gradient filling.
    • innerBounds.stroke : Stroke color.
      • null : No stroke.
    • innerBounds.strokeThickness : Line width of stroke.
  • style : Initial text-style.
    • style.bold : Bold
    • style.italic : Italic
    • style.fontSize : Font size
    • style.fontFamily : Font family
    • style.color : Fill color
    • style.stroke : Stroke color
    • style.strokeThickness : Line width of stroke.
    • style.shadowColor : Shadow color.
      • null : No shadow.
    • style.shadowOffsetX : OffsetX of shadow.
    • style.shadowOffsetY : OffsetY of shadow.
    • style.shadowBlur : Blur of shadow.
    • style.offsetX : OffsetX.
    • style.offsetY : OffsetY.
    • style.leftSpace : Extra space between this character and previous character.
    • style.rightSpace : Extra space between this character and next character.
    • style.align : Override default line-alignment setting.
      • 0, 'left', 'top' : Align remainder lines to left/top.
      • 1, 'center' : Align remainder lines to center.
      • 2, 'right', 'bottom' : Align remainder lines to right/bottom.
      • undefined : Use default line-alignment setting.
  • wrap : Default configuration Horizontal/Vertical wrapping.
  • typing :
    • typing.speed : Default typing speed of each character.
    • typing.onTypingStart : Callback when typing start. Default is to set all children to invisible.
      function (children) {\nfor (var i = 0, cnt = children.length; i < cnt; i++) {\nchildren[i].setVisible(false);\n}\n
      • children : Array of child.
    • typing.animation : Configuration of typing animation
      • undefined : No typing animation, default behavior
    • typing.animation.duration : Duration of typing animation.
    • typing.animation.yoyo :
      • false : Mapping progress t to 0 - 1. Default behavior.
      • true : Mapping progress t to 0 - 1 - 0.
    • typing.animation.onStart : Callback when typing start of a character. Default is to set this child to visible.
      function(child) { child.setVisible(); }\n
      • child
    • typing.animation.onProgress : Callback when progress typing animation.
      function(child, t) {\n}\n
      • child
    • typing.animation.onComplete : Callback when typing animation complete.
      function(child) {\n}\n
      • child
    • typing.skipSpace :
      • false : Will have delay when typing space character. Default behavior.
      • true : Typing space character immediately.
    • typing.minSizeEnable :
      • true : Resize to minimun size for showing all visible characters.
      • false : Won't resize during typing. Default behavior.
    • typing.fadeOutPage : Callback to fade-out characters of previous page.
      • undefined : Default value, no fade-out-page animation.
      • Callback
        function(characters) {\nreturn tween;  // eventEmitter\nreturn promise;\n}\n
        • characters : Fade out targets.
        • Return value could be tween object (event emitter), or promise object.
          • Tween object : Wait until 'complete' event triggering.
          • Promise object : Wait until promoise resolving.
  • parser : Configuration of parser.
    • parser.delimiters : Delimiters of tag. Default value is '[]'.
    • parser.comment : Start word of a comment line. Default value is '//'.
      • null, or false : No comment line.
    • parser.translateTagNameCallback : Callback to translate tag-name
      • undefined : Use original tag-name. Default behavior.
      • A function, return new tag name.
        function(tagName) {\nreturn newTagName;\n}\n
  • images : Configuration of images.
  • sprites : Configuration of sprites.
    • sprites.createCallback :
      • 'sprite' : Create sprite game object. Default behavior.
      • 'image' : Create image game object.
      • Callback to return a game object
        function(scene, textureKey, frameName) {\n// return scene.add.sprite(0, 0, textureKey, frameName);\n}\n
    • sprites.fade :
      • 0 : No fade-in or fade-out when adding or removing a sprite.
      • A number : Duration of fading. Default value is 500.
      • A plain object contains mode, time
        • sprite.fade.mode : Fade mode
          • 'tint', or 0 : Fade-in or fade-out via tint property.
          • 'alpha', or 1 : Fade-in or fade-out via alpha property.
          • 'revealUp', or 2 : Reveal up for fade-in.
          • 'revealDown', or 3 : Reveal down for fade-in.
          • 'revealLeft', or 4 : Reveal left for fade-in.
          • 'revealRight', or 5 : Reveal right for fade-in.
        • sprite.fade.time : Duration of fading. Default value is 500.
    • sprites.viewportCoordinate : Apply viewportCoordinate behavior to sprite game object.
      • true : Attach vpx, vpy, vp to sprite game object.
        • vpx, vpy : Number between 0~1. Proportion of viewport.
        • vp : Viewport in rectangle
      • false : Do nothing, default behavior.
    • sprites.symbols : Convert string value to number value when Set or Ease property of game object.
      • A plain object contains string key and number value.
  • layers :
    • undefined : Don't create layerManger.
    • Array of string : Pre-create layer game objects in layerManger.
  • sounds : Configuration of sound effect, or background music.
    • sounds.bgm.initial, sounds.bgm2.initial : Initial music instance created by scene.sound.add(key) before starting playing content.
      • undefined : No initial music instance, default value.
    • sounds.bgm.loop, sounds.bgm2.loop :
      • true : Loop background music, default behavior.
      • false : Play background music once.
    • sounds.bgm.fade, sounds.bgm2.fade :
      • 0 : No fade-in or fade-out when starting or stopping a background music.
      • A number : Fade-in or fade-out (cross-fade) when starting or stopping a background music. Default value is 500.
  • nextPageInput : Wait condition to type next page
    • null, or false : Stop tying next page. Default behavior
      • Typing next manually via txt.typingNextPage().
    • 'click' : Wait click.
    • 'click|2000' : Wait one of condition: click, or 2000ms.
    • 'click|enter|2000' : Wait one of condition: click, enter key down, or 2000ms.
    • A function callback :
      function(callback) {\n// Invoke `callback()` to continue typing\n}\n
  • clickTarget : Click target, default is text player itself.
    • scene : Any pointer down on this scene.
  • ignoreNextPageInput : Set true to continue typing next page without any waiting.
  • text : Content of text to play.

or

var txt = scene.add.rexTextPlayer(x, y, width, height, config);\n

or

var txt = scene.add.rexTextPlayer(x, y, config);\n

Add textplayer from JSON

var txt = scene.make.rexTextPlayer({\nx: 0,\ny: 0,\n\n// origin: {x: 0.5, y: 0.5},\n// fill: null,\n\nadd: true\n});\n
"},{"location":"textplayer/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTextPlayer extends TextPlayer {\nconstructor(scene, x, y, config) {\nsuper(scene, x, y, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyTextPlayer(scene, x, y, config);\n
"},{"location":"textplayer/#game-object-manager","title":"Game object manager","text":"
txt.addGameObjectManager({\nname: goType,\ncreateGameObject: function(scene, ...) {\nreturn gameObject\n},\n\nfade: 500,\n// fade: {mode: 'tint', time: 500},\n\n// viewportCoordinate: false,\n// viewportCoordinate: { viewport: new Phaser.Geom.Rectangle() },\n\n// defaultLayer: layerName,\n\n// symbols: undefined,  // { key:value },\n})\n
  • name : Name of this game object manager, a string.
  • createGameObject : Callback to return a game object
    function(scene, a, b, c) {\n// return gameObject;\n}\n
    • a, b, c : Parameters pass from [goType.name=a,b,c]
  • fade : Tint-fade (if game object has tint property) or alpha-fade game object when creating or destroying a game object.
    • 0 : No fade-in or fade-out when adding or removing a game object.
    • A number : Duration of fading. Default value is 500.
    • A plain object contains mode, time
      • fade.mode : Fade mode
        • 'tint', or 0 : Fade-in or fade-out via tint property.
        • 'alpha', or 1 : Fade-in or fade-out via alpha property.
        • 'revealUp', or 2 : Reveal up for fade-in.
        • 'revealDown', or 3 : Reveal down for fade-in.
        • 'revealLeft', or 4 : Reveal left for fade-in.
        • 'revealRight', or 5 : Reveal right for fade-in.
      • fade.time : Duration of fading. Default value is 500.
  • viewportCoordinate : Apply viewportCoordinate behavior to sprite game object.
    • false : Do nothing, default behavior.
    • true, or an object :
      • viewport :
        • undefined : Rectangle of display area under main camera of current scene. Default value.
        • A rectangle
  • defaultLayer : Put this game object into layer inside of layerManager.
  • symbols : Convert string value to number value when Set or Ease property of game object.
    • A plain object contains string key and number value.
"},{"location":"textplayer/#built-in-commands","title":"Built-in commands","text":"

goType : name parameter in config of txt.addGameObjectManager method

  • Add game object : [goType.name=a,b,c]
    • Tint-fade-in, or alpha-fade-in if fade is not 0
  • Remove game object : [/goType.name]
    • Tint-fade-out, or alpha-fade-out if fade is not 0
  • Remove all game objects : [/goType]
    • Tint-fade-out, or alpha-fade-out if fade is not 0
  • Call method : [goType.name.methodName=value0,value1,value2]
  • Set property : [goType.name.x=value], [goType.name.alpha=value], ....
  • Ease property :
    [goType.name.prop.easeMode=value,duration]\n[goType.name.prop.easeMode=value,duration,repeat]\n[goType.name.prop.easeMode=value,duration,easeFunction,repeat]\n[goType.name.prop.easeMode=value]\n
    • prop : Any number property of this sprite.
    • easeMode : One of these modes
      • to, toLeft, toRight, toUp, toDown
      • yoyo, yoyoLeft, yoyoRight, yoyoUp, yoyoDown
      • from, fromLeft, fromRight, fromUp, fromDown
    • duration : Default value is 1000
    • easeFunction : Default value is 'Linear'
    • repeat : Default value is 0
  • Wait ease task of game object's number property : [wait=goType.name.prop]
    • Also fire event 'wait.' + goType
      txt.on('wait.' + goType, function(name, prop) {\n})\n
  • Wait a game objects are destroyed : [wait=goType.name]
    • Also fire event 'wait.' + goType
      txt.on('wait.' + goType, function(name, prop) {\n// prop parameter are `undefined` here\n})\n
  • Wait all game objects are destroyed : [wait=goType]
    • Also fire event 'wait.' + goType
      txt.on('wait.' + goType, function(name, prop) {\n// name and prop parameter are `undefined` here\n})\n
  • Wait boolean data in game object's data manager set to true/false : [wait=goType.name.dataKey]/[wait=goType.name.!dataKey]
    • Also fire event 'wait.' + goType
      txt.on('wait.' + goType, function(name, prop) {\n})\n
"},{"location":"textplayer/#typing-content","title":"Typing content","text":"
txt.play(content);\n

or

txt.playPromise(content)\n.then(function(){\n// Typing content complete\n})\n
"},{"location":"textplayer/#show-current-page","title":"Show current page","text":"
txt.showPage();\n
  • Set typing speed to 0.
  • Set animation progress to 1.
  • Skip all waiting events.
  • Stop current sound effects, and ignore remainder sound effects.
"},{"location":"textplayer/#typing-next-page","title":"Typing next page","text":"
txt.typingNextPage();\n
  • Set nextPageInput to null, or false in config.
"},{"location":"textplayer/#ignore-next-page-input","title":"Ignore next page input","text":"
  • Ignore next page input
    txt.setIgnoreNextPageInput();\n
  • Rollback waiting next page input
    txt.setIgnoreNextPageInput(false);\n
"},{"location":"textplayer/#pause","title":"Pause","text":"
  • Pause typing
    txt.pauseTyping();\n
  • Pause typing and typing animation
    txt.pause();\n
"},{"location":"textplayer/#resume","title":"Resume","text":"
  • Resume typing
    txt.resumeTyping();\n
  • Resume typing and typing animation
    txt.resume();\n
"},{"location":"textplayer/#typing-speed","title":"Typing speed","text":"
  • Get
    • Default typing speed
      var speed = txt.defaultTypingSpeed;\n
    • Current typing speed
      var speed = txt.typingSpeed;\n
  • Set
    • Default typing speed
      txt.setDefaultTypingSpeed(speed);\n
      txt.defaultTypingSpeed = speed;\n
    • Current typing speed
      txt.setTypingSpeed(speed);\n// txt.setTypingSpeed();    // Set speed to default speed\n
      txt.typingSpeed = speed;\n
"},{"location":"textplayer/#time-scale","title":"Time scale","text":"

Time scale of typing, typing animation, sprite animation and easing of sprite's properties.

  • Get
    var timeScale = txt.timeScale;\n
  • Set
    txt.setTimeScale(timeScale);    
    txt.timeScale = timeScale;\n
"},{"location":"textplayer/#status","title":"Status","text":"
  • Is playing : After txt.play(content), before typing all pages completed
    var isPlaying = txt.isPlaying\n
  • Is page typing : After txt.play(content), or txt.typingNextPage(), before page typing completed
    var isPageTyping = txt.isPageTYyping;\n
"},{"location":"textplayer/#events","title":"Events","text":"
  • On typing content complete
    txt.on('complete', function() {\n\n})\n
  • On typing a character or an image
    txt.on('typing', function(child) {\nif (child.type === 'text') {\nvar character = child.text;\n} else {\nvar textureLey = child.key;\nvar frameKey = child.frame;\n}\n})\n
  • On typing a page start
    txt.on('page.start', function() {\n\n})\n
  • On typing a page complete
    txt.on('page.complete', function() {\n\n})\n
"},{"location":"textplayer/#tags-of-content","title":"Tags of content","text":""},{"location":"textplayer/#content","title":"Content","text":"

These lines will be skipped :

  • Empty line, which only has space characters.
  • Comment line, start with '//'.

New line symbol '\\n' will be removed, use [r] to insert a new line character.

"},{"location":"textplayer/#content-output-switch","title":"Content output switch","text":"
  • Turn off content output : [content.off]
  • Turn on content output : [content.on]
"},{"location":"textplayer/#content-output-enable","title":"Content output enable","text":"
  • Content won't output if parser.setContentOutputEnable(false) under custom tag events
    • Fire 'parser.+custom#content' event if conent is ignored now
      txt.on('parser.+custom#content', function(parser, content) {\n\n})\n
  • Invoke parser.setContentOutputEnable() to turn on content output back.
"},{"location":"textplayer/#text-style","title":"Text style","text":"
  • Font color : [color=red]content[/color], [color=#FF0000]content[/color]
  • Font size : [size=24]content[/size]
  • Bold : [b]content[/b]
  • Italic : [i]content[/i]
  • Stroke : [stroke]content[/stroke], [stroke=red]content[/stroke]
    • strokeThickness is set in config
  • Shadow : [shadow]content[/shadow], [shadow=red]content[/shadow]
    • shadowOffsetX, shadowOffsetY, shadowBlur are set in config
  • Character offset Y : [y=-8]c[/y]ontent
  • Character offset X : [x=10]c[/x]ontent
  • Left space : [left=10]c[/left]ontent
  • Right space : conten[right=10]t[/right]
  • Line-align : [align=left], [align=center], [align=right]
"},{"location":"textplayer/#new-line","title":"New line","text":"
  • New line : [r]
    • New line via \\n will be ignored.
"},{"location":"textplayer/#page-break","title":"Page break","text":"
  • [pagebreak], or [pb] : Put remainder characters to next page.
"},{"location":"textplayer/#image","title":"Image","text":"

[img=key]

"},{"location":"textplayer/#render-size","title":"Render size","text":"
  • Set render size in config
    {\nimages: {\n// key: {width, height},\n// key: {key, frame, width, height, tintFill: false}\n}\n}\n
    • tintFill :
      • false : Keep original color. Default behavior.
      • true : Change fill-color by color tag. [color=...][img=...].
  • Set render size by method
    txt.addImage({\n// key: {width, height},\n// key: {key, frame, width, height, tintFill: false}\n})\n
  • Use origin render size by default
"},{"location":"textplayer/#space","title":"Space","text":"

[space=width]

"},{"location":"textplayer/#typing-speed_1","title":"Typing speed","text":"
  • No typing : [speed=0]
  • Set speed : [speed=1000]
  • Back to default speed : [/speed]
"},{"location":"textplayer/#sprite","title":"Sprite","text":"
  • Add sprite : [sprite.name=textureKey,frameKey]
    • Tint-fade-in if sprite.fade is not 0
  • Remove sprite : [/sprite.name]
    • Tint-fade-out if sprite.fade is not 0
  • Remove all sprites : [/sprite]
    • Tint-fade-out if sprite.fade is not 0
  • Call method : [sprite.name.methodName=value0,value1,value2]
  • Set property : [sprite.name.x=value], [sprite.name.alpha=value], ....
  • Ease property :
    [sprite.name.x.to=value,duration]\n
    [sprite.name.x.to=value,duration,repeat]\n
    [sprite.name.x.to=value,duration,easeFunction,repeat]\n
    [sprite.name.x.to=value]\n
    • duration : Default value is 1000
    • easeFunction : Default value is 'Linear'
    • repeat : Default value is 0
  • Yoyo ease property :
    [sprite.name.x.yoyo=value,duration]\n
    [sprite.name.x.yoyo=value,duration,repeat]\n
    [sprite.name.x.yoyo=value,duration,easeFunction,repeat]\n
    [sprite.name.x.yoyo=value]\n
  • Set texture : [sprite.name.texture=textureKey,frameKey]
  • Play animation : [sprite.name.play=animationKey], or [sprite.name.play=animationKey0,animationKey1,...]
    • Can play animation without adding sprite first.
  • Stop animation : [/sprite.name.play], or [sprite.name.stop]
  • Pause animation : [sprite.name.pause]
"},{"location":"textplayer/#sound-effect","title":"Sound effect","text":"
  • Play : [se=key], [se2=key]
    • Sound effect will be destroyed when complete
  • Play with fade in volume : [se=key,1000], [se2=key,1000]
  • Fade in volume : [se.fadein=1000], [se2.fadein=1000]
  • Fade out volume : [se.fadeout=1000], [se2.fadeout=1000]
  • Fade out volume then stop : [se.fadeout=1000,stop], [se2.fadeout=1000,stop]
  • Set volume : [se.volume=1], [se2.volume=1]
"},{"location":"textplayer/#background-music","title":"Background music","text":"
  • Play, stop : [bgm=key], [/bgm], [bgm2=key],[/bgm2]`
    • Previous background music will be stopped and destroyed.
    • Cross fade to next background music if sounds.bgm.fade/sounds.bgm2.fade is not 0
  • Play with fade in volume : [bgm=key,1000], [bgm2=key,1000]
  • Pause, resume : [bgm.pause], [/bgm.pause], [bgm2.pause], [/bgm2.pause]
  • Fade in volume : [bgm.fadein=1000], [bgm2.fadein=1000]
  • Fade out volume : [bgm.fadeout=1000], [bgm2.fadeout=1000]
  • Fade out volume then stop : [bgm.fadeout=1000,stop], [bgm2.fadeout=1000,stop]
  • Cross fade to another background music : [bgm.cross=key,10000], [bgm2.cross=key,10000]
  • Set volume : [bgm.volume=1], [bgm2.volume=1]
  • Mute : [bgm.mute], [bgm2.mute], [bgm.unmute], [bgm2.unmute]
"},{"location":"textplayer/#camera","title":"Camera","text":"
  • Fade-in effect : [camera.fadein], [camera.fadein=1000], or [camera.fadein=duration,red,green,blue]
  • Fade-out effect : [camera.fadeout], [camera.fadeout=1000], or [camera.fadeout=duration,red,green,blue]
  • Flash effect : [camera.flash], [camera.flash=1000], or [camera.flash=duration,red,green,blue]
  • Shake effect : [camera.shake], [camera.shake=1000], or [camera.shake=duration,intensity]
  • Zoom
    • Set zoom : [camera.zoom=2]
    • Zoom to : [camera.zoom.to=1,1000], or [camera.zoom.to=zoomValue,duration,Cubic]
  • Rotate
    • Set angle : [camera.rotate=90], angle in degrees
    • Rotate to : [camera.rotate.to=0,1000], or [camera.rotate.to=deg,duration,Cubic], angle in degrees
  • Scroll
    • Scroll x,y : [camera.scroll=0,200]
    • Scroll x,y to : [camera.scroll.to=0,200,1000], or [camera.rotate.to=x,y,duration,Cubic]
"},{"location":"textplayer/#wait-conditions","title":"Wait conditions","text":"
  • Wait click : [wait=click], [click]
    • Also fire event 'wait.click'
       txt.on('wait.click', function() {\n})\n
  • Wait key-down : [wait=enter], [wait=space], ....
    • Also fire event 'wait.keydown'
       txt.on('wait.keydown', function(keyName) {\n})\n
  • Wait time : [wait=1000]
    • Also fire event 'wait.time'
       txt.on('wait.time', function(time) {\n})\n
  • Wait sound effect : [wait=se], [wait=se2]
    • Also fire event 'wait.music'
       txt.on('wait.music', function(music) {\n// var key = music.key;\n})\n
  • Wait background music : [wait=bgm], [wait=bgm2]
    • Also fire event 'wait.music'
       txt.on('wait.music', function(music) {\n// var key = music.key;\n})\n
  • Wait camera effect : [wait=camera.fadein], [wait=camera.fadeout], [wait=camera.flash], [wait=camera.shake], [wait=camera.zoom], [wait=camera.rotate], [wait=camera.scroll]
    • Also fire event 'wait.camera'
       txt.on('wait.camera', function(effectName) {\n// effectName : 'camera.fadein', 'camera.fadeout', 'camera.flash', 'camera.shake', 'camera.zoom', 'camera.rotate', 'camera.scroll'\n})\n
  • Wait ease task of sprite's property : [wait=sprite.name.prop]
    • Also fire event 'wait.sprite'
       txt.on('wait.sprite', function(name, prop) {\n})\n
  • Wait all sprites are destroyed : [wait=sprite]
    • Also fire event 'wait.sprite'
       txt.on('wait.sprite', function(name, prop) {\n// name and prop parameter are `undefined` here\n})\n
  • Wait callback : [wait], or [wait=xxx] (xxx is any string which not been used in above case)
    • Fire event 'wait'
      txt.on('wait', function(callback) {\n// Invoke `callback()` to continue typing\n})\n
    • Fire event 'wait.xxx'
      txt.on('wait.xxx', function(callback) {\n// Invoke `callback()` to continue typing\n})\n
  • Combine conditions : [wait=cond0|cond1|...]
    • Wait click, or enter key down : [wait=click|enter]
    • Wait click, enter key down, or 100ms : [wait=click|enter|1000]
"},{"location":"textplayer/#custom-tag","title":"Custom tag","text":"

Assume that adding a custom tag : [custom=10,20][/custom].

+custom parses the open tag [custom=10,20] and -custom parses the closing tag [/custom]

  • On parse a +custom tag, will add a custom command child
    txt.on('parser.+custom', function(parser, a, b, params) {\n// console.log('Parse +custom tag:', a, b)\n})\n
    • parses opening tag
    • a, b, ... : Parameters after =
    • params : Arguments array used when executing +custom. Equal to [a, b] in this case.
    • Disable content after this start tag
      parser.setContentOutputEnable(false);\n
  • On execute a +custom command child
    txt.on('tag.+custom', function(a, b) {\n// console.log('Execute +custom tag:', a, b)\n})\n
    • a, b, ... : Parameters passed from params in 'parser.+custom' event.
  • On parse a -custom tag, will add a custom command child
    txt.on('parser.-custom', function(parser, params) {\n// console.log('Parse -custom tag')\n})\n
    • parses closing tag
    • params : Arguments array used when executing -custom. Equal to [] in this case.
    • Enable content after this start tag
      parser.setContentOutputEnable(true);\n
  • On execute a -custom command child
    txt.on('tag.-custom', function(...params) {\n// console.log('Execute -custom tag')\n})\n
    • params : Parameters passed from params in 'parser.-custom' event.
"},{"location":"textplayer/#size","title":"Size","text":"
  • Resize canvas size
    txt.setCanvasSize(width, height)\n
  • Reisze text wrapping size and canvas size.
    txt.setSize(width, height);\n
    or
    txt.setFixedSize(width, height);\n
  • Resize to minimun size to show all visible characters.
    txt.setToMinSize();\n
"},{"location":"textplayer/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"textplayer/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"textplayer/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"texttranslation/","title":"Translation","text":""},{"location":"texttranslation/#introduction","title":"Introduction","text":"

Apply translated string (i18next) to text object, bbcode text object, tag text object, bitmap text object, or label game object

  • Author: Rex
  • Behavior of text object
"},{"location":"texttranslation/#live-demos","title":"Live demos","text":"
  • Inline resources
  • External resources
  • External yaml resource
"},{"location":"texttranslation/#usage","title":"Usage","text":"

Sample code

"},{"location":"texttranslation/#install-plugin","title":"Install plugin","text":""},{"location":"texttranslation/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in scene's config
    class Demo extends Phaser.Scene {\nconstructor() {\nsuper({\nkey: 'Scnee',\npack: {\nfiles: [{\ntype: 'plugin',\nkey: 'rextexttranslationplugin',\nurl: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextexttranslationplugin.min.js',\nstart: true,\nmapping: 'translation'  // Add text-translation plugin to `scene.translation`\n}]\n},\n// ...\n});\n}\n// ...\n}\n
  • Initialize i18next during preload stage
    scene.plugins.get('rextexttranslationplugin').initI18Next(scene, {\nlng: 'dev',\nfallbackLng: 'dev',\nns: 'translation',\n\n// resources: {\n//     'dev': {\n//         'translation': {\n//             key: value,  \n//         }\n//     }\n// }\n\n// debug: true,\n\n// backend: {\n//     loadPath: '',\n//     parse: function(data) { return JSON.parse(data); }\n// },\n})\n
  • Add translation behavior
    var translation = scene.plugins.get('rextexttranslationplugin').add(textGameObject, config);\n
"},{"location":"texttranslation/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TextTranslationPlugin from 'phaser3-rex-plugins/plugins/texttranslation-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTextTranslation',\nplugin: TextTranslationPlugin,\nstart: true,\nmapping: 'translation'  // Add text-translation plugin to `scene.translation`\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize i18next during preload stage
    scene.plugins.get('rexTextTranslation').initI18Next(scene, {\nlng: 'dev',\nfallbackLng: 'dev',\nns: 'translation',\n\n// resources: {\n//     'dev': {\n//         'translation': {\n//             key: value,  \n//         }\n//     }\n// }\n\n// debug: true,\n\n// backend: {\n//     loadPath: '',\n//     parse: function(data) { return JSON.parse(data); }\n// },\n})\n
  • Add translation behavior
    var translation = scene.plugins.get('rexTextTranslation').add(textGameObject, config);\n
"},{"location":"texttranslation/#import-class","title":"Import class","text":"
  • Install rex plugins, i18next, i18next-http-backend from npm
    npm i phaser3-rex-plugins\nnpm i i18next\nnpm i i18next-http-backend\n
  • Import class
    import TextTranslationBehavior from 'phaser3-rex-plugins/plugins/texttranslation.js';\nimport i18next from 'i18next';\nimport Backend from 'i18next-http-backend';\nimport Awaitloader from 'phaser3-rex-plugins/plugins/awaitloader.js';\n
  • Initialize i18next during preload stage
    Awaitloader.call(scene.load, function (successCallback, failureCallback) {\ni18next\n.use(Backend)\n.init({\nlng: 'dev',\nfallbackLng: 'dev',\nns: 'translation',\n\n// resources: {\n//     'dev': {\n//         'translation': {\n//             key: value,  \n//         }\n//     }\n// }\n\n// debug: true,\n\n// backend: {\n//     loadPath: '',\n//     parse: function(data) { return JSON.parse(data); }\n// },\n}, successCallback);\n})\nTextTranslationBehavior.setI18Next(i18next);\n
    • Awaitloader : Using Awaitloader to load external resource.
    • Backend : i18next-http-backend module can be used to load external resource.
    • TextTranslationBehavior.setI18Next(i18next) : Pass i18next to TextTranslationBehavior.
      • TextTranslationBehavior.setI18Next is a static method.
  • Add translation behavior
    var translation = new TextTranslationBehavior(textGameObject, config);\n
"},{"location":"texttranslation/#initialize-i18next","title":"Initialize i18next","text":"
scene.plugins.get('rexTextTranslation').initI18Next(scene, {\nlng: 'dev',\nfallbackLng: 'dev',\nns: 'translation',\n\n// resources: {\n//     'dev': {\n//         'translation': {\n//             key: value,  \n//         }\n//     }\n// }\n\n// debug: true,\n\n// backend: {\n//     loadPath: '',\n//     parse: function(data) { return JSON.parse(data); }\n// },\n})\n

or

i18next\n.use(Backend)\n.init(config, onComplete);\n
  • lng : Language to use. Will fallback to 'dev'.
  • fallbackLng : Language to use if translations in user language are not available. Setting it explicitly to false will not trigger to load the fallbackLng at all.
  • ns : String or array of namespaces to load. Default value is 'translation'.
  • debug : Logs info level to console output. Helps finding issues with loading not working. Default value is false.
  • resources : Resources to initialize with.
  • backend.loadPath : Path where resources get loaded from, or a function returning a path.
    function(lngs, namespaces) { return customPath; }\n
  • backend.parse : Parse data after it has been fetched. Optional.
    function(data) { return JSON.parse(data); }\n

See also Configuration Options, and Backend Options

"},{"location":"texttranslation/#create-instance","title":"Create instance","text":"
var translation = scene.plugins.get('rexTextTranslation').add(textGameObject, {\n// translationKey: '',\n// interpolation: {},\n\n// updateText: true,\n\n// setText: function(gameObject, text) { \n//     gameObject.setText(text); \n// }\n});\n
  • textObject : text object, bbcode text object, tag text object, bitmap text object, or label game object
  • translationKey : Key in translation resource. See Essentials
  • interpolation : Integrating dynamic values into translation result. See Interpolation
  • updateText :
    • true : Update text object via translationKey, and interpolation. Default behavior.
    • false : Don't update text object now.
  • setText : Callback invoked when updating text object. Default value is
    function(gameObject, text) {\ngameObject.setText(text);\n}\n
"},{"location":"texttranslation/#set-translation-key","title":"Set translation key","text":"
translation\n.setTranslationKey(key)\n.updateText()\n
"},{"location":"texttranslation/#set-interpolation","title":"Set interpolation","text":"
  • Assign interpolation object
    translation\n.setInterpolation(object)\n.updateText()\n
  • Update current interpolation object
    translation\n.updateInterpolation(key, value)\n.updateText()\n
    or
    translation\n.updateInterpolation(object)\n.updateText()\n
"},{"location":"texttranslation/#update-text","title":"Update text","text":"

Update text object via translationKey, and interpolation.

translation.updateText()\n
"},{"location":"texttranslation/#change-language","title":"Change language","text":"
scene.plugins.get('rexTextTranslation').changeLanguage(language);\n// scene.plugins.get('rexTextTranslation').changeLanguage(language, onComplete);\n

or

i18next.changeLanguage(language, onComplete);\n

All translation behavior will update text object after changing language.

"},{"location":"texttranslation/#set-default-namespace","title":"Set default namespace","text":"
scene.plugins.get('rexTextTranslation').setDefaultNamespace(namespace);\n

or

i18next.setDefaultNamespace(namespace);\n
"},{"location":"texttranslation/#translate-string","title":"Translate string","text":"
var result = scene.plugins.get('rexTextTranslation').t(translationKey, interpolation);\n

or

var result = i18next.t(translationKey, interpolation);\n
"},{"location":"texttranslation/#events","title":"Events","text":"
  • On language changed, triggered by changeLanguage method.
    scene.plugins.get('rexTextTranslation').on('languageChanged', function (lng) {\n});\n
    or
    i18next.on('languageChanged', function (lng) {\n});\n
"},{"location":"texttruncator/","title":"Truncator","text":""},{"location":"texttruncator/#introduction","title":"Introduction","text":"

Constraints text game object size by truncating text with padding symbol on text object, bbcode text object, or tag text object.

  • Author: Rex
  • Behavior of text object
"},{"location":"texttruncator/#live-demos","title":"Live demos","text":"
  • Truncate text
  • Truncate BBCodeText
"},{"location":"texttruncator/#usage","title":"Usage","text":"

Sample code

"},{"location":"texttruncator/#install-plugin","title":"Install plugin","text":""},{"location":"texttruncator/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextexttruncatorplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextexttruncatorplugin.min.js', true);\n
  • Add text-truncator behavior
    var truncator = scene.plugins.get('rextexttruncatorplugin').add(textGameObject, config);\n
"},{"location":"texttruncator/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TextTruncatorPlugin from 'phaser3-rex-plugins/plugins/texttruncator-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTextTruncator',\nplugin: TextTruncatorPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text-truncator behavior
    var truncator = scene.plugins.get('rexTextTruncator').add(textGameObject, config);\n
"},{"location":"texttruncator/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TextTruncator from 'phaser3-rex-plugins/plugins/texttruncator.js';\n
  • Add text-truncator behavior
    var truncator = new TextTruncator(textGameObject, config);\n
"},{"location":"texttruncator/#create-instance","title":"Create instance","text":"
var truncator = scene.plugins.get('rexTextTruncator').add(textGameObject, {\n// enable: true,\n// symbol: '...',\n// maxWidth: undefined,\n// maxHeight: undefined,\n// text: '',              // content in string or array\n});\n
  • textObject : Text object, bbcode text object, tag text object, or bitmap text object
  • enable :
    • true : Truncate string with padding symbol. Default value.
    • false : Display all text.
  • symbol : Padding symbol. Default value is '...'
  • maxWidth : Maximum width of game object, for single-line mode.
    • undefined : Use fixedWidth as maximum width.
  • maxHeight : Maximum height of game object, for multiple-line mode.
    • undefined : Use fixedHeight as maximum height.
  • text : content in string or array, optional
"},{"location":"texttruncator/#truncation-modes","title":"Truncation modes","text":"
  • Single-line mode :
    • maxHeight or fixedHeight are not given, or 0
    • Have maxWidth or fixedWidth
  • Multiple-line mode
    • Have fixedWidth or wordWrap.width (wrap-width)
    • Have maxHeight or fixedHeight
"},{"location":"texttruncator/#set-content","title":"Set content","text":"
  • Set content
    truncator.setText(content);\n
    • content : String, number, or string array.
  • Append content
    truncator.appendText(content);\n
    • content : String, number, or string array.

Will update displaying content.

  • Get content back
    var text = truncator.text;\n
"},{"location":"texttruncator/#update-display-content","title":"Update display content","text":"
truncator.updateText();\n
"},{"location":"texttruncator/#set-enable","title":"Set enable","text":"
truncator.setEnable(enable).updateText();\n
"},{"location":"texttruncator/#set-paddding-symbol","title":"Set paddding symbol","text":"
truncator.setSymbol(symbol).updateText();\n
"},{"location":"texttruncator/#set-max-size","title":"Set max size","text":"
  • Max width
    • Set
      truncator.setMaxWidth(width).updateText();\n
    • Get
      var width = truncator.maxWidth;\n
  • Max height
    • Set
      truncator.setMaxHeight(height).updateText();\n
    • Get
      var height = truncator.maxHeight;\n
"},{"location":"texttyping/","title":"Typing","text":""},{"location":"texttyping/#introduction","title":"Introduction","text":"

Typing text on text object, bbcode text object, or tag text object.

  • Author: Rex
  • Behavior of text object
"},{"location":"texttyping/#live-demos","title":"Live demos","text":"
  • BBCode text + page + typing
  • Text wrap enable
  • TextBox, see text-box.
"},{"location":"texttyping/#usage","title":"Usage","text":"

Sample code

"},{"location":"texttyping/#install-plugin","title":"Install plugin","text":""},{"location":"texttyping/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextexttypingplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextexttypingplugin.min.js', true);\n
  • Add typing behavior
    var typing = scene.plugins.get('rextexttypingplugin').add(textGameObject, config);\n
"},{"location":"texttyping/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TextTypingPlugin from 'phaser3-rex-plugins/plugins/texttyping-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTextTyping',\nplugin: TextTypingPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add typing behavior
    var typing = scene.plugins.get('rexTextTyping').add(textGameObject, config);\n
"},{"location":"texttyping/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TextTyping from 'phaser3-rex-plugins/plugins/texttyping.js';\n
  • Add typing behavior
    var typing = new TextTyping(textGameObject, config);\n
"},{"location":"texttyping/#create-instance","title":"Create instance","text":"
var typing = scene.plugins.get('rexTextTyping').add(textGameObject, {\n// wrap: false,\n// speed: 333,       // typing speed in ms\n// typeMode: 0,      //0|'left-to-right'|1|'right-to-left'|2|'middle-to-sides'|3|'sides-to-middle'\n// setTextCallback: function(text, isLastChar, insertIdx){ return text; }  // callback before set-text\n// setTextCallbackScope: null,   \n});\n
  • textObject : Text object, bbcode text object, tag text object, or bitmap text object
  • wrap :
    • false : Don't insert \\n, default behavior.
    • true : Insert \\n to wrap content according to style of text, to prevent typing jittering.
  • speed : Typing speed in ms, default value is 333.
  • typeMode :
    • 'left-to-right', or 0 : Typing characters from left to right.
    • 'right-to-left', or 1 : Typing characters from right to left.
    • 'middle-to-sides', or 2 : Typing characters from middle to sides.
    • 'sides-to-middle', or 3 : Typing characters from sides to middle.
  • setTextCallback : Callback befor set-text, to decorate display text.
    function(text, isLastChar, insertIdx) { return text; }\n
  • setTextCallbackScope : Scope of setTextCallback function.
"},{"location":"texttyping/#start-typing","title":"Start typing","text":"
typing.start(text);\n// typing.start(text, speed); \n
  • text : Typing content string.
  • speed : Typing speed in ms.
"},{"location":"texttyping/#start-typing-from-line","title":"Start typing from line","text":"
typing.startFromLine(text, lineIndex);\n// typing.startFromLine(text, lineIndex, speed);\n
  • text : Typing content string.
  • lineIndex : Start from line.
  • speed : Typing speed in ms.
"},{"location":"texttyping/#typing-more-text","title":"Typing more text","text":"
typing.appendText(text);\n
"},{"location":"texttyping/#stop-typing","title":"Stop typing","text":"
typing.stop();\n// typing.stop(true);;  // stop and show all text\n
"},{"location":"texttyping/#pauseresume-typing","title":"Pause/Resume typing","text":"
  • Pause typing
    typing.pause();\n
  • Resume typing
    typing.resume();\n
"},{"location":"texttyping/#set-typing-speed","title":"Set typing speed","text":"
typing.setTypingSpeed(speed);  // speed in ms\n// typing.speed = speed;\n

Set speed in typing event or setTextCallback to change typing speed of remaining text.

"},{"location":"texttyping/#set-typing-mode","title":"Set typing mode","text":"
typing.setTypeMode(mode);\n
  • typeMode :
    • 'left-to-right', or 0 : typing characters from left to right.
    • 'right-to-left', or 1 : typing characters from right to left.
    • 'middle-to-sides', or 2 : typing characters from middle to sides, optional.
    • 'sides-to-middle', or 3 : typing characters from sides to middle.
"},{"location":"texttyping/#events","title":"Events","text":"
  • On changing content of text game object :
    typing.on('type', function(){\n\n});\n
  • On typing a character
    typing.on('typechar', function(char){\n\n});\n
  • On typing completed :
    typing.on('complete', function(typing, txt){});\n
"},{"location":"texttyping/#status","title":"Status","text":"
  • Is typing
    var isTyping = typing.isTyping;\n
"},{"location":"textures/","title":"Textures","text":""},{"location":"textures/#introduction","title":"Introduction","text":"

Textures cache, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"textures/#usage","title":"Usage","text":""},{"location":"textures/#image-texture","title":"Image texture","text":"
  • Load image texture
    scene.load.image(key, url);\n
    Reference: Loader
  • Load image texture via base64 string
    scene.textures.addBase64(key, data)\n
  • Get image texture
    var texture = scene.textures.get(key);\nvar image = texture.getSourceImage();\n// var width = image.width;\n// var height = image.height;\n
  • Get image texture from frame object
    var texture = scene.textures.get(frameObject);\n
"},{"location":"textures/#get-pixel","title":"Get pixel","text":"
var color = scene.textures.getPixel(x, y, key);\n// var color = scene.textures.getPixel(x, y, key, frame);\n

Properties of color

  • r : 0 ~ 255
  • g : 0 ~ 255
  • b : 0 ~ 255
  • a : 0 ~ 255
  • color : color integer
var alpha = scene.textures.getPixelAlpha(x, y, key);\n// var alpha = scene.textures.getPixelAlpha(x, y, key, frame);\n

alpha : 0 ~ 255

Return null if the coordinates were out of bounds.

"},{"location":"textures/#generate-texture-from-array","title":"Generate texture from array","text":"
var config = {\ndata: data,\n// 3x3:\n// [ '...',\n//   '...',\n//   '...' ]\npixelWidth: 1,    // pixel width of each data\npixelHeight: 1,   // pixel height of each data\npreRender: null,  // callback, function(canvas, ctx) {}\npostRender: null, // callback, function(canvas, ctx) {}\n\ncanvas: null,  // create a canvas if null\nresizeCanvas: true,\nclearCanvas: true\n};\nvar texture = scene.textures.generate(key, config);\n
"},{"location":"textures/#has-key","title":"Has key","text":"
var hasKey = scene.textures.exists(key);\n
"},{"location":"textures/#remove-texture","title":"Remove texture","text":"

Remove texture stored in texture cache.

scene.textures.remove(key);\n
"},{"location":"textures/#get-base64","title":"Get base64","text":"
var s = scene.textures.getBase64(key);  // type= 'image/png', encoderOptions= 0.92\n// var s = scene.textures.getBase64(key, frame, type, encoderOptions);\n
"},{"location":"textures/#default-textures","title":"Default textures","text":"
  • Default : '__DEFAULT'
  • Missing : '__MISSING'
  • 4x4 white : '__WHITE'
"},{"location":"textures/#get-key-list-of-all-textures","title":"Get key list of all textures","text":"
var keys = scene.textures.getTextureKeys();\n
"},{"location":"textures/#texture","title":"Texture","text":""},{"location":"textures/#get-texture","title":"Get texture","text":"
var texture = scene.textures.get(key);\n
"},{"location":"textures/#has-frame","title":"Has frame","text":"
var hasFrame = texture.has(frameName);\n
"},{"location":"textures/#add-frame","title":"Add frame","text":"
var frame = texture.add(frameName, sourceIndex, x, y, width, height);\n
  • key : Texture key.
  • frameName : The name of this Frame. The name is unique within the Texture.
  • sourceIndex : The index of the TextureSource that this Frame is a part of.
  • x, y : The x/y coordinate of the top-left of this Frame.
  • width, height : The width/height of this Frame.
"},{"location":"textures/#remove-frame","title":"Remove frame","text":"
var removed = texture.remove(frameName);\n
"},{"location":"textures/#get-name-of-frames","title":"Get name of frames","text":"
var nameList = texture.getFrameNames();\n// nameList does not include `__BASE`\n

or

var nameList = texture.getFrameNames(true);\n// nameList includes `__BASE`\n
"},{"location":"textures/#frame-object","title":"Frame object","text":""},{"location":"textures/#get-frame","title":"Get frame","text":"
var frame = scene.textures.getFrame(key, frame);\n
"},{"location":"textures/#properties","title":"Properties","text":"
  • frame.source.image : Image of texture source.
  • frame.cutX : X position within the source image to cut from.
  • frame.cutY : Y position within the source image to cut from.
  • frame.cutWidth : The width of the area in the source image to cut.
  • frame.cutHeight : The height of the area in the source image to cut.
"},{"location":"textures/#add-atlas","title":"Add atlas","text":"
scene.textures.addAtlas(key, HTMLImageElement, data);\n// scene.textures.addAtlas(key, HTMLImageElement, data, dataSource);\n
  • key : The unique string-based key of the Texture.
  • HTMLImageElement : HTML Image element/s.
  • data : The Texture Atlas data/s.
    {\nframes: [\n{\n// Location of frame image\nframe: {\nx, y, w, h\n},\n\n// trimmed\ntrimmed:\nsourceSize: {\nw, h\n},\nspriteSourceSize: {\nx, y, w, h\n},\n\nrotated:\n\n// Custom origin\nanchor: pivot: {\nx, y\n},\n\n// Other custom properties of this frame ...\n}\n],\n\n// Other custom properties of this texture ...\n}\n
  • dataSource : An optional data Image element (normal map).

or

scene.textures.addAtlas(undefined, texture, data);\n// scene.textures.addAtlas(undefined, texture, data, dataSource);\n
  • texture : Phaser Texture.
"},{"location":"textures/#add-sprite-sheet","title":"Add sprite sheet","text":"
scene.textures.addSpriteSheet(key, HTMLImageElement, config);\n// scene.textures.addAtlas(key, HTMLImageElement, config, dataSource);\n
  • key : The unique string-based key of the Texture.
  • HTMLImageElement : HTML Image element/s.
  • config : The configuration object for this Sprite Sheet.
    {\nframeWidth: ,\nframeHeight: ,\nstartFrame: 0,\nendFrame: -1,\nmargin: 0,\nspacing: 0\n}\n
  • dataSource : An optional data Image element (normal map).

or

scene.textures.addSpriteSheet(undefined, texture, config);\n// scene.textures.addSpriteSheet(undefined, texture, config, dataSource);\n
  • texture : Phaser Texture.
"},{"location":"textures/#events","title":"Events","text":"
  • Texture manager is ready
    scene.textures.on('ready', function() {\n\n})\n
  • Add texture
    scene.textures.on('addtexture', function(key) {\n\n})\n
    or
    scene.textures.on('addtexture-' + key, function() {\n\n})\n
  • Error when adding texture
    scene.textures.on('onerror', function(key) {\n\n})\n
  • Remove texture
    scene.textures.on('removetexture', function(key) {\n\n})\n
    or
    scene.textures.on('removetexture-' + key, function() {\n\n})\n
"},{"location":"tiledmapdata/","title":"Tiled map data","text":""},{"location":"tiledmapdata/#introduction","title":"Introduction","text":"

Parses a Tiled JSON object into a new MapData object.

  • Author: Richard Davey
"},{"location":"tiledmapdata/#usage","title":"Usage","text":"
var mapData = Phaser.Tilemaps.Parsers.Tiled.ParseJSONTiled(name, json, insertNull);\n
  • name : The name of the tilemap, used to set the name on the MapData.
  • json : The Tiled JSON object.
  • insertNull : Controls how empty tiles, tiles with an index of -1.
    • true : Empty locations will get a value of null.
    • false : Empty location will get a Tile object with an index of -1.
"},{"location":"tiledmapdata/#map-data","title":"Map data","text":""},{"location":"tiledmapdata/#map-type","title":"Map type","text":"
var mapType = mapData.orientation;\n
  • mapType : orthogonal, isometric, hexagonal
"},{"location":"tiledmapdata/#map-size","title":"Map size","text":"
  • Grid size
    var mapWidth = mapData.width;\nvar mapHeight = mapData.height;\n
  • Pixel size
    var mapWidth = mapData.widthInPixels;\nvar mapHeight = mapData.heightInPixels;\n
"},{"location":"tiledmapdata/#tile-size","title":"Tile size","text":"
var tileWidth = mapData.tileWidth;\nvar tileHeight = mapData.tileHeight;\n
"},{"location":"tiledmapdata/#layer","title":"Layer","text":"
var layers = mapData.layers;\n
mapData.layers.forEach(function(layer){\nvar name = layer.name;\n\n\nvar alpha = layer.alpha;\nvar visible = layer.visible;\n\nvar x = layer.x;\nvar y = layer.y;\nvar width = layer.width;\nvar height = layer.height;\nvar data = layer.data;\n\nlayer.data.forEach(function(gid, index){\nvar tileX = index % width;\nvar tileY = Math.floor(index / width);\nif (gid === -1) { // Empty\n\n} else {\n\n}\n})\n})\n
"},{"location":"tilemap/","title":"Tile map","text":""},{"location":"tilemap/#introduction","title":"Introduction","text":"

Display of tiles map, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"tilemap/#usage","title":"Usage","text":""},{"location":"tilemap/#hierarchy","title":"Hierarchy","text":"
graph TB\n\ntilemap --> layerA[\"layerA<br>(Game object)\"]\ntilemap --> layerB\n\nlayerA --> tilesA[\"tiles<br>(layer.data[x][y])\"]\nlayerB --> tilesB[\"tiles\"]
  • map : A container for Tilemap data.
  • layer : A Game Object that renders LayerData from a map when used in combination with one or more tileset.
  • tiles : A 2d array of Tile object
    • Tile : A lightweight data representation, store position information without factoring in scroll, layer scale or layer position.
  • tileset : Image and tileData of some kind of tiles.
"},{"location":"tilemap/#load-tile-map","title":"Load tile map","text":"
scene.load.tilemapTiledJSON(key, url);   // JSON\nscene.load.tilemapCSV(key, url);         // CSV\n
"},{"location":"tilemap/#add-tile-map-object","title":"Add tile map object","text":"
  1. Create map
    • Create map from tiled
      var map = scene.add.tilemap(key);\n
      or
      var map = this.make.tilemap({ key: 'map', tileWidth: 16, tileHeight: 16\n});\n
      • Support ORTHOGONAL, ISOMETRIC, STAGGERED, HEXAGONAL map
    • Create map from 2d array
      var map = this.make.tilemap({\n// data: tileIdxArray,  // [ [], [], ... ]\ntileWidth: 32,\ntileHeight: 32,\nwidth: 10,\nheight: 10,\n});\n
      • Only support ORTHOGONAL map
    • Create map from csv
      var map = this.make.tilemap({\nkey: 'map',     // csv file\ntileWidth: 32,\ntileHeight: 32,\n});\n
      • Only support ORTHOGONAL map
  2. Add tileset image
    var tileset = map.addTilesetImage(tilesetName, key); // key: texture key\n// var tileset = map.addTilesetImage(tilesetName);  // key = tilesetName\n// var tileset = map.addTilesetImage(tilesetName, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid, tileOffset);\n
    • key : The key of the Phaser.Cache image used for this tileset.
      • undefined , null : Use tilesetName as default value.
    • tileWidth , tileHeight : The width/height of the tile (in pixels) in the Tileset Image.
      • undefined : Default to the map's tileWidth/tileHeight.
    • tileMargin : The margin around the tiles in the sheet (in pixels).
      • undefined : Default to 0
    • tileSpacing The spacing between each the tile in the sheet (in pixels).
      • undefined : Default to 0
    • gid : If adding multiple tilesets to a blank map, specify the starting GID this set will use here.
    • tileOffset : {x, y} Tile texture drawing offset.
  3. Create layer
    • Create existed layer
      var layer = map.createLayer(layerID, tileset);\n// var layer = map.createLayer(layerID, tileset, x, y);\n
      • tileset : The tileset, or an array of tilesets.
        • A string, or an array of string.
        • A tileset object, or an array of tileset objects.
      • x, y : Offset in pixels. Default is 0/0.
    • Create a new and empty layer
      var layer = map.createBlankLayer(layerID, tileset);\n// var layer = map.createBlankLayer(layerID, tileset, x, y, width, height, tileWidth, tileHeight); // x, y : offset in pixels\n
      • layerID : The name of this layer. Must be unique within the map.
      • tileset : The tileset, or an array of tilesets.
        • A string, or an array of string.
        • A tileset object, or an array of tileset objects.
      • x, y : Offset in pixels. Default is 0/0.
      • width, height : The width/height of the layer in tiles. Default is map.width/map.height.
      • tileWidth, tileHeight : The width/height of the tiles the layer uses for calculations. Default is map's tileWidth/tileHeight.
  4. Create game objects (optional)
    • Create game objects by Object-ID/Object-GID/Object-Name
      var sprites = map.createFromObjects(layerName, {\n// gid: 26,\n// name: 'bonus',\n// id: 9,\n\n// classType: Sprite,\n// ignoreTileset\n// scene,\n// container: null,\n// key: null,\n// frame: null\n}, useTileset);\n
      or
      var sprites = map.createFromObjects(layerName, configArray, useTileset);\n
      • One of filter
        • gid : Object GID.
        • id : Object ID.
        • name : Object Name.
      • classType : Class of game object, default is Sprite.
      • ignoreTileset :
      • scene : A Scene reference, passed to the Game Objects constructors. Default is map's scene.
      • container : Optional Container to which the Game Objects are added.
      • key, frame : Optional key of a Texture to be used.
    • Create game objects by tile
      var sprites = map.createFromTiles(indexes, replacements, spriteConfig);\n// var sprites = map.createFromTiles(indexes, replacements, spriteConfig, scene, camera, layer);\n
      • indexes : The tile index, or array of indexes
      • replacements :
        • null : Leave the tiles unchanged
        • Array of indexes : One-to-one mapping indexes to replacements.
      • spriteConfig : The config object to pass into the Sprite creator (i.e. scene.make.sprite).
        • useSpriteSheet : Set to true to load the tileset as a sprite sheet (not an image), map frame to tile index.
        • Copy rotation, flipX, flipY, alpha, visible and tint properties from Tile to sprites if these properties are not given.
      • scene : The Scene to create the Sprites within.
      • camera : The Camera to use when determining the world XY.
      • layer : The Tilemap Layer to act upon.
"},{"location":"tilemap/#map","title":"Map","text":""},{"location":"tilemap/#map-size","title":"Map size","text":"
var mapWidth = map.width;\nvar mapHeight = map.height;\n
"},{"location":"tilemap/#tile-size","title":"Tile size","text":"
  • Set
    map.setBaseTileSize(tileWidth, tileHeight);\n
  • Get
    var tileWidth = map.tileWidth;\nvar tileHeight = map.tileHeight;\n
"},{"location":"tilemap/#tileworld-position","title":"Tile/world position","text":"
  • World position -> Tile position
    var tileXY = map.worldToTileXY(worldX, worldY);\n// var out = map.worldToTileXY(worldX, worldY, snapToFloor, out, camera, layer);\n
  • Tile position -> World position
    var worldXY = map.tileToWorldXY(tileX, tileY);\n// var out = map.tileToWorldXY(tileX, tileY, out, camera, layer);\n
"},{"location":"tilemap/#tile-at-world-xy","title":"Tile at world XY","text":"
var hasTile = map.hasTileAtWorldXY(worldX, worldY);\n

or

var hasTile = map.hasTileAtWorldXY(worldX, worldY, camera, layer);\n
"},{"location":"tilemap/#draw-on-graphics","title":"Draw on graphics","text":"
map.renderDebug(graphics);\n

or

map.renderDebug(graphics, {\ntileColor: new Phaser.Display.Color(105, 210, 231, 150),         // null\ncollidingTileColor: new Phaser.Display.Color(243, 134, 48, 200), // null\nfaceColor: new Phaser.Display.Color(40, 39, 37, 150)             // null\n});\n

or

map.renderDebug(graphics, styleConfig, layer);\n
  • graphics : Graphics game object.
"},{"location":"tilemap/#layer","title":"Layer","text":"

A Game Object that renders LayerData from a map when used in combination with one or more tileset.

"},{"location":"tilemap/#get-layer","title":"Get layer","text":"
  • Get layer instance
    var layer = map.getLayer(name);\n
  • Set current layer of map
    map.setLayer(layer);  // layer name, layer index\n
    or
    map.layer = layer;\n
"},{"location":"tilemap/#render-pipeline","title":"Render pipeline","text":"
layer.setPipeline(pipelineName);\n
layer.setPostPipeline(pipelineName);\n

See Render pipeline section of Game object.

"},{"location":"tilemap/#render-order","title":"Render order","text":"
layer.setRenderOrder(renderOrder);\n
  • renderOrder
    • 0, or 'right-down'
    • 1, or 'left-down'
    • 2, or 'right-up'
    • 3, or 'left-up'
"},{"location":"tilemap/#fill-tiles","title":"Fill tiles","text":"
  • Fill current layer
    map.fill(index);  // Fill all grids\n
    or
    map.fill(index, tileX, tileY, width, height);\n
  • Fill layer
    layer.fill(index);  // Fill all grids\n
    or
    layer.fill(index, tileX, tileY, width, height);\n
"},{"location":"tilemap/#randomize","title":"Randomize","text":"
  • Randomize current layer
    map.randomize(); // Randomize all grids\n
    or
    map.randomize(tileX, tileY, width, height, indexes);\n
    • indexes An array of tile indexes.
      • -1 : Empty tile.
  • Weight randomize current layer
    map.weightedRandomize(\n{\n{ index: 0, weight: 4 },\n{ index: [0, 1], weight: 4 }\n},\ntileX, tileY, width, height);\n
  • Randomize layer
    layer.randomize();  // Randomize all grids\n
    or
    layer.randomize(tileX, tileY, width, height, indexes);\n
    • indexes An array of tile indexes.
  • Weight randomize layer
    layer.weightedRandomize(\n{\n{ index: 0, weight: 4 },\n{ index: [0, 1], weight: 4 }\n},\ntileX, tileY, width, height);\n
"},{"location":"tilemap/#copy-tiles","title":"Copy tiles","text":"
  • Copy current layer
    map.copy(srcTileX, srcTileY, width, height, destTileX, destTileY);\n
  • Copy layer
    map.copy(srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, layer);\n
    or
    layer.copy(srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces);\n
"},{"location":"tilemap/#put-tile-at","title":"Put tile at","text":"
  • Put on current layer
    map.putTileAt(tile, tileX, tileY);\n
    • tile :
      • Tile index
      • Tile object :
        var tile = map.getTileAt(tileX, tileY);\n
        or
        var tile = map.getTileAtWorldXY(worldX, worldY);\n
  • Put on layer
    map.putTileAt(tile, tileX, tileY, recalculateFaces, layer);\n
    or
    layer.putTileAt(tile, tileX, tileY, recalculateFaces);\n
    • tile : Tile index, or tile object.
"},{"location":"tilemap/#put-tiles-at","title":"Put tiles at","text":"
  • Put on current layer
    map.putTilesAt(tilesArray, tileX, tileY);  // tilesArray: 1d/2d array of Tile object or tile index\n
    • tilesArray : 1d/2d array of tile objects or tile indexes
  • Put on layer
    map.putTilesAt(tilesArray, tileX, tileY, recalculateFaces, layer);\n
    or
    layer.putTilesAt(tilesArray, tileX, tileY, recalculateFaces);\n
    • tilesArray : 1d/2d array of tile objects or tile indexes
"},{"location":"tilemap/#replace-tiles","title":"Replace tiles","text":"
  • Replace on current layer
    map.replaceByIndex(findIndex, newIndex); // Search on all grids\n
    or
    map.replaceByIndex(findIndex, newIndex, tileX, tileY, width, height);\n
  • Replace on layer
    map.replaceByIndex(findIndex, newIndex, tileX, tileY, width, height, layer);\n
    or
    layer.replaceByIndex(findIndex, newIndex, tileX, tileY, width, height);\n
"},{"location":"tilemap/#swap-tiles","title":"Swap tiles","text":"
  • Swap on current layer
    map.swapByIndex(indexA, indexB);\n
    or
    map.swapByIndex(indexA, indexB, tileX, tileY, width, height);\n
  • Swap on layer
    map.swapByIndex(indexA, indexB, tileX, tileY, width, height, layer);\n
    or
    layer.swapByIndex(indexA, indexB, tileX, tileY, width, height);\n
"},{"location":"tilemap/#shuffle-tiles","title":"Shuffle tiles","text":"
  • Shuffle on current layer
    map.shuffle();\n
    or
    map.shuffle(tileX, tileY, width, height);\n
  • Shuffle on layer
    map.shuffle(tileX, tileY, width, height, layer);\n
    or
    layer.shuffle(tileX, tileY, width, height);\n
"},{"location":"tilemap/#shader-effects","title":"Shader effects","text":"

`layer`` support postFX effects

Note

No preFX effect support

"},{"location":"tilemap/#tile","title":"Tile","text":""},{"location":"tilemap/#get-tile","title":"Get tile","text":"
var tile = map.getTileAt(tileX, tileY);\n// var tile = map.getTileAtWorldXY(worldX, worldY);\n

or

var tile = map.getTileAt(tileX, tileY, true, layer);  // Return a Tile object with an index of -1 for empty tile\n// var tile = map.getTileAtWorldXY(worldX, worldY, true, camera, layer);\n
  • layer : The tile layer to use. Default is current layer (map.setLayer(layer))
  • tile : A tile, or null if layer is invalid.
"},{"location":"tilemap/#get-tiles-within-a-rectangle-area","title":"Get tiles within a rectangle area","text":"
var tiles = map.getTilesWithin(tileX, tileY, width, height);\n

or

var tiles = map.getTilesWithin(tileX, tileY, width, height, {\n// isNotEmpty: false,\n// isColliding: false,\n// hasInterestingFace: false\n}, layer);\n
  • tileX , tileY : The left/top most tile index (in tile coordinates) to use as the origin of the area. Default is 0/0.
  • width , height : How many tiles wide/tall from the tileX/tileY index the area will be. Default is map.width/map.height.
  • filteringOptions : Optional filters to apply when getting the tiles.
    • isNotEmpty : If true, only return tiles that don't have -1 for an index.
    • isColliding : If true, only return tiles that collide on at least one side.
    • hasInterestingFace : If true, only return tiles that have at least one interesting face.
  • layer : The tile layer to use. Default is current layer (map.setLayer(layer))
  • tiles : An array of Tiles, or null if layer is invalid.
"},{"location":"tilemap/#get-tiles-within-world-xy","title":"Get tiles within world XY","text":"
var tiles = map.getTilesWithinWorldXY(worldX, worldY, width, height);\n

or

var tiles = map.getTilesWithinWorldXY(worldX, worldY, width, height,  {\n// isNotEmpty: false,\n// isColliding: false,\n// hasInterestingFace: false\n}, camera, layer);\n
  • worldX , worldY : The world x/y coordinate for the top-left of the area.
  • width , height : The width/height of the area. Default is map.width/map.height.
  • filteringOptions : Optional filters to apply when getting the tiles.
    • isNotEmpty : If true, only return tiles that don't have -1 for an index.
    • isColliding : If true, only return tiles that collide on at least one side.
    • hasInterestingFace : If true, only return tiles that have at least one interesting face.
  • camera : The Camera to use when factoring in which tiles to return. Default is main camera.
  • layer : The tile layer to use. Default is current layer (map.setLayer(layer))
  • tiles : An array of Tiles, or null if layer is invalid.
"},{"location":"tilemap/#get-tiles-within-shape","title":"Get tiles within shape","text":"
vat tiles = map.getTilesWithinShape(shape);\n

or

vat tiles = map.getTilesWithinShape(shape, {\n// isNotEmpty: false,\n// isColliding: false,\n// hasInterestingFace: false\n}, camera, layer);\n

Shape:

  • new Phaser.Geom.Rectangle(x0, y0, width, height)
  • new Phaser.Geom.Line(x0, y0, x1, y1)
  • new Phaser.Geom.Circle(x, y, radius)
  • new Phaser.Geom.Triangle(x0, y0, x1, y1, x2, y2)
"},{"location":"tilemap/#for-each-tile-in-layer","title":"For each tile in layer","text":"
map.forEachTile(function(tile, index, tileArray) { /* ... */ }, context);\n

or

map.forEachTile(function(tile, index, tileArray) { /* ... */ }, context,\ntileX, tileY, width, height, {\n// isNotEmpty: false,\n// isColliding: false,\n// hasInterestingFace: false\n}, layer);\n
  • tileX , tileY : The left/top most tile index (in tile coordinates) to use as the origin of the area to search.
  • width , height : How many tiles wide/tall from the tileX/tileY index the area will be. Default is map.width/map.height.
  • filteringOptions : Optional filters to apply when getting the tiles.
    • isNotEmpty : If true, only return tiles that don't have -1 for an index.
    • isColliding : If true, only return tiles that collide on at least one side.
    • hasInterestingFace : If true, only return tiles that have at least one interesting face.
  • layer : The tile layer to use. Default is current layer (map.setLayer(layer))
"},{"location":"tilemap/#tile-index","title":"Tile index","text":"
  • Get index
    var index = tile.index;\n
  • Copy index
    tile.index = index;\n
  • Copy
    tile.copy(tileSrc);\n
    Copies the tile data & properties from the given tile to this tile. This copies everything except for position and interesting faces.
"},{"location":"tilemap/#tile-position","title":"Tile position","text":"
var x = tile.x;\nvar y = tile.y;\n
"},{"location":"tilemap/#tile-corners","title":"Tile corners","text":"
var points = map.getTileCorners(tileX, tileY, camera, layer);\n
  • points : Array of vector2 corresponding to the world XY location of each tile corner.
"},{"location":"tilemap/#alpha","title":"Alpha","text":"
  • Set
    tile.setAlpha(value);\n
    or
    tile.alpha = value;\n
  • Get
    var alpha = tile.alpha;\n
"},{"location":"tilemap/#visible","title":"Visible","text":"
  • Set
    tile.setVisible(visible);\n
    or
    tile.visible = visible;\n
  • Get
    var visible = visible;\n
"},{"location":"tilemap/#flip","title":"Flip","text":"
  • Set
    tile.setFlipX(flipX);\ntile.setFlipY(flipY);\n
    or
    tile.flipX = flipX;\ntile.flipY = flipY;\n
  • Toggle
    tile.toggleFlipX();\ntile.toggleFlipY();\n
    or
    tile.flipX = !tile.flipX;\ntile.flipY = !tile.flipY;\n
  • Reset
    tile.resetFlip();\n
    or
    tile.flipX = false;\ntile.flipY = false;\n
  • Get
    var flipX = tile.flipX;\nvar flipY = tile.flipY;\n
"},{"location":"tilemap/#bounds","title":"Bounds","text":"
  • Bounds rectangle
    var bounds = tile.getBounds();\n// var out = tile.getBounds(camera, out);\n
  • Left
    var left = tile.getLeft();\n// var left = tile.getLeft(camera);\n
  • Right
    var right = tile.getRight();\n// var right = tile.getRight(camera);\n
  • CenterX
    var centerX = tile.getCenterX();\n// var centerX = tile.getCenterX(camera);\n
  • Top
    var top = tile.getTop();\n// var top = tile.getTop(camera);\n
  • Bottom
    var bottom = tile.getBottom();\n// var bottom = tile.getBottom(camera);\n
  • CenterY
    var centerY = tile.getCenterY();\n// var centerY = tile.getCenterY(camera);\n
"},{"location":"tilemap/#properties","title":"Properties","text":"
var properties = tile.properties;  // object or null\nvar value = properties[key];\n
tile.properties[key] = value;\n
"},{"location":"tilemap/#collision","title":"Collision","text":""},{"location":"tilemap/#enable-collision","title":"Enable collision","text":"
  • Enable collision by tile index
    map.setCollision(index);\n// map.setCollision(index, true, recalculateFaces, updateLayer);\n
    • index : Tile index, or an array of tile indexes.
  • Enable collision by tile index in a range
    map.setCollisionBetween(start, stop);\n// map.setCollisionBetween(start, stop, true, recalculateFaces, layer);\n
    • start , stop : The first/last index of the tile.
  • Enable collision excluded tile indexes
    map.setCollisionByExclusion(indexes);\n// map.setCollisionByExclusion(indexes, true, recalculateFaces, layer);\n
    • index : An array of tile indexes.
  • Enable collision by properties matching
    • Enable collision if value of tile property 'key' is equal to 'value'
      map.setCollisionByProperty({key:value});\n// map.setCollisionByProperty({key:value}, true, recalculateFaces, layer);\n
    • Enable collision if value of tile property 'key' is equal to 'value0', or 'value1'
      map.setCollisionByProperty({key:[value0, value1]});\n// map.setCollisionByProperty({key:[value0, value1]}, true, recalculateFaces, layer);\n
  • Enable collision by collision group
    map.setCollisionFromCollisionGroup();\n// map.setCollisionFromCollisionGroup(true, recalculateFaces, layer);\n
"},{"location":"tilemap/#disable-collision","title":"Disable collision","text":"
  • Disable collision by tile index
    map.setCollision(index, false);\n// map.setCollision(index, false, recalculateFaces, layer);\n
    • index : Tile index, or an array of tile indexes.
  • Disable collision by tile index in a range
    map.setCollisionBetween(start, stop, false);\n// map.setCollisionBetween(start, stop, false, recalculateFaces, layer);\n
    • start , stop : The first/last index of the tile.
  • Disable collision by properties matching
    • Disable collision if value of tile property 'key' is equal to 'value'
      map.setCollisionByProperty({key:value}, false);\n// map.setCollisionByProperty({key:value}, false, recalculateFaces, layer);\n
    • Disable collision if value of tile property 'key' is equal to 'value0', or 'value1'
      map.setCollisionByProperty({key:[value0, value1]}, false);\n// map.setCollisionByProperty({key:[value0, value1]}, false, recalculateFaces, layer);\n
  • Disable collision by collision group
    map.setCollisionFromCollisionGroup(false);\n// map.setCollisionFromCollisionGroup(false, recalculateFaces, layer);\n
"},{"location":"tilemap/#get-collision-group","title":"Get collision group","text":"
var collisionGroup = tile.getCollisionGroup();\n

or

var collisionGroup = tileset.getTileCollisionGroup(tile.index); // array of collision shapes, or null\n

Types of collision shape (collisionGroup.objects[i])

  • object.rectangle :
    {\nrectangle: true,\nx, y,\nwidth, height\n}\n
    • x, y : Offset position related top-left of tile.
      var worldX = tile.getLeft() + object.x;\nvar worldY = tile.getTop() + object.y;\n
    • width, height : Width/height of rectangle area in pixels.
  • object.ellipse :
    {\nellipse: true,\nx, y,\nwidth, height\n}\n
    • x, y : Offset position related top-left of tile.
      var centerX = tile.getLeft() + object.x + (object.width / 2);\nvar centerY = tile.getTop() + object.y + (object.height / 2);\n
    • width, height : Width/height of ellipse area in pixels.
  • object.polygon :
    {\nx, y,\npolygon: [{x,y}, {x,y}, ...]\n}\n
    • Each point :
      {\nx: tile.getLeft() + object.x + polygon[i].x,\ny: tile.getTop() + object.y + polygon[i].y\n}\n
  • object.polyline :
    {\nx, y,\npolyline: [{x,y}, {x,y}, ...]\n}\n
    • Each point :
      {\nx: tile.getLeft() + object.x + polyline[i].x,\ny: tile.getTop() + object.y + polyline[i].y\n}\n
"},{"location":"tilemap/#arcade-collision","title":"Arcade collision","text":"
scene.physics.add.collider(arcadeGO, layer);\n

or, in update stage:

scene.physics.world.collide(arcadeGO, layer);\n

See Collision section of Arcade-world.

"},{"location":"tilemap/#matter-collision","title":"Matter collision","text":"
  • Any colliding tiles will be given a Matter body.
    scene.matter.world.convertTilemapLayer(layer);\n
"},{"location":"tilemap/#tileset","title":"Tileset","text":""},{"location":"tilemap/#get-tileset","title":"Get tileset","text":"
var tileset = map.getTileset(name);\n
"},{"location":"tilemap/#change-texture-of-tileset","title":"Change texture of tileset","text":"
var texture = scene.sys.textures.get(key);\ntileset.setImage(texture);\n
"},{"location":"tilesprite/","title":"Tile sprite","text":""},{"location":"tilesprite/#introduction","title":"Introduction","text":"

Display of repeating texture, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"tilesprite/#usage","title":"Usage","text":""},{"location":"tilesprite/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"tilesprite/#add-tile-sprite-object","title":"Add tile sprite object","text":"
var image = scene.add.tileSprite(x, y, width, height, textureKey);\n

Add tile sprite from JSON

var image = scene.make.tileSprite({\nx: 0,\ny: 0,\nwidth: 512,\nheight: 512,\nkey: '',\n\n// angle: 0,\n// alpha: 1\n// flipX: true,\n// flipY: true,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
"},{"location":"tilesprite/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTileSprite extends Phaser.GameObjects.TileSprite {\nconstructor(scene, x, y, width, height, texture, frame) {\nsuper(scene, x, y, width, height, texture, frame);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyTileSprite(scene, x, y, key);\n
"},{"location":"tilesprite/#properties-of-tiles","title":"Properties of tiles","text":"
  • Position
    image.setTilePosition(x, y);\n
    or
    image.tilePositionX = x;\nimage.tilePositionY = y;\n
  • Scale
    image.setTileScale(scaleX, scaleY);\n
    or
    image.tileScaleX = scaleX;\nimage.tileScaleY = scaleY;\n
"},{"location":"tilesprite/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"tilesprite/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"tilesprite/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"timeline/","title":"Timeline","text":""},{"location":"timeline/#introduction","title":"Introduction","text":"

Schedule commands to happen at specific times in the future, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"timeline/#usage","title":"Usage","text":""},{"location":"timeline/#create-timeline","title":"Create timeline","text":"
var timeline = scene.add.timeline([    {\n// Time condition\nat: 0,\nin:\nfrom:\n\n// Enable condition\nif(event) {\n// this: target parameter\nreturn true;  // false\n},\n\nset: {\nkey: value,\n},\n\ntween: {\ntargets: gameObject,\nalpha: 1,\nease: 'Linear',       // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\nrepeat: 0,            // -1: infinity\nyoyo: false\n},\n\nrun(){ // this: target parameter\n},\n\nloop() {\n\n},\n\nsound: '',\n\nevent: '',\n\n// target: this,\n\n// once: false,\n// stop: false,\n},\n\n// ...\n])\n
  • Time :
    • at : Absolute delay time after starting in ms.
    • in : Absolute delay time after current time in ms.
    • from : Relative delay time after previous event in ms
  • Enable :
    • if : A function. Invoking every tick, run actions when it returns true.
  • Actions :
    • set : A key-value object of properties to set on the target.
    • tween : tween config
    • run : A function which will be called when the Event fires.
      function() {\n// this: target parameter\n}\n
    • loop : A function which will be called when the Event sequence repeat again.
      function() {\n// this: target parameter\n}\n
    • sound :
      • A string : A key from the Sound Manager to play
      • A config object for a sound to play when the Event fires.
        {\nkey,\nconfig\n}\n
        • key : The key of the sound to play
        • config : config of playing sound
    • event : String-based event name to emit when the Event fires. The event is emitted from the Timeline instance.
      timeline.on(eventName);\n
    • target : The scope (this object) with which to invoke the run.
  • Control
    • once : If set, the Event will be removed from the Timeline when it fires.
    • stop : If set, the Timeline will stop and enter a complete state when this Event fires, even if there are other events after it.

The Timeline always starts paused.

"},{"location":"timeline/#steps-of-commands","title":"Steps of commands","text":"

For each tick, for each command :

  1. Test time (at, in, from)
  2. Test enable (if)
  3. Run actions (set, tween, run, sound, event)
  4. Control (once, stop)
"},{"location":"timeline/#start","title":"Start","text":"
timeline.play();\n
"},{"location":"timeline/#restart","title":"Restart","text":"
timeline.play(true);\n
"},{"location":"timeline/#start-with-repeat","title":"Start with repeat","text":"
  • Repeat infinite
    timeline.repeat().play();\n// timeline.repeat(true).play();\n// timeline.repeat(-1).play();\n
  • Amount of times to repeat
    timeline.repeat(amount).play();\n
    • amount : A positive number
  • No repeat
    timeline.repeat(false);\n
  • Current loop counter
    var loopCounter = timeline.iteration;\n
"},{"location":"timeline/#stop","title":"Stop","text":"
timeline.stop();\n
"},{"location":"timeline/#pause-resume","title":"Pause / Resume","text":"
timeline.pause();\n// timeline.paused = true;\n
timeline.resume();\n// timeline.paused = false;\n

Will also pause/resume currently active Tweens.

"},{"location":"timeline/#reset","title":"Reset","text":"

Resets this Timeline back to the start, include loop counter.

If the Timeline had any events that were set to once that have already been removed, they will not be present again after calling this method.

timeline.reset();\n

If the Timeline isn't currently running (i.e. it's paused or complete) then calling this method resets those states, the same as calling Timeline.play(true) (restart).

"},{"location":"timeline/#add-command","title":"Add command","text":"
timeline.add(config);\n

or

timeline.add([config0, config1, ...]);\n
"},{"location":"timeline/#clear-all-commands","title":"Clear all commands","text":"
timeline.clear();\n

Will also destroy currently active Tweens.

"},{"location":"timeline/#events","title":"Events","text":"
  • On all commands are completed
    timeline.on('complete', function(){\n\n});\n
"},{"location":"timeline/#other-properties","title":"Other properties","text":"
  • Timeline is currently playing, not paused or not complete.
    var isPlaying = timeline.isPlaying()\n
  • Is paused
    var isPaused = timeline.paused;\n
  • All commands are complete
    var isCompleted = timeline.complete;\n
"},{"location":"timeline/#destroy","title":"Destroy","text":"

Also remove updating.

timeline.destroy();\n

Will also destroy currently active Tweens.

"},{"location":"timer/","title":"Timer","text":""},{"location":"timer/#introduction","title":"Introduction","text":"

Execute callback when time-out, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"timer/#usage","title":"Usage","text":""},{"location":"timer/#start-timer","title":"Start timer","text":"
  • Looped timer
    var timer = scene.time.addEvent({\ndelay: 500,                // ms\ncallback: callback,\n//args: [],\ncallbackScope: thisArg,\nloop: true\n});\n
  • Repeat timer
    var timer = scene.time.addEvent({\ndelay: 500,                // ms\ncallback: callback,\n//args: [],\ncallbackScope: thisArg,\nrepeat: 4\n});\n
  • Oneshot timer
    var timer = scene.time.delayedCall(delay, callback, args, scope);  // delay in ms\n
  • All properties of timer
    var timer = scene.time.addEvent({\ndelay: 500,                // ms\ncallback: callback,\nargs: [],\ncallbackScope: thisArg,\nloop: false,\nrepeat: 0,\nstartAt: 0,\ntimeScale: 1,\npaused: false\n});\n
  • Reuse timer
    timer.reset({\ndelay: 500,                // ms\ncallback: callback,\nargs: [],\ncallbackScope: thisArg,\nloop: false,\nrepeat: 0,\nstartAt: 0,\ntimeScale: 1,\npaused: false\n})\nscene.time.addEvent(timer);\n

Note

Throw error message if delay : 0 with (repeat > 0 or loop: true)

"},{"location":"timer/#pauseresume","title":"Pause/resume","text":"
  • Pause timer
    timer.paused = true;\n
  • Resume timer
    timer.paused = false;\n
  • Is paused
    var isPaused = timer.paused;\n
"},{"location":"timer/#stop","title":"Stop","text":"
  • Stop a running timer
    timer.remove();\n
  • Remove from timeline's all internal lists, for timer re-using
    scene.time.removeEvent(timer);\n
"},{"location":"timer/#time-scale","title":"Time scale","text":"
  • Set
    timer.timeScale = 2;\n
  • Get
    var timeScale = timer.timeScale;\n
"},{"location":"timer/#other-properties","title":"Other properties","text":"
  • Get elapsed time
    var elapsed = timer.getElapsed();   // ms\nvar elapsed = timer.getElapsedSeconds(); // sec\n// var elapsed = timer.elapsed;  // ms\n
  • Get remaining time
    var remaining = timer.getRemaining();   // ms\nvar remaining = timer.getRemainingSeconds(); // sec\n// var remaining = timer.getOverallRemaining();   // ms\n// var remaining = timer.getOverallRemainingSeconds(); // sec\n
  • Get repeat count
    var repeat = timer.getRepeatCount();\n
  • Gets the progress of the current iteration
    var progress = timer.getProgress();  // elapsed / delay\n
  • Gets the progress of the timer overall, factoring in repeats.
    var progress = timer.getOverallProgress();  // totalElapsed / totalDuration\n
  • Get delay time
    var delay = timer.delay;   // ms\n
"},{"location":"tintrgb/","title":"TintRGB","text":""},{"location":"tintrgb/#introduction","title":"Introduction","text":"

Attach tintR, tintG, tintB, and tintGray properties to a game object.

Note

This behavior will override default tint property

  • Author: Rex
  • Method only
"},{"location":"tintrgb/#live-demos","title":"Live demos","text":"
  • Fade
  • Yellow to green
"},{"location":"tintrgb/#usage","title":"Usage","text":"

Sample code

"},{"location":"tintrgb/#install-plugin","title":"Install plugin","text":""},{"location":"tintrgb/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextintrgbplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextintrgbplugin.min.js', true);\n
  • Attach tintR, tintG, tintB, and tintGray properties.
    scene.plugins.get('rextintrgbplugin').add(gameObject, tintRGB);\ngameObject.tintGray = 128;\n
"},{"location":"tintrgb/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TintRGBPlugin from 'phaser3-rex-plugins/plugins/tintrgb-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTintRGB',\nplugin: TintRGBPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Attach tintR, tintG, tintB, and tintGray properties.
    scene.plugins.get('rexTintRGB').add(gameObject, tintRGB);\ngameObject.tintGray = 128;\n
"},{"location":"tintrgb/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import AddTintRGBProperties from 'phaser3-rex-plugins/plugins/tintrgb.js';\n
  • Attach tintR, tintG, tintB, and tintGray properties.
    AddTintRGBProperties(gameObject, tintRGB);\ngameObject.tintGray = 128;\n
"},{"location":"tintrgb/#attach-properties","title":"Attach properties","text":"
scene.plugins.get('rexTintRGB').add(gameObject, tintRGB);\ngameObject.tintGray = 128;\n// gameObject.tintR = 128;\n// gameObject.tintG = 128;\n// gameObject.tintB = 128;\n
  • tintRGB : Initial tintRGB value in 0xRRGGBB.
  • tintR : color R of tint, 0~255. Default is 255.
  • tintG : color G of tint, 0~255. Default is 255.
  • tintB : color B of tint, 0~255. Default is 255.
  • tintGray :\u3000Gray tint, 0~255. Default is 255.
    • Set gameObject.tintGray is equal to set tintR, tintG, tintB with the same value.
"},{"location":"tintrgb/#fade","title":"Fade","text":"
scene.tweens.add({\ntargets: gameObject,\ntintR: 0,\ntintG: 0,\ntintB: 0,\n// tintGray: 0,\nduration: 3000\n})\n
"},{"location":"tools/","title":"Tools","text":""},{"location":"tools/#texture-atlas","title":"Texture atlas","text":""},{"location":"tools/#texture-packer","title":"Texture-packer","text":"

Texture-packer

"},{"location":"tools/#free-texture-packer","title":"Free texture packer","text":"

Free texture packer, Web app

"},{"location":"tools/#leshy-spritesheet-tool","title":"Leshy SpriteSheet Tool","text":"

Leshy SpriteSheet Tool

Export to JSON-TP-Hash

"},{"location":"tools/#aseprite","title":"Aseprite","text":"

Aseprite

  1. Go to \"File - Export Sprite Sheet\"
  2. On the Layout tab:
  3. Set the \"Sheet type\" to \"Packed\"
  4. Set the \"Constraints\" to \"None\"
  5. Check the \"Merge Duplicates\" checkbox
  6. On the Sprite tab:
    1. Set \"Layers\" to \"Visible layers\"
    2. Set \"Frames\" to \"All frames\", unless you only wish to export a sub-set of tags
  7. On the Borders tab:
    1. Check the \"Trim Sprite\" and \"Trim Cells\" options
    2. Ensure \"Border Padding\", \"Spacing\" and \"Inner Padding\" are all > 0 (1 is usually enough)
  8. On the Output tab:
    1. Check \"Output File\", give your image a name and make sure you choose \"png files\" as the file type
    2. Check \"JSON Data\" and give your json file a name
    3. The JSON Data type can be either a Hash or Array, Phaser doesn't mind.
    4. Make sure \"Tags\" is checked in the Meta options
    5. In the \"Item Filename\" input box, make sure it says just \"{frame}\" and nothing more.
  9. Click export

Tested with Aseprite 1.2.25

"},{"location":"tools/#atlas-packer","title":"Atlas-packer","text":"
  • gammafp/Atlas-packer
"},{"location":"tools/#animation","title":"Animation","text":"
  • gammafp/Animator
"},{"location":"tools/#bitmap-font","title":"Bitmap font","text":"
  • SnowB BMF
  • 71squared-glyphdesigner
  • Bitmap Font Generator
  • TTF to PNG
"},{"location":"touchevents/","title":"Touch events","text":""},{"location":"touchevents/#introduction","title":"Introduction","text":"

Built-in touch/mouse events of phaser.

  • Author: Richard Davey

Note

No touch input event fired in preload stage.

"},{"location":"touchevents/#usage","title":"Usage","text":""},{"location":"touchevents/#quick-start","title":"Quick start","text":"
  • Is touching
    var pointer = scene.input.activePointer;\nif (pointer.isDown) {\nvar touchX = pointer.x;\nvar touchY = pointer.y;\n// ...\n}\n
  • On any touching start
    scene.input.on('pointerdown', function(pointer){\nvar touchX = pointer.x;\nvar touchY = pointer.y;\n// ...\n}, scope);\n
  • On any touching end
    scene.input.on('pointerup', function(pointer){\nvar touchX = pointer.x;\nvar touchY = pointer.y;\n// ...\n}, scope);\n
  • On touch game object start
    gameObject.setInteractive().on('pointerdown', function(pointer, localX, localY, event){\n// ...\n}, scope);\n
  • On touch game object end
    gameObject.setInteractive().on('pointerup', function(pointer, localX, localY, event){\n// ...\n}, scope);\n
  • Drag game object
    gameObject\n.setInteractive({ draggable: true })\n.on('dragstart', function(pointer, dragX, dragY){\n// ...\n}, scope);\n.on('drag', function(pointer, dragX, dragY){\ngameObject.setPosition(dragX, dragY);\n}, scope);\n.on('dragend', function(pointer, dragX, dragY, dropped){\n// ...\n}, scope);\n

Reference : Properties of point

"},{"location":"touchevents/#register-interactive","title":"Register interactive","text":"

Call gameObject.setInteractive(...) to register touch input of Game Object before listening touching events.

  • Set hit area from width & height (rectangle) of the texture
    gameObject.setInteractive();\n
  • Set hit area from game object
    gameObject.setInteractive(shape, callback);\n
    • Circle
      • shape : new Phaser.Geom.Circle(x, y, radius)
      • callback : Phaser.Geom.Circle.Contains
    • Ellipse
      • shape : new Phaser.Geom.Ellipse(x, y, width, height)
      • callback : Phaser.Geom.Ellipse.Contains
    • Rectangle
      • shape : new Phaser.Geom.Rectangle(x, y, width, height)
      • callback : Phaser.Geom.Rectangle.Contains
    • Triangle
      • shape : new Phaser.Geom.Triangle(x1, y1, x2, y2, x3, y3)
      • callback : Phaser.Geom.Triangle.Contains
    • Polygon
      • shape : new Phaser.Geom.Polygon(points)
      • callback : Phaser.Geom.Polygon.Contains
    • Hexagon
      • shape : new Phaser.Geom.rexHexagon(x, y, size, type)
      • callback : Phaser.Geom.Polygon.Contains
    • Rhombus
      • shape : new Phaser.Geom.rexRhombus(x, y, width, height)
      • callback : Phaser.Geom.Polygon.Contains
    • Note: x, y relate to the top-left of the gameObject.
  • Set hit area from input plugin
    scene.input.setHitArea(gameObjects, shape, callback);\n
    • Circle
      scene.input.setHitAreaCircle(gameObjects, x, y, radius);\n// scene.input.setHitAreaCircle(gameObjects, x, y, radius, callback); // callback = Circle.Contains\n
    • Ellipse
      scene.input.setHitAreaEllipse(gameObjects, x, y, width, height);\n// scene.input.setHitAreaEllipse(gameObjects, x, y, width, height, callback); // callback = Ellipse.Contains\n
    • Rectangle
      scene.input.setHitAreaRectangle(gameObjects, x, y, width, height);\n// scene.input.setHitAreaRectangle(gameObjects, x, y, width, height, callback); // callback = Rectangle.Contains\n
    • Triangle
      scene.input.setHitAreaTriangle(gameObjects, x1, y1, x2, y2, x3, y3);\n// scene.input.setHitAreaTriangle(gameObjects, x1, y1, x2, y2, x3, y3, callback); // callback = Triangle.Contains\n
    • Note: x, y relate to the top-left of the gameObject.
  • Set interactive configuration
    gameObject.setInteractive({\nhitArea: shape,\nhitAreaCallback: callback,\nhitAreaDebug: shape,\ndraggable: false,\ndropZone: false,\nuseHandCursor: false,\ncursor: CSSString,\npixelPerfect: false,\nalphaTolerance: 1\n});\n
    • Hit area
      • shape
      • Pixel alpha
        • pixelPerfect : true
        • alphaTolerance : 1 (0-255)
      • Custom hit-testing function
        • hitAreaCallback
          function(shape, x, y, gameObject) {\nreturn hit;  // true/false\n}\n
          • shape : Hit area object
          • x, y : Local position of texture.
          • gameObject : Game object.
      • hitAreaDebug : Debug shape.
    • Dragging
      • draggable : true
    • Drop zone
      • dropZone : true
    • Cursor
      • cursor : CSS string
      • useHandCursor : true

Pixel perfect hit-testing

This is an expensive process, should only be enabled on Game Objects that really need it.

"},{"location":"touchevents/#disable-interactive","title":"Disable interactive","text":"
  • Disable temporary
    gameObject.disableInteractive();\n// gameObject.disableInteractive(resetCursor);\n
    • resetCursor : Should the currently active Input cursor, if any, be reset to the default cursor?
  • Remove interaction
    gameObject.removeInteractive();\n// gameObject.removeInteractive(resetCursor);\n
    • resetCursor : Should the currently active Input cursor, if any, be reset to the default cursor?
"},{"location":"touchevents/#top-only","title":"Top only","text":"

When set to true this Input Plugin will emulate DOM behavior by only emitting events from the top-most Game Objects in the Display List. If set to false it will emit events from all Game Objects below a Pointer, not just the top one.

  • Get
    var topOnly = scene.input.topOnly;\n
  • Set
    scene.input.topOnly = topOnly;\nscene.input.setTopOnly(topOnly);\n

Each scene can has its own scene.input.topOnly setting.

"},{"location":"touchevents/#touch-events","title":"Touch events","text":"

Trigger these events from top scene to bottom scene.

  1. Events on touched Game object
    gameObject.on('pointerdown', function(pointer, localX, localY, event){ /* ... */ }, scope);\ngameObject.on('pointerup', function(pointer, localX, localY, event){ /* ... */ }, scope);\ngameObject.on('pointermove', function(pointer, localX, localY, event){ /* ... */ }, scope);\ngameObject.on('pointerover', function(pointer, localX, localY, event){ /* ... */ }, scope);\ngameObject.on('pointerout', function(pointer, event){ /* ... */ }, scope);\n
    • Cancel remaining touched events
      function(pointer, localX, localY, event) {\nevent.stopPropagation();\n}\n
  2. Event on input plugin for each touched Game object
    scene.input.on('gameobjectdown', function(pointer, gameObject, event){ /* ... */ }, scope);\nscene.input.on('gameobjectup', function(pointer, gameObject, event){ /* ... */ }, scope);\nscene.input.on('gameobjectmove', function(pointer, gameObject, event){ /* ... */ }, scope);\nscene.input.on('gameobjectover', function(pointer, gameObject, event){ /* ... */ }, scope);\nscene.input.on('gameobjectout', function(pointer, gameObject, event){ /* ... */ }, scope);\n
    • Cancel remaining touched events
      function(pointer, gameObject, event) {\nevent.stopPropagation();\n}\n
  3. Events to get all touched Game Objects
    scene.input.on('pointerdown', function(pointer, currentlyOver){ /* ... */ }, scope);\nscene.input.on('pointerdownoutside', function(pointer){ /* ... */ }, scope);\nscene.input.on('pointerup', function(pointer, currentlyOver){ /* ... */ }, scope);\nscene.input.on('pointerupoutside', function(pointer){ /* ... */ }, scope);\nscene.input.on('pointermove', function(pointer, currentlyOver){ /* ... */ }, scope);\nscene.input.on('pointerover', function(pointer, justOver){ /* ... */ }, scope);\nscene.input.on('pointerout', function(pointer, justOut){ /* ... */ }, scope);\nscene.input.on('gameout', function(timeStamp, domEvent){ /* ... */ }, scope);\nscene.input.on('gameover', function(timeStamp, domEvent){ /* ... */ }, scope);\n
    • Check pointer.camera in multiple-cameras scene.
"},{"location":"touchevents/#game-canvas","title":"Game canvas","text":"
scene.input.on('gameout', function(timeStamp, event){ /* ... */ }, scope);\nscene.input.on('gameover', function(timeStamp, event){ /* ... */ }, scope);\n
"},{"location":"touchevents/#dragging","title":"Dragging","text":""},{"location":"touchevents/#enable-dragging","title":"Enable dragging","text":"
  • Enable dragging when registering interactive
    gameObject.setInteractive({ draggable: true });\n
  • Enable dragging and add it to dragging detecting list after registered interactive
    scene.input.setDraggable(gameObject);\n
  • Enable dragging
    gameObject.input.draggable = true;\n
"},{"location":"touchevents/#disable-dragging","title":"Disable dragging","text":"
  • Remove Game Object from dragging detecting list
    scene.input.setDraggable(gameObject, false);\n
  • Disable dragging but keep it in dragging detecting list
    gameObject.input.draggable = false;\n
"},{"location":"touchevents/#dragging-events","title":"Dragging events","text":"
gameObject.on('dragstart', function(pointer, dragX, dragY){ /* ... */ }, scope);\ngameObject.on('drag', function(pointer, dragX, dragY){ /* ... */ }, scope);\ngameObject.on('dragend', function(pointer, dragX, dragY, dropped){ /* ... */ }, scope);\n
scene.input.on('dragstart', function(pointer, gameObject){ /* ... */ }, scope);\nscene.input.on('drag', function(pointer, gameObject, dragX, dragY){ /* ... */ }, scope);\nscene.input.on('dragend', function(pointer, gameObject, dropped){ /* ... */ }, scope);\n
  • dropped : 'dragend' and also 'drop'.
"},{"location":"touchevents/#dragging-properties","title":"Dragging properties","text":"
scene.input.dragDistanceThreshold = 16;\nscene.input.dragTimeThreshold = 500;\n
"},{"location":"touchevents/#drop-zone","title":"Drop zone","text":""},{"location":"touchevents/#enable-drop-zone","title":"Enable drop zone","text":"
  • Enable dropping when registering interactive
    gameObject.setInteractive({ dropZone: true });\n
  • Enable dropping after registered interactive
    gameObject.input.dropZone = true;\n
"},{"location":"touchevents/#disable-drop-zone","title":"Disable drop zone","text":"
gameObject.input.dropZone = false;\n
"},{"location":"touchevents/#dropping-events","title":"Dropping events","text":"
gameObject.on('drop', function(pointer, target){ /* ... */ }, scope);\n\ngameObject.on('dragenter', function(pointer, target){ /* ... */ }, scope);\ngameObject.on('dragover', function(pointer, target){ /* ... */ }, scope);\ngameObject.on('dragleave', function(pointer, target){ /* ... */ }, scope);\n
scene.input.on('drop', function(pointer, gameObject, target){ /* ... */ }, scope);\n\nscene.input.on('dragenter', function(pointer, gameObject, target){ /* ... */ }, scope);\nscene.input.on('dragover', function(pointer, gameObject, target){ /* ... */ }, scope);\nscene.input.on('dragleave', function(pointer, gameObject, target){ /* ... */ }, scope);\n
"},{"location":"touchevents/#force-state-of-pointer","title":"Force state of pointer","text":"
  • Down state
    scene.input.forceDownState(pointer, gameObject);\n
    • Emit 'pointerdown' event from game object.
    • Emit 'gameobjectdown' event from scene.input.
  • Up state
    scene.input.forceUpState(pointer, gameObject);\n
    • Emit 'pointerup' event from game object.
    • Emit 'gameobjectup' event from scene.input.
  • Over state
    scene.input.forceOverState(pointer, gameObject);\n
    • Emit 'pointerover' event from game object.
    • Emit 'gameobjectover' event from scene.input.
  • Out state
    scene.input.forceOutState(pointer, gameObject);\n
    • Emit 'pointeroutr' event from game object.
    • Emit 'gameobjectout' event from scene.input.
"},{"location":"touchevents/#first-event-of-all","title":"First event of all","text":"
scene.input.on('preupdate', function() { /* ... */ }, scope);\n
"},{"location":"touchevents/#single-touch","title":"Single touch","text":""},{"location":"touchevents/#pointer","title":"Pointer","text":"
var pointer = scene.input.activePointer;\n
"},{"location":"touchevents/#multi-touch","title":"Multi-touch","text":""},{"location":"touchevents/#amount-of-active-pointers","title":"Amount of active pointers","text":"

Set amount of active pointers in game configuration

var config = {\n// ...\ninput: {\nactivePointers: 1,\n// ...\n}\n};\nvar game = new Phaser.Game(config);\n

Or add pointers in run-time.

scene.input.addPointer(num);  // total points = num + 1\n
"},{"location":"touchevents/#pointers","title":"Pointers","text":"
  • pointer 1 ~ 10
    var pointer = scene.input.pointer1;\n// ...\nvar pointer = scene.input.pointer10;\n
  • pointer n
    var pointer = scene.input.manager.pointers[n];\n
  • Amount of total pointers
    var amount = scene.input.manager.pointersTotal;\n
    • 1 in desktop
    • 2 in touch device. (0 for mouse, 1 for 1 touch pointer)
"},{"location":"touchevents/#pointer_1","title":"Pointer","text":"
  • Position
    • Current touching
      • Position in screen : pointer.x , pointer.y
      • Position in camera :
        • Single camera :
          var worldX = pointer.worldX;\nvar worldY = pointer.worldY;\n
        • Multiple cameras :
          var worldXY = pointer.positionToCamera(camera);  // worldXY: {x, y}\n// var worldXY = pointer.positionToCamera(camera, worldXY);\nvar worldX = worldXY.x;\nvar worldY = worldXY.y;\n
        • Camera
          var camera = pointer.camera;\n
      • Position of previous moving : pointer.prevPosition.x , pointer.prevPosition.y
        • Updating when pointer-down, potiner-move, or pointer-up.
      • Interpolated position :
        var points = pointer.getInterpolatedPosition(step);\n// var out = pointer.getInterpolatedPosition(step, out);\n
    • Drag
      • Touching start : pointer.downX, pointer.downY
      • Touching end : pointer.upX, pointer.upY
      • Drag distance between pointer-down to latest pointer : pointer.getDistance()
        • Horizontal drag distance : pointer.getDistanceX()
        • Vertical drag distance : pointer.getDistanceY()
      • Drag angle : pointer.getAngle()
  • Time
    • Touching start : pointer.downTime
    • Touching end : pointer.upTime
    • Drag : pointer.getDuration()
  • Touch state
    • Is touching/any button down : pointer.isDown
    • Is primary button down : pointer.primaryDown
  • Button state : pointer.button
    • On Touch devices the value is always 0.
  • Button down
    • No button down : pointer.noButtonDown()
    • Is primary (left) button down : pointer.leftButtonDown()
    • Is secondary (right) button down : pointer.rightButtonDown()
    • Is middle (mouse wheel) button down : pointer.middleButtonDown()
    • Is back button down : pointer.backButtonDown()
    • Is forward button down : pointer.forwardButtonDown()
  • Button released
    • Is primary (left) button released : pointer.leftButtonReleased()
    • Is secondary (right) button released : pointer.rightButtonReleased()
    • Is middle (mouse wheel) button released : pointer.middleButtonReleased()
    • Is back button released : pointer.backButtonReleased()
    • Is forward button released : pointer.forwardButtonReleased()
  • Index in scene.input.manager.pointers : pointer.id
  • Motion
    • Angle: pointer.angle
    • Distance: pointer.distance
    • Velocity: pointer.velocity
      • pointer.velocity.x, `pointer.velocity.y
"},{"location":"touchevents/#input-object","title":"Input object","text":"
  • gameObject.input : Game object's input object.
  • gameObject.input.localX, gameObject.input.localY : Pointer to local position of texture.
  • gameObject.input.dragStartX, gameObject.input.dragStartY : The x/y coordinate of the Game Object that owns this Interactive Object when the drag started.
  • gameObject.input.dragStartXGlobal, gameObject.input.dragStartYGlobal : The x/y coordinate that the Pointer started dragging this Interactive Object from.
  • gameObject.input.dragX, gameObject.input.dragY : The x/y coordinate that this Interactive Object is currently being dragged to.
"},{"location":"touchevents/#smooth","title":"Smooth","text":"

Get touch position from interpolation of previous touch position and current touch position.

Touch-position = (current-touch-position * smooth-factor) + (previous-touch-position * (1 - smooth-factor))\n
  1. Set smooth factor. In game configuration
    var config = {\n// ....\ninput: {\nsmoothFactor: 0\n}\n}\n
  2. Get touch position
    var x = pointer.x;\nvar y = pointer.y;\nvar worldX = pointer.worldX;\nvar worldY = pointer.worldY;\n
"},{"location":"touchevents/#debug","title":"Debug","text":"
  • Enable, draw shape of (shape) hit area.
    scene.input.enableDebug(gameObject);\n// scene.input.enableDebug(gameObject, color);\n
  • Disable
    scene.input.removeDebug(gameObject);\n
  • Get debug shape game object
    var shape = gameObject.input.hitAreaDebug;\n
"},{"location":"touchevents/#poll-rate","title":"Poll rate","text":"
  • Poll when touches moved, or updated. Default behavior.
    scene.input.setPollOnMove();\n
  • Poll every tick.
    scene.input.setPollAlways();\n
  • Set poll rate.
    scene.input.setPollRate(rate);\n
"},{"location":"toucheventstop/","title":"Touch event stop","text":""},{"location":"toucheventstop/#introduction","title":"Introduction","text":"

Stop touch events propagation.

  • Author: Rex
  • Behavior of game object
"},{"location":"toucheventstop/#live-demos","title":"Live demos","text":"
  • Stop touch events
"},{"location":"toucheventstop/#usage","title":"Usage","text":"

Sample code

"},{"location":"toucheventstop/#install-plugin","title":"Install plugin","text":""},{"location":"toucheventstop/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextoucheventstopplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextoucheventstopplugin.min.js', true);\n
  • Add touch-event-stop behavior
    var touchEventStop = scene.plugins.get('rextoucheventstopplugin').add(gameObject, config);\n
"},{"location":"toucheventstop/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TouchEventStopPlugin from 'phaser3-rex-plugins/plugins/toucheventstop-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTouchEventStop',\nplugin: TouchEventStopPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add touch-event-stop behavior
    var touchEventStop = scene.plugins.get('rexTouchEventStop').add(gameObject, config);\n
"},{"location":"toucheventstop/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import TouchEventStop from 'phaser3-rex-plugins/plugins/toucheventstop.js';\n
  • Add touch-event-stop behavior
    var touchEventStop = newe TouchEventStop(gameObject, config);\n
"},{"location":"toucheventstop/#create-instance","title":"Create instance","text":"
var touchEventStop = scene.plugins.get('rexTouchEventStop').add(gameObject, {\n// hitAreaMode: 0,    // 0|1|'default'|'fullWindow'\n// enable: true\n});\n
  • hitAreaMode : Mode of hit-area
    • 0, or 'default' : Set hit-area to size of game object, only touch events on this game object will be stopped..
    • 1, or 'fullWindow' : Set hit-area to whole window, all touch events will be stopped.
  • enable : Set false to disable touch-event-stop behavior.
"},{"location":"toucheventstop/#enable","title":"Enable","text":"
  • Get
    var enable = touchEventStop.enable;  // enable: true, or false\n
  • Set
    touchEventStop.setEnable(enable);  // enable: true, or false\n// touchEventStop.enable = enable;\n
  • Toggle
    touchEventStop.toggleEnable();\n
"},{"location":"touchstate/","title":"Touch state","text":""},{"location":"touchstate/#introduction","title":"Introduction","text":"

Store current touch input properties.

  • Author: Rex
  • Behavior of game object
"},{"location":"touchstate/#usage","title":"Usage","text":"

Sample code

"},{"location":"touchstate/#install-plugin","title":"Install plugin","text":""},{"location":"touchstate/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextouchstateplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextouchstateplugin.min.js', true);\n
  • Add touch-state behavior
    var touchState = scene.plugins.get('rextouchstateplugin').add(gameObject, config);\n
"},{"location":"touchstate/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TouchStatePlugin from 'phaser3-rex-plugins/plugins/touchstate-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTouchState',\nplugin: TouchStatePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add touch-state behavior
    var touchState = scene.plugins.get('rexTouchState').add(gameObject, config);\n
"},{"location":"touchstate/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TouchState from 'phaser3-rex-plugins/plugins/touchstate.js';\n
  • Add touch-state behavior
    var touchState = new TouchState(gameObject, config);\n
"},{"location":"touchstate/#create-instance","title":"Create instance","text":"
var touchState = scene.plugins.get('rexTouchState').add(gameObject, {\n// enable: true,\n});\n
  • enable : Can touch.
"},{"location":"touchstate/#properties","title":"Properties","text":"
  • Is pointer down, is pointer up
    var isDown = touchState.isDown;\nvar isUp = touchState.isUp;\n
  • Is in touching
    var isInTouching = touchState.isInTouching;\n
  • Pointer in local position
    var localX = touchState.localX;\nvar localY = touchState.localY;\n
  • Drag speed
    var speed = touchState.speed;\nvar speedX =  touchState.speedX;\nvar speedY =  touchState.speedY;\n
    var dx = touchState.dx;\nvar dy = touchState.dy;\nvar dt = touchState.dt;    
"},{"location":"touchstate/#events","title":"Events","text":"
  • Touch start (pointer down)
    touchState.on('touchstart', function (touchState, gameObject, pointer, localX, localY, event) {\n// ...\n}, scope);\n
  • Touch end (pointer up)
    touchState.on('touchend', function (touchState, gameObject, pointer) {\n// ...\n}, scope);\n
  • Touch move (pointer move)
    touchState.on('touchmove', function (touchState, gameObject, pointer, localX, localY, event) {\n// ...\n}, scope);\n
"},{"location":"touchstate/#enable","title":"Enable","text":"
  • Get
    var enabled = touchState.enable;  // enabled: true, or false\n
  • Set
    touchState.setEnable(enabled);  // enabled: true, or false\n// touchState.enable = enabled;\n
  • Toggle
    touchState.toggleEnable();\n
"},{"location":"transitionimage/","title":"Transition image","text":""},{"location":"transitionimage/#introduction","title":"Introduction","text":"

Transit texture to another one. A containerLite game object with 2 image game objects.

  • Author: Rex
  • Game object
"},{"location":"transitionimage/#live-demos","title":"Live demos","text":"
  • Ease property of current/next image
    • Cross-fade
    • Scale
    • Slide
  • Apply shader effect to current/next image, then ease property this shader effect.
    • Split
    • Dissolve
  • Grid cut current/next image to cell images, then ease property of cell images
    • Grid cut
    • 3 columns
  • Morph custom mask game object
    • Pie mask
  • Transition modes
"},{"location":"transitionimage/#usage","title":"Usage","text":"

Sample code

"},{"location":"transitionimage/#install-plugin","title":"Install plugin","text":""},{"location":"transitionimage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextransitionimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextransitionimageplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexTransitionImage(x, y, texture, frame, config);\n
"},{"location":"transitionimage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TransitionImagePlugin from 'phaser3-rex-plugins/plugins/transitionimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTransitionImagePlugin',\nplugin: TransitionImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexTransitionImage(x, y, texture, frame, config);\n
"},{"location":"transitionimage/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TransitionImage from 'phaser3-rex-plugins/plugins/transitionimage.js';\n
  • Add image object
    var image = new TransitionImage(scene, x, y, texture, frame, config);\nscene.add.existing(image);\n
"},{"location":"transitionimage/#create-instance","title":"Create instance","text":"

var image = scene.add.rexTransitionImage(x, y, texture, frame, {\n// dir: 0,\n// onStart: function(parent, currentImage, nextImage, t) { },\n// onStartScope: undefined,\n// onProgress: function(parent, currentImage, nextImage, t) { },\n// onProgressScope: undefined,\n// onComplete: function(parent, currentImage, nextImage, t) { },\n// onCompleteScope: undefined,    \n// duration: 1000,\n// ease: 'Linear',\n// mask: undefined,\n\n// width: undefined, height: undefined,\n});\n
or

var image = scene.add.rexTransitionImage(x, y, texture, frame, {\n// x: 0,\n// y: 0,\n// key: \n// frame: \n// dir: 0,\n// onStart: function(parent, currentImage, nextImage, t) { },\n// onStartScope: undefined,\n// onProgress: function(parent, currentImage, nextImage, t) { },\n// onProgressScope: undefined,\n// onComplete: function(parent, currentImage, nextImage, t) { },\n// onCompleteScope: undefined,    \n// duration: 1000,\n// ease: 'Linear',\n// mask: undefined,\n\n// width: undefined, height: undefined,\n});\n
  • dir : Transition direction.
    • 0, or 'out' : Transit current texture/image out.
    • 1, or 'in' : Transit next texture/image in.
  • onStart, onStartScope : Callback and scope of transition-start. See Set transition callbacks
  • onProgress, onProgressScope : Callback and scope of transition-progress. See Set transition callbacks
  • onComplete, onCompleteScope : Callback and scope of transition-complete. See Set transition callbacks
  • duration : Duration of transition.
  • ease : Ease function of transition-progress.
  • mask : Mask game object.
    • true : Default graphics game object.
    • Any shape game object, or custom shape, custom progress game object.
  • width, height : Scale images to fit this size (widthxheight).
    • undefined : Don't scale images.

If onStart, onProgress and onComplete are all undefined, it will use cross-fade as default transition callbacks.

Add transitionimage from JSON

var image = scene.make.rexTransitionImage({\nx: 0,\ny: 0,\nkey: null,\nframe: null,\n\n// dir: 0,\n// onStart: function(parent, currentImage, nextImage, t) { },\n// onStartScope: undefined,\n// onProgress: function(parent, currentImage, nextImage, t) { },\n// onProgressScope: undefined,\n// onComplete: function(parent, currentImage, nextImage, t) { },\n// onCompleteScope: undefined,\n// duration: 1000,\n// ease: 'Linear',\n// mask: undefined,\n\n// width: undefined, height: undefined,\n\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
"},{"location":"transitionimage/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTransitionImage extends TransitionImage {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var transitionimage = new MyTransitionImage(scene, x, y, texture, frame, config);\n
"},{"location":"transitionimage/#transit","title":"Transit","text":"
image\n// .setTransitionDirection(dir)\n// .setTransitionStartCallback(onStart, onStartScope)\n// .setTransitionProgressCallback(onProgress, onProgressScope)\n// .setTransitionCompleteCallback(onComplete, onCompleteScope)\n// .setDuration(duration)\n// .setEaseFunction(ease)\n// .setMaskEnable(enable)\n.transit(texture, frame)\n

or

image.transit({\nkey: undefined,\n// frame: undefined,\n// dir: 0,\n// onStart: function(parent, currentImage, nextImage, t) { },\n// onStartScope: undefined,\n// onProgress: function(parent, currentImage, nextImage, t) { },\n// onProgressScope: undefined,\n// onComplete: function(parent, currentImage, nextImage, t) { },\n// onCompleteScope: undefined,\n// duration: 1000,\n// ease: 'Linear',\n// mask: undefined,\n})\n
  • mask : Mask game object.
    • true : Default graphics game object. Also apply this mask to current and next textures/images
    • Any shape game object, or custom shape, custom progress game object.
      • Apply mask to current texture :
        image.setCurrentImageMaskEnable();\n// image.setCurrentImageMaskEnable(enable, invertAlpha);\n
      • Apply mask to next texture :
        image.setNextImageMaskEnable();\n// image.setNextImageMaskEnable(enable, invertAlpha);\n
      • Apply mask to both current and next trextures :
        image.setMaskEnable();\n// image.setMaskEnable(enable, invertAlpha);\n

Fire 'complete' event when transition completed.

"},{"location":"transitionimage/#register-transtion-mode","title":"Register transtion mode","text":"
  • Register transtion mode
    image.addTransitionMode(modeName, {\n// dir: 0,\n// onStart: function(parent, currentImage, nextImage, t) { },\n// onStartScope: undefined,\n// onProgress: function(parent, currentImage, nextImage, t) { },\n// onProgressScope: undefined,\n// onComplete: function(parent, currentImage, nextImage, t) { },\n// onCompleteScope: undefined,\n// duration: 1000,\n// ease: 'Linear',\n// mask: undefined,\n});\n
  • Trnasit by transition mode
    image.transit(texture, frame, modeName);\n// image.transit(texture, frame, modeNames);\n
    or
    image.transit({\nkey: undefined,\n// frame: undefined,\n\nmode: modeName, // or modeName\n// dir: 0,\n// onStart: function(parent, currentImage, nextImage, t) { },\n// onStartScope: undefined,\n// onProgress: function(parent, currentImage, nextImage, t) { },\n// onProgressScope: undefined,\n// onComplete: function(parent, currentImage, nextImage, t) { },\n// onCompleteScope: undefined,\n// duration: 1000,\n// ease: 'Linear',\n// mask: undefined,\n})\n
    • Can override configuration of transition mode
    • modeName : A string, or an array of string to pick a random mode.
  • Current transition mode
    var modeName = image.currentTransitionMode;\n
"},{"location":"transitionimage/#current-texture","title":"Current texture","text":"
var textureKey = image.texture.key;\nvar frameName = image.frame.name;\n
"},{"location":"transitionimage/#transition-callbacks","title":"Transition callbacks","text":"
  • Set transition direction
    image.setTransitionDirection(dir);\n
    • 0, or 'out' : Transit current texture out.
    • 1, or 'in' : Transit next texture in.
  • Set transition-start callback
    image.setTransitionStartCallback(onStart, onStartScope)\n
    • onStart
      function(parent, currentImage, nextImage, t) { }\n
      • parent : Transition image game object, extends from ContainerLite
      • currentImage : Image game object to display current texture.
      • nextImage : Image game object to display next texture.
      • t : Progress percentage. It is 0 in this case.
  • Set transition-progress callback
    image.setTransitionProgressCallback(onProgress, onProgressScope)\n
    • onProgress
      function(parent, currentImage, nextImage, t) { // parent.setChildLocalAlpha(currentImage, 1 - t);\n// parent.setChildLocalScale(currentImage, 1 - t);\n// parent.setChildLocalPosition(currentImage, x, 0);\n}\n
      • parent : Transition image game object, extends from ContainerLite
      • currentImage : Image game object to display current texture.
        • Set alpha of currentImage, or nextImage by parent.setChildLocalAlpha(currentImage, alpha).
        • Set scale of currentImage, or nextImage by parent.setChildLocalScale(currentImage, scale).
        • Set position of currentImage, or nextImage by parent.setChildLocalScale(currentImage, x, y).
      • nextImage : Image game object to display next texture.
      • t : Progress percentage. 0~1.
  • Set transition-complete callback
    image.setTransitionCompleteCallback(onComplete, onCompleteScope)\n
    • onComplete
      function(parent, currentImage, nextImage, t) { }\n
      • parent : Transition image game object, extends from ContainerLite
      • currentImage : Image game object to display current texture.
      • nextImage : Image game object to display next texture.
      • t : Progress percentage. It is 1 in this case.
"},{"location":"transitionimage/#transition-duration","title":"Transition duration","text":"
  • Set
    image.setDuration(duration);\n
  • Get
    var duration = image.duration;\n
"},{"location":"transitionimage/#ease-function","title":"Ease function","text":"
  • Set
    image.setEaseFunction(ease);\n
    • ease : Ease function of transition-progress.
  • Get
    var ease = image.easeFunction;\n
"},{"location":"transitionimage/#mask","title":"Mask","text":"
  • Apply mask to current texture :
    image.setCurrentImageMaskEnable();\n// image.setCurrentImageMaskEnable(enable, invertAlpha);\n
  • Apply mask to next texture :
    image.setNextImageMaskEnable();\n// image.setNextImageMaskEnable(enable, invertAlpha);\n
  • Apply mask to both current and next trextures :
    image.setMaskEnable();\n// image.setMaskEnable(enable, invertAlpha);\n
  • Assign default mask game object
    image.setMaskGameObject(true);\n
  • Assign custom mask game object
    image.setMaskGameObject(maskGameObject);\n
    • maskGameObject : A graphics game object, or any shape game objects, custom-progress shape game object
"},{"location":"transitionimage/#grid-cut","title":"Grid cut","text":"

Grid cut texture to cells.

  • Grid cut current texture :
    var cellImageGameObjects = image.gridCutCurrentImage(columns, rows);\n
    • cellImageGameObjects : Array of cell game objects.
  • Grid cut next texture :
    var cellImageGameObjects = image.gridCutNextImage(columns, rows);\n
    • cellImageGameObjects : Array of cell game objects.
  • Get cut cell image game objects, after cutting.
    var cellImageGameObjects = image.getCellImages();\n
  • Apply mask to cell images
    image.setCellImagesMaskEnable();\n// image.setCellImagesMaskEnable(enable, invertAlpha);\n

Cut cell image game objects will be set to invisible after transition complete.

"},{"location":"transitionimage/#pauseresume","title":"Pause/Resume","text":"
image.pause();\n
image.resume();\n
"},{"location":"transitionimage/#stop","title":"Stop","text":"
image.stop();\n

Also will fire 'complete' event.

"},{"location":"transitionimage/#events","title":"Events","text":"
  • On complete
    image.on('complete', function(){\n})\n
"},{"location":"transitionimage/#flip","title":"Flip","text":"

Apply flipX, flipY to both current and next trextures.

  • Flip
    image.flipX(value);\nimage.flipY(value);\nimage.flip(x, y);\n
  • Toggle
    image.toggleFlipX();\nimage.toggleFlipY();\n
"},{"location":"transitionimage/#tint","title":"Tint","text":"

Apply tint to both current and next trextures.

image.setTint(value);\n
"},{"location":"transitionimage/#use-cases","title":"Use cases","text":"
  • Ease property of current/next image.
    • Scale
    • Slide, apply mask to current/next image.
  • Apply shader effect to current/next image, then ease property this shader effect.
    • Dissolve
    • Split
  • Grid cut current/next image to cell images, then ease property of cell images
    • Grid cut
    • Three-columns, apply mask to cell images.
  • Morph custom mask game object
    • Pie-mask, mask current/next image by a custom-progress game object.
"},{"location":"transitionimage/#internal-image-game-object","title":"Internal image game object","text":"
  • Current, next image game object
    var curentImageGO = image.currentImage;\nvar nextImageGO = image.nextImage;\n
  • Front, back image game object
    var frontImageGO = image.frontImage;\nvar backImageGO = image.backImage;\n
"},{"location":"transitionimage/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"transitionimage/#shader-effects","title":"Shader effects","text":"

Internal image game objects (image.currentImage, image.nextImage) support preFX and postFX effects

"},{"location":"transitionimagepack/","title":"Transition image pack","text":""},{"location":"transitionimagepack/#introduction","title":"Introduction","text":"

Transit texture to another one, with some pre-build effects, extended from TransitionImage

  • Author: Rex
  • Game object
"},{"location":"transitionimagepack/#live-demos","title":"Live demos","text":"
  • Effect list
  • Slide modes
  • Fade modes
  • Mask modes
  • Shader effect modes
"},{"location":"transitionimagepack/#usage","title":"Usage","text":"

Sample code

"},{"location":"transitionimagepack/#install-plugin","title":"Install plugin","text":""},{"location":"transitionimagepack/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextransitionimagepackplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextransitionimagepackplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexTransitionImagePack(x, y, texture, frame, config);\n
"},{"location":"transitionimagepack/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TransitionImagePackPlugin from 'phaser3-rex-plugins/templates/transitionimagepack/transitionimagepack-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTransitionImagePackPlugin',\nplugin: TransitionImagePackPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexTransitionImagePack(x, y, texture, frame, config);\n
"},{"location":"transitionimagepack/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TransitionImagePack from 'phaser3-rex-plugins/templates/transitionimagepack/TransitionImagePack.js';\n
  • Add image object
    var image = new TransitionImagePack(scene, x, y, texture, frame, config);\nscene.add.existing(image);\n
"},{"location":"transitionimagepack/#create-instance","title":"Create instance","text":"

var image = scene.add.rexTransitionImagePack(x, y, texture, frame, {   // duration: 1000,\n// width: undefined, height: undefined,\n});\n
or

var image = scene.add.rexTransitionImagePack(x, y, texture, frame, {\n// x: 0,\n// y: 0,\n// key: \n// frame: \n// duration: 1000,\n// width: undefined, height: undefined,\n});\n
  • duration : Duration of transition.
  • width, height : Scale images to fit this size (widthxheight).
    • undefined : Don't scale images.

Add transitionimage from JSON

var image = scene.make.rexTransitionImagePack({\nx: 0,\ny: 0,\nkey: null,\nframe: null,\n\n// duration: 1000,\n// width: undefined, height: undefined,\n\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
"},{"location":"transitionimagepack/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTransitionImagePack extends TransitionImagePack {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var transitionimage = new MyTransitionImagePack(scene, x, y, texture, frame, config);\n
"},{"location":"transitionimagepack/#transit","title":"Transit","text":"
image\n// .setDuration(duration)\n// .setEaseFunction(ease)\n.transit(texture, frame, modeName)\n

or

image.transit({\nkey: undefined,\n// frame: undefined,\n// duration: 1000,\n// ease: 'Linear',\nmode: modeName\n})\n
  • duration : Override default duration setting.
  • ease : Override default ease setting.
  • mode : Pre-build effects
    • Fade effects :
      • 'fade' : Tint old image to black, then tint new image from black to origin color.
      • 'crossFade' : Ease alpha of old image from 1 to 0, and ease alpha of new image from 0 to 1 at the same time.
    • Slide effects : 'slideLeft', 'slideRight', 'slideUp', 'slideDown', 'slideAwayLeft', 'slideAwayRight', 'slideAwayUp', 'slideAwayDown', 'pushLeft', 'pushRight', 'pushUp', 'pushDown'.
    • Zoom(scale) effects : 'zoomOut', 'zoomIn', 'zoomInOut'.
    • Mask effects : 'wipeLeft', 'wipeRight', 'wipeUp', 'wipeDown', 'irisOut', 'irisIn', 'irisInOut', 'pieOut', 'pieIn', 'pieInOut', 'blinds', 'squares', 'diamonds', 'circles', 'curtain'.
    • Shader effects : 'pixellate', 'dissolve', 'revealLeft', 'revealRight', 'revealUp', 'revealDown'
"},{"location":"transitionimagepack/#current-texture","title":"Current texture","text":"
var textureKey = image.texture.key;\nvar frameName = image.frame.name;\n
"},{"location":"transitionimagepack/#transition-duration","title":"Transition duration","text":"
  • Set
    image.setDuration(duration);\n
  • Get
    var duration = image.duration;\n
"},{"location":"transitionimagepack/#ease-function","title":"Ease function","text":"
  • Set
    image.setEaseFunction(ease);\n
    • ease : Ease function of transition-progress.
  • Get
    var ease = image.easeFunction;\n
"},{"location":"transitionimagepack/#pauseresume","title":"Pause/Resume","text":"
image.pause();\n
image.resume();\n
"},{"location":"transitionimagepack/#stop","title":"Stop","text":"
image.stop();\n

Also will fire 'complete' event.

"},{"location":"transitionimagepack/#events","title":"Events","text":"
  • On complete
    image.on('complete', function(){\n})\n
"},{"location":"transitionimagepack/#flip","title":"Flip","text":"
  • Flip
    image.flipX(value);\nimage.flipY(value);\nimage.flip(x, y);\n
  • Toggle
    image.toggleFlipX();\nimage.toggleFlipY();\n
"},{"location":"transitionimagepack/#other-properties","title":"Other properties","text":"

See transition image object, game object

"},{"location":"tween/","title":"Tween","text":""},{"location":"tween/#introduction","title":"Introduction","text":"

Change properties by tween equations, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"tween/#usage","title":"Usage","text":""},{"location":"tween/#create-tween-task","title":"Create tween task","text":"
var tween = scene.tweens.add({\ntargets: gameObject,\nx: 1,\n// x: '+=1',\n// x: '-=1',\n// x: '*=1',\n// x: '/=1',\n// x: 'random(0.25, 0.75)',\n// x: 'int(10, 100)',\n// x: [100, 300, 200, 600],\n// x: { from: 0, to: 1 },\n// x: { start: 0, to: 1 },  \n// x: { start: value0, from: value1, to: value2 },  \n// x: {\n//      getActive: function (target, key, value, targetIndex, totalTargets, tween) { return newValue; },\n//      getStart: function (target, key, value, targetIndex, totalTargets, tween) { return newValue; },\n//      getEnd: function (target, key, value, targetIndex, totalTargets, tween) { return newValue; }\n// },\nease: 'Linear',       // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\nrepeat: 0,            // -1: infinity\nyoyo: false,\n\n// interpolation: null,\n});\n
  • key: value2 : Tween to value2.
  • key: '+=deltaValue' : Tween to current value + deltaValue
    • Support these expressions : key: '+=deltaValue', key: '-=deltaValue', key: '*=deltaValue', key: '/=deltaValue'
  • key: 'random(10, 100)' : Tween to a random float value.
  • key: 'int(10, 100)' : Tween to a random int value.
  • key: [100, 300, 200, 600] : Use interpolation to determine the value.
  • key: { from: value1, to: value2 } : Set the property to value11 when tween started after delay, then tween to value2.
  • value1, value2 : A number, string, or callback(function(target, key, value, targetIndex, totalTargets, tween) { return newValue; })
  • key: { start: value0, to: value2 } : Set the property to value0 immediately, then tween to value2.
    • value1, value2 : A number, string, or callback(function(target, key, value, targetIndex, totalTargets, tween) { return newValue; })
  • key: { start: value0, from: value1, to: value2 } : Set the property to value0 immediately, then set to value1 when tween started after delay, then tween to value2.
    • value0, value1, value2 : A number, string, or callback(function(target, key, value, targetIndex, totalTargets, tween) { return newValue; })
  • key: function(target, key, value, targetIndex, totalTargets, tween) { return newValue; }
    • target :\u3000The tween target.
    • key : The target property.
    • value : The current value of the target property.
    • targetIndex : The index of the target within the Tween.
    • totalTargets : The total number of targets in this Tween.
    • tween : The Tween that invoked this callback.
  • key: { getActive:callback, getStart:callback, getEnd:callback}
    • callback : function(target, key, value, targetIndex, totalTargets, tween) { return newValue; }

or

var tween = scene.tweens.add({\ntargets: gameObject,\npaused: false,\ncallbackScope: tween,\n\n// timming/callback of each state\nonStart: function () {},\nonStartParams: [],\n\n// initial delay\ndelay: 0,  // function(target, targetKey, value, targetIndex, totalTargets, tween) { },\n\n// tween duration\nduration: 1000,\nease: 'Linear',\neaseParams: null,\n\nonActive: function () {},\nonUpdate: function (tween, target, key, current, previous, param) {},\nonUpdateParams: [],\n\n// delay between tween and yoyo\nhold: 0,\nyoyo: false,  // true to tween backward\nflipX: false,\nflipY: false,\nonYoyo: function (tween, target, key, current, previous, param) {},\nonYoyoParams: [],\n\n// repeat count (-1: infinite)\nrepeat: 0,\nonRepeat: function (tween, target, key, current, previous, param) {},\nonRepeatParams: [],\n// delay to next pass\nrepeatDelay: 0,\n\n// loop count (-1: infinite)\nloop: 0,\nonLoop: function () {},\nonLoopParams: [],\n// delay to next loop\nloopDelay: 0,\n\n// delay to onComplete callback\ncompleteDelay: 0,\nonComplete: function () {},\nonCompleteParams: [],\n// timming/callback of each state\n\nonStop: function () {}, onPause: function () {}, onResume: function () {}, // properties:\nx: '+=600',        // start from current value\ny: 500,\nrotation: ...\nangle: ...\nalpha: ...\n// ...\n\n// or\nprops: {\nx: { value: '+=600', duration: 3000, ease: 'Power2' },\ny: { value: '500', duration: 1500, ease: 'Bounce.easeOut' }\n},\n\n// or\nprops: {\nx: {\nduration: 400,\nyoyo: true,\nrepeat: 8,\nease: 'Sine.easeInOut',\nvalue: {\ngetActive: function (target, key, value, targetIndex, totalTargets, tween)\n{\nreturn value;\n},\ngetStart: function (target, key, value, targetIndex, totalTargets, tween)\n{\nreturn value + 30;\n},\ngetEnd: function (target, key, value, targetIndex, totalTargets, tween)\n{\ndestX -= 30;\nreturn destX;\n}\n}\n},\n....\n},\n\npersist: false,\n\ninterpolation: null,\ninterpolationData: null,\n\n});\n
  • targets : The targets the tween is updating.
  • delay : The time the tween will wait before it first starts
    • A number, for all targets
    • A callback function, built via stagger builder :
      • From 0 to endValue :
        • scene.tweens.stagger(endValue)
      • From startValue to endValue :
        • scene.tweens.stagger([startValue, endValue])
      • From 0 to endValue, with specific ease function :
        • scene.tweens.stagger(endValue, {ease: 'cubic.inout'})
      • From startValue to endValue, with specific ease function :
        • scene.tweens.stagger([startValue, endValue], {ease: 'cubic.inout'})
      • From 0 to endValue, with specific start index :
        • scene.tweens.stagger(endValue, {from: 'last'})
        • scene.tweens.stagger(endValue, {from: 'center'})
        • scene.tweens.stagger(endValue, {from: index})
      • From startValue to endValue, , with specific start index :
        • scene.tweens.stagger([startValue, endValue], {from: 'last'})
        • scene.tweens.stagger([startValue, endValue], {from: 'center'})
        • scene.tweens.stagger([startValue, endValue], {from: index})
      • From 0 to endValue, with specific ease function, with specific start index :
        • scene.tweens.stagger(endValue, {from: 'last', ease: 'cubic.inout'})
      • From startValue to endValue, with specific ease function , with specific start index :
        • scene.tweens.stagger([startValue, endValue], {from: 'last', ease: 'cubic.inout'})
      • Grid mode. From 0 to endValue.
        • scene.tweens.stagger(endValue, {grid: [gridWidth, gridHeight], })
        • scene.tweens.stagger(endValue, {grid: [gridWidth, gridHeight], from: 'center'})
        • scene.tweens.stagger(endValue, {grid: [gridWidth, gridHeight], from: 'center', ease: 'cubic.inout'})
      • Grid mode. From startValue to endValue.
        • scene.tweens.stagger([startValue, endValue], {grid: [gridWidth, gridHeight], })
        • scene.tweens.stagger([startValue, endValue], {grid: [gridWidth, gridHeight], from: 'center'})
        • scene.tweens.stagger([startValue, endValue], {grid: [gridWidth, gridHeight], from: 'center', ease: 'cubic.inout'})
  • duration : The duration of the tween
  • ease : The ease function used by the tween
  • easeParams : The parameters to go with the ease function (if any)
  • hold : The time the tween will pause before running a yoyo
  • repeat : The number of times the tween will repeat itself (a value of 1 means the tween will play twice, as it repeated once)
  • repeatDelay : The time the tween will pause for before starting a repeat. The tween holds in the start state.
  • yoyo : boolean - Does the tween reverse itself (yoyo) when it reaches the end?
  • flipX : flip X the GameObject on tween end
  • flipY : flip Y the GameObject on tween end
  • completeDelay : The time the tween will wait before the onComplete event is dispatched once it has completed
  • loop : -1 for an infinite loop
  • loopDelay
  • paused : Does the tween start in a paused state, or playing?
  • props : The properties being tweened by the tween
  • onActive : Tween becomes active within the Tween Manager.
    function(tween, target) { }\n
  • onStart : A tween starts.
    function(tween, targets) { }\n
  • onUpdate : Callback which fired when tween task updated
    function(tween, target, key, current, previous, param) { }\n
  • onComplete : Tween completes or is stopped.
    function(tween, targets) { }\n
  • onYoyo : A function to call each time the tween yoyos. Called once per property per target.
    function(tween, target, key, current, previous, param) { }\n
  • onLoop : A function to call each time the tween loops.
    function(tween, targets) { }\n
  • onRepeat : A function to call each time the tween repeats. Called once per property per target.
    function(tween, target, key, current, previous, param) { }\n
  • onStop : A function to call when the tween is stopped.
    function(tween, targets) { }\n
  • onPause : A function to call when the tween is paused.
    function(tween, targets) { }\n
  • onResume : A function to call when the tween is resumed after being paused.
    function(tween, targets) { }\n
  • persist : Will the Tween be automatically destroyed on completion, or retained for future playback?
  • interpolation : The interpolation function to use if the value given is an array of numbers.
    • 'linear', 'bezier', 'catmull' (or 'catmullrom')

Note

Tween task will not manipulate any property that begins with an underscore.

"},{"location":"tween/#ease-equations","title":"Ease equations","text":"
  • Power0 : Linear
  • Power1 : Quadratic.Out
  • Power2 : Cubic.Out
  • Power3 : Quartic.Out
  • Power4 : Quintic.Out
  • Linear
  • Quad : Quadratic.Out
  • Cubic : Cubic.Out
  • Quart : Quartic.Out
  • Quint : Quintic.Out
  • Sine : Sine.Out
  • Expo : Expo.Out
  • Circ : Circular.Out
  • Elastic : Elastic.Out
  • Back : Back.Out
  • Bounce : Bounce.Out
  • Stepped
  • Quad.easeIn
  • Cubic.easeIn
  • Quart.easeIn
  • Quint.easeIn
  • Sine.easeIn
  • Expo.easeIn
  • Circ.easeIn
  • Back.easeIn
  • Bounce.easeIn
  • Quad.easeOut
  • Cubic.easeOut
  • Quart.easeOut
  • Quint.easeOut
  • Sine.easeOut
  • Expo.easeOut
  • Circ.easeOut
  • Back.easeOut
  • Bounce.easeOut
  • Quad.easeInOut
  • Cubic.easeInOut
  • Quart.easeInOut
  • Quint.easeInOut
  • Sine.easeInOut
  • Expo.easeInOut
  • Circ.easeInOut
  • Back.easeInOut
  • Bounce.easeInOut

Demo

"},{"location":"tween/#pause-resume-task","title":"Pause / Resume task","text":"
tween.pause();\n
tween.resume();\n
"},{"location":"tween/#stop-task","title":"Stop task","text":"
tween.complete();\n
tween.stop();\n

Won't invoke onComplete callback ('complete' event)

"},{"location":"tween/#play-task","title":"Play task","text":"
tween.play();\n
"},{"location":"tween/#restart-task","title":"Restart task","text":"
tween.restart();\n
"},{"location":"tween/#seek","title":"Seek","text":"
tween.seek(amount);\n// tween.seek(amount, delta, emit);\n
  • amount : The number of milliseconds to seek into the Tween from the beginning.
  • delta : The size of each step when seeking through the Tween. Default value is 16.6 (1000/60)
  • emit : While seeking, should the Tween emit any of its events or callbacks? The default is false.
"},{"location":"tween/#remove-task","title":"Remove task","text":"

Removes this Tween from the TweenManager

tween.remove();\n
"},{"location":"tween/#destroy-task","title":"Destroy task","text":"

Free tween task from memory

tween.destroy();\n

Note

A Tween that has been destroyed cannot ever be played or used again.

"},{"location":"tween/#get-tweens","title":"Get tweens","text":"
  • Tweens of a target
    var tweens = scene.tweens.getTweensOf(target);\n// var tweens = scene.tweens.getTweensOf(target, includePending);\n
    • tweens : Array of tweens, or timelines.
    • includePending : Set true to search pending tweens.
  • All tweens
    var tweens = scene.tweens.getTweens();\n
"},{"location":"tween/#destroy-task-of-a-target","title":"Destroy task of a target","text":"
scene.tweens.killTweensOf(target);\n
  • target : The target to kill the tweens of. Provide an array to use multiple targets.
"},{"location":"tween/#time-scale","title":"Time-scale","text":"
tween.setTimeScale(v);\n// tween.timeScale = timescale;\n
var timeScale = tween.getTimeScale();\n// var timeScale = tween.timeScale;\n
"},{"location":"tween/#global-time-scale","title":"Global time-scale","text":"
var timeScale = scene.tweens.timeScale;\n
scene.tweens.timeScale = timescale;\n
"},{"location":"tween/#events","title":"Events","text":"
  • Tween becomes active within the Tween Manager.
    tween.on('active', function(tween, targets){\n\n}, scope);\n
  • Tween completes or is stopped.
    tween.on('complete', function(tween, targets){\n\n}, scope);\n
  • A tween loops, after any loop delay expires.
    tween.on('loop', function(tween, targets){\n\n}, scope);\n
  • A tween property repeats, after any repeat delay expires.
    tween.on('repeat', function(tween, key, target){\n\n}, scope);\n
  • A tween starts.
    tween.on('start', function(tween, targets){\n\n}, scope);\n
  • A tween property updates.
    tween.on('update', function(tween, key, target, current, previous){\n\n}, scope);\n
    • tween : A reference to the Tween instance that emitted the event.
    • key : The property that was updated, i.e. x or scale.
    • target : The target object that was updated. Usually a Game Object, but can be of any type.
    • current : The current value of the property that was tweened.
    • previous : The previous value of the property that was tweened, prior to this update.
  • A tween property pause.
    tween.on('pause', function(tween, key, target){\n\n}, scope);\n
  • A tween property resume.
    tween.on('resume', function(tween, key, target){\n\n}, scope);\n
  • A tween property yoyos.
    tween.on('yoyo', function(tween, key, target){\n\n}, scope);\n
  • A tween stopped.
    tween.on('stop', function(tween, targets){\n\n}, scope);\n
"},{"location":"tween/#set-callbacks","title":"Set callbacks","text":"
tween.setCallback(type, callback, param);\n
  • type :
    • 'onActive' : When the Tween is first created it moves to an 'active' state when added to the Tween Manager. 'Active' does not mean 'playing'.
    • 'onStart' : When the Tween starts playing after a delayed or paused state. This will happen at the same time as onActive if the tween has no delay and isn't paused.
    • 'onLoop' : When a Tween loops, if it has been set to do so. This happens after the loopDelay expires, if set.
    • 'onComplete' : When the Tween finishes playback fully. Never invoked if the Tween is set to repeat infinitely.
    • 'onStop' : Invoked only if the Tween.stop method is called.
    • 'onPause' : Invoked only if the Tween.pause method is called. Not invoked if the Tween Manager is paused.
    • 'onResume' : Invoked only if the Tween.resume method is called. Not invoked if the Tween Manager is resumed.
    • 'onYoyo' : When a TweenData starts a yoyo. This happens after the hold delay expires, if set.
    • 'onRepeat' : When a TweenData repeats playback. This happens after the repeatDelay expires, if set.
    • 'onUpdate' : When a TweenData updates a property on a source target during playback.
  • callback :
    • 'onRepeat', 'onUpdate', 'onYoyo'
      function(tween, targets, key, current, previous, param) {\n\n}\n
    • 'onActive', 'onLoop', 'onPause', 'onResume', 'onComplete', 'onStart', 'onStop',
      function(tween, targets, param) {\n\n}\n
"},{"location":"tween/#state","title":"State","text":"
  • Is playing
    var isPlaying = tween.isPlaying();\n
  • Is paused
    var isPaused = tween.isPaused();\n
  • Is actively and not just in a delayed state
    var hasStarted = tween.hasStarted;\n
"},{"location":"tween/#custom-ease-function","title":"Custom ease function","text":"
var tween = scene.tweens.add({\ntargets: gameObject,\n// ...\nease: function (t) {  // t: 0~1\nreturn value;     // value: 0~1\n},\n// ...\n});\n
"},{"location":"tween/#has-target","title":"Has target","text":"
var hasTarget = tween.hasTarget(gameObject);\n
"},{"location":"tween/#tween-value","title":"Tween value","text":"
  • Create tween task
    var tween = scene.tweens.addCounter({\nfrom: 0,\nto: 1,\nease: 'Linear',       // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\nrepeat: 0,            // -1: infinity\nyoyo: false,\nonUpdate(tween, targets, key, current, previous, param) {\n// var value = current;\n// var value = tween.getValue();\n}\n});\n
    • More config parameters...
  • Get value
    var value = tween.getValue();\n
"},{"location":"tween/#chain","title":"Chain","text":""},{"location":"tween/#create-chain","title":"Create chain","text":"
var chain = scene.tweens.chain({\ntargets: null,\ntweens: [\n{\n// targets: gameObject,\nalpha: 1,            ease: 'Linear',       // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\nrepeat: 0,            // -1: infinity\nyoyo: false\n},        // ...\n],\n\ndelay: 0,\ncompleteDelay: 0,\nloop: 0,  // repeat: 0,\nrepeatDelay: 0,\npaused: false,\npersist: true,\n// callbackScope: this,\n})\n
  • targets, or tweenConfig.targets
  • tweens : Array of tween config
"},{"location":"tween/#pause-resume-chain","title":"Pause / Resume chain","text":"
chain.pause();\n
chain.resume();\n
"},{"location":"tween/#restart-chain","title":"Restart chain","text":"
chain.restart();\n
"},{"location":"tween/#add-tween-task","title":"Add tween task","text":"
chain.add({\ntargets: gameObject,\nalpha: 1,\nease: 'Linear',       // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\nrepeat: 0,            // -1: infinity\nyoyo: false\n})\n

or

chain.add([tweenConfig0, tweenConfig1, ...]);\n
"},{"location":"tween/#remove-tween-task","title":"Remove tween task","text":"
chain.remove(tweenTask);\n
"},{"location":"tween/#has-target_1","title":"Has target","text":"
var hasTarget = chain.hasTarget(gameObject);\n
"},{"location":"tween/#flow-chart","title":"Flow chart","text":"
graph TB\n\nStart((Start)) --> CallbackOnStart\nCallbackOnStart>\"Callback: onStart\"] --> ActiveDelay((\"delay\"))\nActiveDelay --> DurationForward\n\nDurationForward((\"Tween forward<br>Callback: onUpdate<br>(duration)\")) --> Hold[\"hold\"]\nHold((hold)) --> IsYoyo{Is yoyo}\nIsYoyo --> |Yes| CallbackOnYoyo>\"Callback: onYoyo\"]\nCallbackOnYoyo --> DurationBackward((\"Tween backword<br>Callback: onUpdate<br>(duration)\"))\nDurationBackward --> IsRepeat{\"Repeat count > 0\"}\nIsYoyo --> |No| IsRepeat\nIsRepeat --> |Yes| CallbackOnRepeat>\"Callback: onRepeat\"]\nCallbackOnRepeat --> RepeatDelay((\"repeatDelay\"))\nRepeatDelay --> DurationForward\n\nIsRepeat --> |No| IsLoop{\"Loop count > 0\"}\n\nIsLoop --> |Yes| CallbackOnLoop\nCallbackOnLoop>\"Callback: onLoop\"] --> LoopDelay((\"loopDelay\"))\nLoopDelay --> DurationForward\n\nIsLoop --> |No| CompleteDelay\nCompleteDelay((\"completeDelay\")) --> CallbackOnComplete>\"Callback: onComplete\"]\nCallbackOnComplete --> End((End))
"},{"location":"tween/#tween-data","title":"Tween data","text":"
  • tween.data : An array of TweenData objects, each containing a unique property and target being tweened.
    • tween.data[i].key : The property of the target to tween.
    • tween.data[i].start, tween.data[i].end, tween.data[i].current : Ease Value Data.
"},{"location":"ui-badgelabel/","title":"Badge label","text":""},{"location":"ui-badgelabel/#introduction","title":"Introduction","text":"

A container with badges above a main item.

  • Author: Rex
  • Game object
"},{"location":"ui-badgelabel/#live-demos","title":"Live demos","text":"
  • Badge
"},{"location":"ui-badgelabel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-badgelabel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-badgelabel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add badge-label object
    var badgeLabel = scene.rexUI.add.badgeLabel(config);\n
"},{"location":"ui-badgelabel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add badge-label object
    var badgeLabel = scene.rexUI.add.badgeLabel(config);\n
"},{"location":"ui-badgelabel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { BadgeLabel } from 'phaser3-rex-plugins/templates/ui/uiComponents.js';\n
  • Add badge-label object
    var badgeLabel = new BadgeLabel(scene, config);\nscene.add.existing(badgeLabel);\n
"},{"location":"ui-badgelabel/#add-badgelabel-object","title":"Add badgeLabel object","text":"
var badgeLabel = scene.rexUI.add.badgeLabel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\nmain: mainItemGameObject,\n\nleftTop: leftTopBadgeGameObject,\ncenterTop: centerTopBadgeGameObject,\nrightTop: rightTopBadgeGameObject,\nleftCenter: leftCenterBadgeGameObject,\ncenter: centerBadgeGameObject,\nrightCenter: rightCenterBadgeGameObject,\nleftBottom: leftBottomBadgeGameObject,\ncenterBottom: centerBottomBadgeGameObject,\nrightBottom: rightBottomBadgeGameObject,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of badgeLabel.
  • main : Game object of main item, optional.
  • leftTop : Badge game object at leftTop side, optional.
  • centerTop : Badge game object at centerTop side, optional.
  • rightTop : Badge game object at rightTop side, optional.
  • leftCenter : Badge game object at leftCenter side, optional.
  • center : Badge game object at center side, optional.
  • rightCenter : Badge game object at rightCenter side, optional.
  • leftBottom : Badge game object at leftBottom side, optional.
  • centerBottom : Badge game object at centerBottom side, optional.
  • rightBottom : Badge game object at rightBottom side, optional.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
      • Positive number : Indent badge game objects inside background.
      • Negative number : Exceed badge game objects out of background.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-badgelabel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyBadgeLabel extends RexPlugins.UI.BadgeLabel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var badgeLabel = new MyBadgeLabel(scene, config);\n
"},{"location":"ui-badgelabel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

badgeLabel.layout();\n

See also - dirty

"},{"location":"ui-badgelabel/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = badgeLabel.getElement('background');\n
    • Main item game object
      var item = badgeLabel.getElement('main');\n
    • LeftTop badge game object
      var badge = badgeLabel.getElement('leftTop');\n
    • CenterTop badge game object
      var badge = badgeLabel.getElement('centerTop');\n
    • RightTop badge game object
      var badge = badgeLabel.getElement('rightTop');\n
    • LeftCenter badge game object
      var badge = badgeLabel.getElement('leftCenter');\n
    • Center badge game object
      var badge = badgeLabel.getElement('center');\n
    • RightCenter badge game object
      var badge = badgeLabel.getElement('rightCenter');\n
    • LeftBottom badge game object
      var badge = badgeLabel.getElement('leftBottom');\n
    • CenterBottom badge game object
      var badge = badgeLabel.getElement('centerBottom');\n
    • RightBottom badge game object
      var badge = badgeLabel.getElement('rightBottom');\n
  • Get by name
    var gameObject = badgeLabel.getElement('#' + name);\n// var gameObject = badgeLabel.getElement('#' + name, recursive);\n
    or
    var gameObject = badgeLabel.getByName(name);\n// var gameObject = badgeLabel.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-badgelabel/#other-properties","title":"Other properties","text":"

See overlap sizer object, base sizer object, container-lite.

"},{"location":"ui-basesizer/","title":"Base sizer","text":""},{"location":"ui-basesizer/#introduction","title":"Introduction","text":"

Base class of all ui plugins.

  • Author: Rex
"},{"location":"ui-basesizer/#usage","title":"Usage","text":""},{"location":"ui-basesizer/#background","title":"Background","text":"
sizer.addBackground(gameObject);\n// sizer.addBackground(gameObject, key);\n// sizer.addBackground(gameObject, paddingConfig, key);\n
  • gameObject : Background game object will be resized after sizer.layout() method.
    • Round rectangle game object
      var gameObject = scene.rexUI.add.roundRectangle(x, y, width, height, radius, fillColor);\n
    • Nine-slice game object
      var gameObject = scene.add.nineslice(x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight);\n
      or
      var gameObject = scene.make.nineslice({\nkey: key, frame: frameName,\nleftWidth: 0, rightWidth: 0,\ntopHeight: 0, bottomHeight: 0\n});\n
    • Nine-patch game object
      var gameObject = scene.rexUI.add.ninePatch(x, y, width, height, key, columns, rows, config);\n
    • Custom game object which has resize(width, height) method.
      • Display width, display height will be changed if this background game object does not have resize method.
  • paddingConfig : Add space between bounds. Default is 0.
    • A number for left/right/top/bottom bounds,
    • Or a plain object.
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • key : A string key. Get background game object back via
    var child = sizer.getElement(key);\n

A sizer can have more than one background. i.e. user can invoke sizer.addBackground(gameObject) many times.

"},{"location":"ui-basesizer/#remove-background","title":"Remove background","text":"
  • Remove background child
    sizer.removeBackground(gameObject);\n
  • Remove background child and destroy it
    sizer.removeBackground(gameObject, true);\n
  • Remove all background children
    sizer.removeAllBackgrounds();\n
  • Remove all background children and destroy them
    sizer.removeAllBackgrounds(true);\n
"},{"location":"ui-basesizer/#depth-of-background","title":"Depth of background","text":"

Send this background child to bottom of sizer.

sizer.sendChildToBack(gameObject);\n
"},{"location":"ui-basesizer/#minimum-size","title":"Minimum size","text":"
  • Get
    var minWidth = sizer.minWidth;\nvar minHeight = sizer.minHeight;\n
  • Set
    sizer.setMinSize(width, height);\n
    or
    sizer.setMinWidth(width);\nsizer.setMinHeight(height);\n

Resize top-most sizer

sizer.setMinSize(width, height).layout()\n
"},{"location":"ui-basesizer/#dirty","title":"Dirty","text":"

Don't layout this sizer if sizer.dirty is false. i.e. Size of this sizer won't be changed, but won't layout children neither.

Default value is true.

  • Get
    var dirty = sizer.dirty;\n
  • Set
    sizer.setDirty();\n// sizer.setDirty(true);\n
    or
    sizer.dirty = true;\n
  • Clear
    sizer.setDirty(false);\n
    or
    sizer.dirty = false;\n
"},{"location":"ui-basesizer/#bounds-of-sizer","title":"Bounds of sizer","text":"
  • Get
    var leftBound = sizer.left;\nvar rightBound = sizer.right;\nvar topBound = sizer.top;\nvar bottomBound = sizer.bottom;\nvar centerX = sizer.centerX;\nvar centerY = sizer.centerY;\n
  • Set
    sizer.left = leftBound;\nsizer.right = rightBound;\nsizer.top = topBound;\nsizer.bottom = bottomBound;\nsizer.centerX = centerXBound;\nsizer.centerY = centerYBound;\n
    or
    sizer.alignLeft(leftBound);\nsizer.alignRight(rightBound);\nsizer.alignTop(topBound);\nsizer.alignBottom(bottomBound);\nsizer.alignCenterX(centerXBound);\nsizer.alignCenterY(centerYBound);\n
"},{"location":"ui-basesizer/#size-of-sizer","title":"Size of sizer","text":"
  • Size
    var width = sizer.width;\nvar height = sizer.height;\n
  • Display size
    var displayWidth = sizer.displayWidth;\nvar displayHeight = sizer.displayHeight;\n
  • Inner size
    var innerWidth = sizer.innerWidth;\nvar innerHeight = sizer.innerHeight;\n
  • Minimum size
    var minWidth = sizer.minWidth;\nvar minHeight = sizer.minHeight;\n
  • Minimum inner size
    var minInnerWidth = sizer.minInnerWidth;\nvar minInnerHeight = sizer.minInnerHeight;\n
"},{"location":"ui-basesizer/#push-into-bounds","title":"Push into bounds","text":"

Align sizer to bound if overlapping it.

sizer.pushIntoBounds();\n

or

sizer.pushIntoBounds(bounds);\n
  • bounds : Bounds in rectangle object.
"},{"location":"ui-basesizer/#scale","title":"Scale","text":"
  • Scale up from 0 to current scale of game object.
    • Pop-up width and height
      sizer\n//.setScale(scaleX, scaleY)\n.popUp(duration);\n\n// sizer.popUp(duration, undefined, ease);\n
      or
      sizer\n//.setScale(scaleX, scaleY)\n.popUpPromise(duration)\n.then(function() {\n// ....\n})\n
      • ease : Ease function, default is 'Cubic'.
    • Pop-up width only
      sizer\n//.setScaleX(scaleX)\n.popUp(duration, 'x');\n\n// sizer.popUp(duration, 'x', ease);\n
      or
      sizer\n//.setScaleX(scaleX)\n.popUpPromise(duration, 'x')\n.then(function() {\n// ....\n})\n
    • Pop-up height only
      sizer\n//.setScaleY(scaleY)\n.popUp(duration, 'y');\n\n// sizer.popUp(duration, 'y', ease);\n
      or
      sizer\n//.setScaleY(scaleY)\n.popUpPromise(duration, 'y')\n.then(function() {\n// ....\n})\n
    • Pop-up via config
      sizer\n//.setScale(scaleX, scaleY)\n.popUp({\nduration: undefined,\norientation: undefined,\nease: undefined,\n})\n
      or
      sizer\n//.setScale(scaleX, scaleY)\n.popUpPromise(config)\n.then(function() {\n// ....\n})\n
      • orientation : undefined, x, or y
  • Scale-down destroy
    • Scale-down width and height
      sizer.scaleDownDestroy(duration);\n// sizer.scaleDownDestroy(duration, undefined, ease);\n
      or
      sizer.scaleDownDestroyPromise(duration)\n.then(function() {\n// ....\n})\n
      • ease : Ease function, default is 'Linear'.
    • Scale-down width only
      sizer.scaleDownDestroy(duration, 'x');\n// sizer.scaleDownDestroy(duration, 'x', ease);\n
      or
      sizer.scaleDownDestroyPromise(duration, 'x');\n.then(function() {\n// ....\n})\n
    • Scale-down height only
      sizer.scaleDownDestroy(duration, 'y');\n// sizer.scaleDownDestroy(duration, 'y', ease);\n
      or
      sizer.scaleDownDestroyPromise(duration, 'y')\n.then(function() {\n// ....\n})\n
  • Scale-down without destroy
    • Scale-down width and height
      sizer.scaleDown(duration);\n// sizer.scaleDown(duration, undefined, ease);\n
      or
      sizer.scaleDownPromise(duration, undefined, ease)\n.then(function() {\n// ....\n})\n
    • Scale-down width only
      sizer.scaleDowny(duration, 'x');\n// sizer.scaleDowny(duration, 'x', ease);\n
      or
      sizer.scaleDownPromise(duration, 'x', ease)\n.then(function() {\n// ....\n})\n
    • Scale-down height only
      sizer.scaleDown(duration, 'y');\n// sizer.scaleDown(duration, 'y', ease);\n
      or
      sizer.scaleDownPromise(duration, 'y', ease)\n.then(function() {\n// ....\n})\n
  • Scale up/down, then scale back (yoyo)
    • Scale up/down, then scale back width and height
      sizer\n//.setScale(scaleX, scaleY)\n.scaleYoyo(duration, peakValue);\n\n// sizer.scaleYoyo(duration, peakValue, repeat, undefined, ease);\n
      or
      sizer\n//.setScale(scaleX, scaleY)\n.scaleYoyoPromise(duration, peakValue, repeat)\n.then(function() {\n// ....\n})\n
      • peakValue : Scale to this peak value, then scale back
      • repeat : Yoyo repeat, default value is 0.
      • ease : Ease function, default is 'Cubic'.
    • Scale up/down, then scale back width only
      sizer\n//.setScaleX(scaleX)\n.scaleYoyo(duration, peakValue, 0, 'x');\n\n// sizer.popUp(duration, peakValue, repeat, 'x', ease);\n
      or
      sizer\n//.setScaleX(scaleX)\n.scaleYoyoPromise(duration, peakValue, repeat, 'x')\n.then(function() {\n// ....\n})\n
    • Scale up/down, then scale back height only
      sizer\n//.setScaleY(scaleY)\n.scaleYoyo(duration, peakValue, 0, 'y');\n\n// sizer.popUp(duration, peakValue, repeat, 'y', ease);\n
      or
      sizer\n//.setScaleY(scaleY)\n.scaleYoyoPromise(duration, peakValue, repeat, 'y')\n.then(function() {\n// ....\n})\n
    • Scale up/down via config
      sizer\n//.setScale(scaleX, scaleY)\n.scaleYoyo({\nduration: undefined,\npeakValue: 1.2,\nrepeat: 0,\norientation: undefined,\nease: undefined,\n})\n
      or
      sizer\n//.setScale(scaleX, scaleY)\n.scaleYoyoPromise(config)\n.then(function() {\n// ....\n})\n
      • orientation : undefined, x, or y
  • Events
    • Pop-up complete
      sizer.on('popup.complete', function(sizer) { });\n
    • Scale-down, scale-down destroy complete
      sizer.on('scaledown.complete', function(sizer) { });\n
    • Scale up/down, then scale back (yoyo)
      sizer.on('scaleyoyo.complete', function(sizer) { });\n
"},{"location":"ui-basesizer/#fade","title":"Fade","text":"
  • Fade-in
    sizer.fadeIn(duration);\n
    or
    sizer.fadeIn(duration, endAlpha);\n
    or
    sizer.fadeIn(duration, {start:0, end:1});\n
    or
    sizer.fadeInPromise(duration, endAlpha)\n.then(function(){\n// ...\n})\n
    or
    sizer.fadeInPromise(duration, {start:0, end:1})\n.then(function(){\n// ...\n})\n
  • Fade-out destroy
    sizer.fadeOutDestroy(duration);\n
    or
    sizer.fadeOutDestroyPromise(duration)\n.then(function(){\n// ...\n})\n
  • Fade-out without destroy
    sizer.fadeOut(duration);\n
    or
    sizer.fadeOutPromise(duration)\n.then(function(){\n// ...\n})\n
  • Events
    • Fade-in complete
      sizer.on('fadein.complete', function(sizer) { });\n
    • Fade-out, fade-out destroy complete
      sizer.on('fadeout.complete', function(sizer) { });\n
"},{"location":"ui-basesizer/#ease-move","title":"Ease move","text":"
  • Move from
    sizer.moveFrom(duration, x, y);\n// sizer.moveFrom(duration, x, y, ease);\n// sizer.moveFrom({x, y, duration, ease});\n// sizer.moveFrom({x, y, speed, ease});\n
    or
    sizer\n.moveFromPromise(duration, x, y, ease)\n// .moveFromPromise({x, y, duration, ease})\n// .moveFromPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
    • x, y : Start position.
      • Number : Start position x/y.
      • String(+=300) : Related position of current position x/y.
      • undefined : Current position x/y.
    • speed : Get duration according to speed and distance between current sizer position to {x, y}
    • ease : 'Linear', 'Cubic', 'Elastic', 'Bounce', 'Back' ...
  • Move-from destroy
    sizer.moveFromDestroy(duration, x, y);\n// sizer.moveFrom(duration, x, y, ease);\n// sizer.moveFrom({x, y, duration, ease});\n// sizer.moveFrom({x, y, speed, ease});\n
    or
    sizer\n.moveFromDestroyPromise(duration, x, y, ease)\n// .moveFromDestroyPromise({x, y, duration, ease})\n// .moveFromDestroyPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
  • Move to
    sizer.moveTo(duration, x, y);\n// sizer.moveTo(duration, x, y, ease);\n// sizer.moveTo({x, y, duration, ease});\n// sizer.moveTo({x, y, speed, ease});\n
    or
    sizer\n.moveToPromise(duration, x, y, ease)\n// .moveToPromise({x, y, duration, ease})\n// .moveToPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
    • x, y : End position.
      • Number : End position x/y.
      • String(+=300) : Related position of current position x/y.
      • undefined : Current position x/y.
    • speed : Get duration according to speed and distance between current sizer position to {x, y}
    • ease : 'Linear', 'Cubic', 'Elastic', 'Bounce', 'Back' ...
  • Move-to destroy
    sizer.moveToDestroy(duration, x, y);\n// sizer.moveTo(duration, x, y, ease);\n// sizer.moveTo({x, y, duration, ease});\n// sizer.moveTo({x, y, speed, ease});\n
    or
    sizer\n.moveToDestroyPromise(duration, x, y, ease)\n// .moveToDestroyPromise({x, y, duration, ease})\n// .moveToDestroyPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
  • Move-stop
    sizer.moveStop();\n// sizer.moveStop(true);  // Set to end position\n
  • Events
    • Move-from complete
      sizer.on('movefrom.complete', function(sizer) { });\n
    • Move-to complete
      sizer.on('moveto.complete', function(sizer) { });\n
"},{"location":"ui-basesizer/#shake","title":"Shake","text":"
  • Start
    sizer.shake(duration);\n// sizer.shake(duration, magnitude);\n
    or
    sizer.shakePromise(duration, magnitude)\n.then(function(){\n// ...\n})\n
  • Events
    • Shake complete
      sizer.on('shake.complete', function(sizer) { });\n
"},{"location":"ui-basesizer/#ease-data","title":"Ease data","text":"
  • Start
    sizer.easeDataTo(key, value, duration);\n// sizer.easeDataTo(key, value, duration, ease);\n// sizer.easeDataTo({ key, value, duration, ease });\n// sizer.easeDataTo({ key, value, speed, ease });\n
    or
    sizer.easeDataToPromise(key, value, duration, ease)\n.then(function(){\n// ...\n})\n
  • Stop
    sizer.stopEaseData(key);           // Set to end value\n// sizer.stopEaseData(key, false); // Stop at current value\n
    or
    sizer.stopAllEaseData();           // Set to end value\n// sizer.stopAllEaseData(false);   // Stop at current value\n
  • Events
    • Easing complete
      sizer.on('easedata.' + key + '.complete', function(sizer) { });\n
      sizer.on('easedata.complete', function(key, sizer) { });\n
"},{"location":"ui-basesizer/#delay-call","title":"Delay call","text":"
sizer.delayCall(delay, callback, scope);\n

Timer will be removed when destroying game object.

"},{"location":"ui-basesizer/#modal","title":"Modal","text":"
  1. Assign sizer.onCreateModalBehavior callback, or register events to close modal sizer directly.
    • onCreateModalBehavior :
      sizer.onCreateModalBehavior = function(sizer, config) {\n// ...\nsizer.modalClose(data);\n}\n
      • config : Passed from sizer.modal(config)
    • Close modal sizer
      sizer.modalClose(data);\n
  2. Pop this modal sizer
    sizer.modal(onClose);  // Use default modal config\n
    or
    sizer.modal({\n// cover: {\n//     color: 0x0,\n//     alpha: 0.8,\n//     transitIn: function(gameObject, duration) { },\n//     transitOut: function(gameObject, duration) { },\n// },\n// cover: false, \n\n// When to close modal dialog?\n// touchOutsideClose: false,\n// anyTouchClose: false,\n// timeOutClose: false,\n// manualClose: false,\n\n// duration: {\n//     in: 200,\n//     hold: 2000,\n//     out: 200\n// }\n\n// transitIn: 0,\n// transitOut: 0,\n\n// destroy: true\n}, onClose);\n
    or
    sizer\n.modalPromise(config)\n.then(function(data){\n\n})\n
    • config : See Modal behavior
    • onClose : Callback when closing modal dialog
      function(data) {      }\n
      • data : Object passed from sizer.modalClose(data).
"},{"location":"ui-basesizer/#set-properties-of-child","title":"Set properties of child","text":"
sizer.setChildPosition(child, x, y);\nsizer.setChildRotation(child, rotation);\nsizer.setChildScale(child, scaleX, scaleY);\nsizer.setChildDisplaySize(child, width, height);\nsizer.setChildVisible(child, visible);\nsizer.setChildAlpha(child, alpha);\n
"},{"location":"ui-basesizer/#depth","title":"Depth","text":"
  • Get depth of sizer
    var depth = sizer.depth;\n
  • Set depth of sizer
    sizer.setDepth(value, true);\n// sizer.depth = depth;\n
  • Set depth of sizer and all children
    sizer.setDepth(value);\n
  • Bring this sizer and its children to top
    sizer.bringToTop();\n
  • Swap depth with another sizer
    sizerA.swapDepth(sizerB);\n
  • Increase of sizer and all children
    sizer.incDepth(value);\n
  • Move game object below this sizer and all children
    sizer.moveDepthBelow(gameObject);\n
  • Move game object above this sizer and all children
    sizer.moveDepthAbove(gameObject);\n
  • Bring a child of this sizer to top
    sizer.bringChildToTop(gameObject);\n
  • Send a child of this sizer to bottom
    sizer.sendChildToBack(gameObject);\n
"},{"location":"ui-basesizer/#scroll-factor","title":"Scroll factor","text":"
  • Set scroll factor to children
    sizer.setScrollFactor(x, y);\n
"},{"location":"ui-basesizer/#change-origin","title":"Change origin","text":"
sizer.changeOrigin(originX, originY);\n

This method also will reset all local state of children.

"},{"location":"ui-basesizer/#destroy","title":"Destroy","text":"
sizer.destroy();\n
"},{"location":"ui-basesizer/#drag-sizer","title":"Drag sizer","text":"
  • Drag top-most sizer by child
    • Enable
      sizer.setDraggable(child);\n// sizer.setDraggable(child, true);\n
      or
      sizer.setDraggable(elementName);\n// sizer.setDraggable(elementName, true);\n
    • Disable
      sizer.setDraggable(child, false);\n
      or
      sizer.setDraggable(elementName, false);\n
  • Drag top-most sizer by this sizer
    • Enable
      sizer.setDraggable();\n// sizer.setDraggable(true);\n
    • Disalbe
      sizer.setDraggable(false);\n
  • Drag target sizer by child
    • Enable
      sizer.setDraggable(child, targetSizer);\n// sizer.setDraggable(child, true, targetSizer);\n
      or
      sizer.setDraggable(elementName);\n// sizer.setDraggable(elementName, true, targetSizer);\n
    • Disable
      sizer.setDraggable(child, false);\n
      or
      sizer.setDraggable(elementName, false);\n
  • Drag target config
    sizer.setDraggable({\nsensor: child, // or elementName\ntarget: undefined, // or a parentSizer\ndraggable: true\n})\n
    • sensor : A game object or a string
    • target
      • undefined : Top-most sizer
      • A game object : A parent sizer
"},{"location":"ui-basesizer/#events","title":"Events","text":"
  • Fire 'sizer.drag' on target sizer when dragging
    targetSizer.on('sizer.drag', function(pointer, dragX, dragY) {\n\n})\n
  • Fire 'sizer.dragstart' on target sizer when dragging
    targetSizer.on('sizer.dragstart', function(pointer, dragX, dragY) {\n\n})\n
  • Fire 'sizer.dragend' on target sizer when dragging
    targetSizer.on('sizer.dragend', function(pointer, dragX, dragY, dropped) {\n\n})\n
  • Fire 'sizer.drop' on target sizer when dropped
    targetSizer.on('sizer.drop', function(pointer, dropZone) {\n\n})\n
"},{"location":"ui-basesizer/#click","title":"Click","text":"
  • Add click event
    sizer.onClick(callback, scope);\n// sizer.onClick(callback, scope, config);\n
    • config : See Button
    • callback :
      function(button, gameObject, pointer, event) {\n\n}\n
      • button : Button behavior.
  • Turn off click event
    sizer.offClick(callback, scope);\n
  • Enable click event
    sizer.enableClick();\n
  • Disable click event
    sizer.disableClick();\n

Equal to

var click = scene.rexUI.add.click(sizer, config);\nclick.on('click', callback, scope);\n
"},{"location":"ui-basesizer/#click-child","title":"Click child","text":"
  • Add click event
    sizer.onClick(child, callback, scope);\n// sizer.onClick(child, callback, scope, config);\n
  • Turn off click event
    sizer.offClick(child, callback, scope);\n
  • Enable click event
    sizer.enableClick(child);\n
  • Disable click event
    sizer.disableClick(child);\n
"},{"location":"ui-basesizer/#click-outside","title":"Click outside","text":"
  • Add click-outside event
    sizer.onClickOutside(callback, scope);\n// sizer.onClickOutside(callback, scope, config);\n
    • config : See ClickOutside
    • callback :
      function(clickOutside, gameObject, pointer) {\n\n}\n
      • clickOutside : ClickOutside behavior.
  • Turn off click-outside event
    sizer.offClickOutside(callback, scope);\n
  • Enable click-outside event
    sizer.enableClickOutside();\n
  • Disable click-outside event
    sizer.disableClickOutside();\n

Equal to

var clickOutside = scene.rexUI.add.clickOutside(sizer, config);\nclickOutside.on('clickoutside', callback, scope);\n
"},{"location":"ui-basesizer/#click-outside-of-child","title":"Click outside of child","text":"
  • Add click-outside event
    sizer.onClickOutside(child, callback, scope);\n// sizer.onClickOutside(child, callback, scope, config);\n
    • config : See ClickOutside
    • callback :
      function(clickOutside, gameObject, pointer) {\n\n}\n
      • clickOutside : ClickOutside behavior.
  • Turn off click-outside event
    sizer.offClickOutside(child, callback, scope);\n
  • Enable click-outside event
    sizer.enableClickOutside(child);\n
  • Disable click-outside event
    sizer.disableClickOutside(child);\n
"},{"location":"ui-basesizer/#is-pointer-in-bounds","title":"Is pointer in bounds","text":"
  • Is current sizer clicking
    var isClicked = sizer.isPointerInBounds();\n
  • Is a child clicking
    var isClicked = sizer.isPointerInBounds(child);\n
    or
    var isClicked = sizer.isPointerInBounds(elementName);\n
    • child : Game object of child
    • elementName : Element name for retrieveing child game object.
"},{"location":"ui-basesizer/#in-touching","title":"In touching","text":"

Invoke callbeack if pointer is inside hitarea every tick.

  • Add in-touching event
    sizer.onTouching(callback, scope);\n// sizer.onTouching(callback, scope, config);\n
  • Turn off in-touching event
    sizer.offTouching(callback, scope);\n
  • Add touching-end event
    sizer.onTouchingEnd(callback, scope);\n// sizer.onTouchingEnd(callback, scope, config);\n
  • Turn off touching-end event
    sizer.offTouchingEnd(callback, scope);\n
  • Enable in-touching event
    sizer.enableTouching();\n
  • Disable in-touching event
    sizer.disableTouching();\n

Equal to

var inTouching = scene.rexUI.add.inTouching(sizer, config);\ninTouching.on('intouch', callback, scope);\n
"},{"location":"ui-basesizer/#in-touching-child","title":"In touching child","text":"
  • Add in-touching event
    sizer.onTouching(child, callback, scope);\n// sizer.onClick(child, callback, scope, config);\n
  • Turn off in-touching event
    sizer.offTouching(child, callback, scope);\n
  • Enable in-touching event
    sizer.enableTouching(child);\n
  • Disable in-touching event
    sizer.disableTouching(child);\n
"},{"location":"ui-basesizer/#set-children-interactive","title":"Set children interactive","text":"

Applies click, tap, press, swipe behaviors on this sizer, to detect input events of children.

sizer.setChildrenInteractive({\n// dropZone: false,\n\n// down: undefined,\n// up: undefined,\n// over: undefined,\n\n// click: {mode: 'release', clickInterval: 100},\n\n// press: {time: 251, threshold: 9},\n\n// tap: {time: 250, tapInterval: 200, threshold: 9, tapOffset: 10, \n//       taps: undefined, minTaps: undefined, maxTaps: undefined,},\n\n// swipe: {threshold: 10, velocityThreshold: 1000, dir: '8dir'},\n\n// inputEventPrefix: 'child.',\n})\n
  • dropZone :
    • true : Enable drop Zone on this sizer.
    • false : Do nothing.
  • down :
    • false : Don't fire (pointer-) down events
  • up :
    • false : Don't fire (pointer-) up events
  • over :
    • false : Don't fire (pointer-) over/out events
  • click : Configuration of Button behavior.
    • false : Don't install Button behavior.
  • press : Configuration of Press behavior.
    • false : Don't install Press behavior.
  • tap : Configuration of Tap behavior.
    • false : Don't install Tap behavior.
  • swipe : Configuration of Swipe behavior.
    • false : Don't install Swipe behavior.
  • inputEventPrefix : Prefix string of each event, default is 'child.'.

Note

Input behaviors are installed to this Sizer game object, not each child. And it assumes that all children are not overlapped. Use Button if user needs to enable/disable input behaviors of each child individually.

"},{"location":"ui-basesizer/#events_1","title":"Events","text":"
  • Pointer-down
    sizer.on('child.down', function(child, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-up
    sizer.on('child.up', function(child, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-over
    sizer.on('child.over', function(child, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-out
    sizer.on('child.out', function(child, pointer, event) {\n// ...\n}, scope);\n
  • Click
    sizer.on('child.click', function(child, pointer, event) {\n// ...\n}, scope);\n
    • child : Triggered child game object.
    • pointer : Pointer object.
  • Press
    sizer.on('child.pressstart', function(child, pointer) { // ...\n}, scope);\n
    sizer.on('child.pressend', function(child, pointer) { // ...\n}, scope);\n
  • Tap
    sizer.on(tapEventName, function(child, pointer) { // ...\n}, scope);\n
    • tapEventName : 'child.1tap', 'child.2tap', 'child.3tap', etc ...
  • Swipe
    sizer.on(swipeEventName, function(child, pointer) { // ...\n}, scope);\n
    • swipeEventName : 'child.swipeleft', 'child.swiperight', 'child.swipeup', 'child.swipedown'.
"},{"location":"ui-basesizer/#bind-event","title":"Bind event","text":"
  • Bind event
    sizer.bindEvent(eventEmitter, eventName, callback, scope);\n
  • Bind scene's 'preupdate' event
    sizer.bindScenePreupdateEvent(callback, scope);\n
  • Bind scene's 'update' event
    sizer.bindSceneUpdateEvent(callback, scope);\n
  • Bind scene's 'postupdate' event
    sizer.bindScenePostupdateEvent(callback, scope);\n
  • Bind scene's 'render' event
    sizer.bindSceneRenderEvent(callback, scope);\n
  • Bind scene's 'pause' event
    sizer.bindScenePauseEvent(callback, scope);\n
  • Bind scene's 'resume' event
    sizer.bindSceneResumeEvent(callback, scope);\n
  • Bind scene's 'sleep' event
    sizer.bindSceneSleepEvent(callback, scope);\n
  • Bind scene's 'wake' event
    sizer.bindSceneWakeEvent(callback, scope);\n
  • Bind scene's 'shutdown' event
    sizer.bindSceneShutdownEvent(callback, scope);\n

Will remove this event from eventEmitter when destroying sizer.

"},{"location":"ui-basesizer/#pin-game-object","title":"Pin game object","text":"
sizer.pin(gameObject);\n

or

sizer.pinLocal(gameObject);\n

Note

Method sizer.add is override in each sizer class usually.

"},{"location":"ui-basesizer/#un-pin-game-object","title":"Un-pin game object","text":"
sizer.unpin(child);\n// sizer.unpin(child, destroyChild);\n
  • destroyChild : Set true to destroy child. Default is false.

Note

Method sizer.remove is override in each sizer class usually.

"},{"location":"ui-basesizer/#draw-bounds","title":"Draw bounds","text":"
  • Draw bounds of shown game object on a graphics game object
    sizer.drawBounds(graphics);\n// sizer.drawBounds(graphics, color);\n
    • graphics : Graphics game object
    • color : Default value is 0xffffff
  • Draw bounds of shown game object, and display name of child
    sizer.drawBounds(graphics, {\n// color: 0xffffff,\n// lineWidth: 2,\n\n// name: false, \n// name: true, \n// name: {\n//     createTextCallback: function(scene) {\n//         return scene.add.text(0, 0, '');\n//     },\n//     createTextCallbackScope: undefined,\n//     align: 'left-top'\n// }\n});\n
    • graphics : Graphics game object
    • color : Default value is 0xffffff.
    • lineWidth : Default value is 1.
    • name :
      • false : Don't display child name, default value
      • true : Display child name with default text game object, aligned at left-top of child bounds.
      • Plain object :
        • name.createTextCallback : Callback of creating customized text game object for child name
          function(scene, child, childBoundsRect) {\n// return scene.add.text(0, 0, ''); \n}\n
        • name.createTextCallbackScope : Callback scope of name.createTextCallback, default is undefined
        • name.align :
          • 'left-top', or Phaser.Display.Align.TOP_LEFT : Align text game object at left-top. Default value
          • 'center', or Phaser.Display.Align.CENTER : Align text game object at center
          • 'left', or Phaser.Display.Align.LEFT_CENTER : Align text game object at left-center
          • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align text game object at right-center
          • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game text object at top-center
          • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game text object at bottom-center
          • 'left-bottom', or Phaser.Display.Align.BOTTOM_LEFT : Align text game object at left-bottom
          • 'right-top', or Phaser.Display.Align.TOP_RIGHT : Align text game object at right-top
          • 'right-bottom', or Phaser.Display.Align.BOTTOM_RIGHT : Align text game object at right-bottom
    • Text game objects of these children's name will be attached on graphics game object, graphics.clear(), or graphics.destroy() will also destroy these text game objects
"},{"location":"ui-basesizer/#hide","title":"Hide","text":"
  • Set invisible, won't layout it
    sizer.hide();\n
    or
    sizer.hide(gameObject);\n
  • Set visible, will layout it
    sizer.show();\n
    or
    sizer.show(gameObject);\n
"},{"location":"ui-basesizer/#padding","title":"Padding","text":"
  • Set inner padding, will indent children position.
    • Set inner padding via config
      sizer.setInnerPadding({\nleft: leftPadding, right: rightPadding,\ntop: topPadding,\nbottom: bottomPadding\n});\n
    • Set inner padding via single number
      sizer.setInnerPadding(value);\n
    • Set specific inner padding
      sizer.setInnerPadding(key, value);\n
      • key : 'left', 'right', 'top', 'bottom'
  • Get inner padding
    • Get inner padding values
      var innerPadding = sizer.getInnerPadding();\n
    • Get specific inner padding
      var value = sizer.getInnerPadding(key);\n
      • key : 'left', 'right', 'top', 'bottom'
  • Set outer padding, which is equal to padding parameter when adding this sizer to parent sizer.
    • Set outer padding via config
      sizer.setOuterPadding({\nleft: leftPadding, right: rightPadding,\ntop: topPadding,\nbottom: bottomPadding\n});\n
    • Set outer padding via single number
      sizer.setOuterPadding(value);\n
    • Set specific outer padding
      sizer.setOuterPadding(key, value);\n
      • key : 'left', 'right', 'top', 'bottom'
  • Get outer padding
    • Get outer padding values
      var outerPadding = sizer.getOuterPadding();\n
    • Get specific outer padding
      var value = sizer.getOuterPadding(key);\n
      • key : 'left', 'right', 'top', 'bottom'
  • Set outer padding of child, which is equal to padding parameter when adding this sizer to parent sizer.
    • Set outer padding via config
      sizer.setChildOuterPadding(\nchild,\n{\nleft: leftPadding, right: rightPadding,\ntop: topPadding,\nbottom: bottomPadding\n}\n);\n
      • child : A string key or game object.
    • Set outer padding via single number
      sizer.setChildOuterPadding(child, value);\n
      • child : A string key or game object.
    • Set specific outer padding
      sizer.setChildOuterPadding(child, key, value);\n
      • child : A string key or game object.
      • key : 'left', 'right', 'top', 'bottom'
  • Get outer padding of child
    • Get outer padding values
      var outerPadding = sizer.getChildOuterPadding(child);\n
      • child : A string key or game object.
    • Get specific outer padding
      var value = sizer.getChildOuterPadding(child, key);\n
      • child : A string key or game object.
      • key : 'left', 'right', 'top', 'bottom'
"},{"location":"ui-basesizer/#anchor","title":"Anchor","text":"
sizer.setAnchor({\n// left: '0%+0',\n// right: '0%+0',\n// centerX: '0%+0',\n// x: '0%+0',\n\n// top: '0%+0',\n// bottom: '0%+0',\n// centerY: '0%+0',\n// y: '0%+0'\n})\n
  • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
    • Percentage of visible width/height : 'p%', p: 0~100
      • 'left'(=0%), 'center'(=50%), 'right'(=100%)
      • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
    • Offset : '+n', or '-n'

For example, anchor game object's left bound to viewport's left+10, and centerY to viewport's center :

{\nleft: 'left+10',\ncenterY: 'center'\n}\n
"},{"location":"ui-basesizer/#get-child","title":"Get child","text":"
  • Get child by specific key
    1. Add child
      sizer.addChildrenMap(key, child);\n
      • Remove children map :
        sizer.removeChildrenMap(key);\n
        or
        sizer.removeChildrenMap(child);\n
    2. Get child
      var child = sizer.getElement(key);\n
  • Get child by name
    var child = sizer.getByName(name);\n// var child = sizer.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-basesizer/#get-parent","title":"Get parent","text":"
  • Get parent sizer
    var parentSizer = sizer.getParentSizer();\n
  • Get ancestor sizer matched given name
    var parentSizer = sizer.getParentSizer(name);\n
  • Get topmost sizer
    var topmostSizer = sizer.getTopmostSizer();\n
"},{"location":"ui-basesizer/#has-parentchild","title":"Has parent/child","text":"
  • Has parent
    var hasParent = sizer.hasParentSizer(parentGameObject);\n
  • Has child
    var hasChild = sizer.hasParentSizer(childGameObject);\n
"},{"location":"ui-basesizer/#is-in-touching","title":"Is in touching","text":"
  • Is this sizer in touching?
    var isTouching = sizer.isInTouching();\n
  • Is child of this sizer in touching?
    var isTouching = sizer.isInTouching(child);\n
    or
    var isTouching = sizer.isInTouching(childKey);\n
    • child : Child game object.
    • childKey : Get child game object back via sizer.getElement(childKey). See also sizer.addChildrenMap(key, child)
"},{"location":"ui-basesizer/#change-properties-of-child","title":"Change properties of child","text":"
  • Set property of child from sizer
  • Set property of child, then reset local state of child
  • Tween local state of child
"},{"location":"ui-basesizer/#add-to-container","title":"Add to container","text":"
  • Add to built-in container
    p3Container.add(sizer);\n
    or
    sizer.addToContainer(p3Container);\n
    • container : Container game object.
  • Add to Layer
    sizer.addToLayer(layer);\n
    • layer : Layer game object.

Note

container.add(sizer), or layer.add(sizer) won't add children of sizer.

"},{"location":"ui-basesizer/#layer","title":"Layer","text":"

A sizer can have a layer. Current children and new children will draw on this layer, instead of display list of scene.

  • Enable layer. Do nothing if layer is existed.
    sizer.enableLayer();\n
  • Get layer game object. Will enable layer if layer is not existed.
    var layer = sizer.getLayer();\n
"},{"location":"ui-basesizer/#shader-effects","title":"Shader effects","text":"

Apply post-fx pipeline on layer of sizer.

"},{"location":"ui-basesizer/#snapshot","title":"Snapshot","text":"
  • Draw all visible children on a render-texture.
    var renderTexture = container.snapshot({\nrenderTexture: undefined,\npadding: 0\n});\n
    • renderTexture : Draw on this render-texture
      • undefined : Create a new render-texture
    • padding :
      • 0 : No extra padding space. Default value.
      • A number : Add extra padding space around this render-texture.
  • Draw all visible children on a texture
    container.snapshot({\npadding: 0,\nsaveTexture: textureKey\n});\n
    • saveTexture : Save render result to texture manager.
"},{"location":"ui-basesizer/#layout-children","title":"Layout children","text":"

Note

Enable sizer events by set sizerEvents to true in config.

  • Fire 'sizer.postlayout' event to all children after layout.
    child.on('sizer.postlayout', function(child, sizer){\nvar prevState = sizer.getChildPrevState(child);\n})\n
    • prevState : Properties before layout.
      • prevState.x, prevState.y : Child position before layout.
      • prevState.width, prevState.height, prevState.displayWidth, prevState.displayHeight, prevState.scaleX, prevState.scaleY : Child size before layout.
  • Fire 'postlayout' event.
    sizer.on('postlayout', function(children, sizer) {\nfor(var i=0, cnt=children.length; i<cnt; i++) {\nvar prevState = sizer.getChildPrevState(children[i]);\n// ...\n}\n})\n
"},{"location":"ui-basesizer/#remove-child","title":"Remove child","text":"

Note

Enable sizer events by set sizerEvents to true in config.

  • Fire 'sizer.remove' event to removed without destroyed child.
    child.on('sizer.remove', function(child, sizer){\n\n})\n
  • Fire 'remove' event.
    sizer.on('remove', function(child, sizer){\n\n})\n
"},{"location":"ui-basesizer/#add-child","title":"Add child","text":"

Note

Enable sizer events by set sizerEvents to true in config.

  • Fire 'sizer.add' event to added child.
    child.on('sizer.add', function(child, sizer){\n\n})\n
  • Fire 'add' event.
    sizer.on('add', function(child, sizer){\n\n})\n
"},{"location":"ui-basesizer/#broadcast-event","title":"Broadcast event","text":"

Fire event to sizer itself and all children

sizer.broadcastEvent(eventName, parameter0, parameter1, ...);\n

Receive event

child.on(eventName, function(parameter0, parameter1, ...) {\n\n}, scope);\n
"},{"location":"ui-basesizer/#other-properties","title":"Other properties","text":"

This game object inherits from ContainerLite.

"},{"location":"ui-buttons/","title":"Buttons","text":""},{"location":"ui-buttons/#introduction","title":"Introduction","text":"

A container with a group of buttons.

  • Author: Rex
  • Game object
"},{"location":"ui-buttons/#live-demos","title":"Live demos","text":"
  • Buttons with header and footer
  • Expand
  • Space
  • Checkboxes/radio
  • CustomProgress background
  • Popup each button
"},{"location":"ui-buttons/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-buttons/#install-plugin","title":"Install plugin","text":""},{"location":"ui-buttons/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add buttons object
    var buttons = scene.rexUI.add.buttons(config);\n
"},{"location":"ui-buttons/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add buttons object
    var buttons = scene.rexUI.add.buttons(config);\n
"},{"location":"ui-buttons/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Buttons } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add buttons object
    var buttons = new Buttons(scene, config);\nscene.add.existing(buttons);\n
"},{"location":"ui-buttons/#add-buttons-object","title":"Add Buttons object","text":"
var buttons = scene.rexUI.add.buttons({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n// buttonsType: undefined,\n\n// Elements\n// background: backgroundGameObject,\n\nbuttons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\nexpand: false,\nalign: undefined,\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n},\n\n// space: 0,   // deprecated \n// space: { left: 0, right:0, top:0, bottom:0, item:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n// eventEmitter: this,\n// groupName: undefined,\n\n// setValueCallback: undefined,  // or setButtonStateCallback: undefined\n// setValueCallbackScope: undefined  // or setButtonStateCallbackScope: undefined\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation : Main orientation of button game objects.
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Arrange button game objects from left ot right.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Arrange button game objects from top to bottom.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • buttonsType : Type/behavior of these buttons.
    • undefined : No extra behavior, default value.
    • 'checkboxes' : Set these buttons to checkboxes.
    • 'radio' : Set these buttons to radio.
  • background : Game object of background, optional. This background game object will be resized to fit the size of grid table.
  • buttons : Array of button game objects, or Space (scene.rexUI.add.space()).
  • expand : Set true to expand width, or height of buton game objects.
  • align : Note: Add Space (scene.rexUI.add.space()) into buttons parameter to have more flexible alignment style. Alignment of these button game objects. Only valid when expand is false.
    • undefined, or 'left', or 'top' : Align game objects at left, or top.
    • 'center' : Align game objects at center.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
  • click: Configuration of button clicking.
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
  • space :
    • An object: Padding of button game objects.
      • space.top, space.bottom, space.left, space.right : Padding around bottons.
      • space.item : Space between 2 button game objects.
    • A number: Deprecated, space between 2 button game objects.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • eventEmitter : Dispatch buttons' touch events to other game object, default is this buttons game object.
  • groupName : Optional group name for argument of touch events.
  • setValueCallback, or setButtonStateCallback : Callback to set value of a button.
    • undefined : No callback, default value.
    • A function object.
      function(button, value, previousValue) {\n// ...\n}\n
      • button : Button game object.
      • value: true, or false.
      • previousValue : true, or false.
"},{"location":"ui-buttons/#custom-class","title":"Custom class","text":"
  • Define class
    class MyButtons extends RexPlugins.UI.Buttons {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var buttons = new MyButtons(scene, config);\n
"},{"location":"ui-buttons/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

buttons.layout();\n

See also - dirty

"},{"location":"ui-buttons/#other-properties","title":"Other properties","text":"

See sizer object

"},{"location":"ui-buttons/#events","title":"Events","text":"
  • Click button
    buttons.on('button.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.click', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
    • groupName : Optional group name.
    • button : Triggered button game object.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-over button
    buttons.on('button.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.over', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-out button
    buttons.on('button.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.out', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-down button
    buttons.on('button.down', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.down', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-up button
    buttons.on('button.up', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.up', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Enable button's input
    buttons.on('button.enable', function(button, index) {\n// ...\n}, scope);\n
    or
    buttons.on('button.enable', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Disable button's input
    buttons.on('button.disable', function(button, index) {\n// ...\n}, scope);\n
    or
    buttons.on('button.disable', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
"},{"location":"ui-buttons/#emit-button-click-event","title":"Emit button click event","text":"
buttons.emitButtonClick(index);\n
  • index : Index of triggered button game object, or a button game object.
"},{"location":"ui-buttons/#enabledisable-input-of-button","title":"Enable/disable input of button","text":"
  • Enable a button's input
    buttons.setButtonEnable(index);\n// buttons.setButtonEnable(index, true);\n
    • index : Index of triggered button game object, or a button game object.
  • Enable all buttons' input
    buttons.setButtonEnable();\n// buttons.setButtonEnable(true);\n
  • Disable
    buttons.setButtonEnable(index, true);\n
    • index : Index of triggered button game object, or a button game object.
  • Disable all buttons' input
    buttons.setButtonEnable(false);\n
  • Toggle
    buttons.toggleButtonEnable(index);\n
  • Toggle all buttons's input
    buttons.toggleButtonEnable();\n
  • Get button's input enable
    var enabled = bottons.getButtonEnable(index);\n
"},{"location":"ui-buttons/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = buttons.getElement('background');\n
    • Button game objects
      var buttonObjects = buttons.getElement('buttons');\n
      or
      var buttonObject = buttons.getButton(index);\n
      or
      var buttonObjects = buttons.getElement('buttons[0]'); // First button\n
  • Get by name
    var gameObject = buttons.getElement('#' + name);\n// var gameObject = buttons.getElement('#' + name, recursive);\n
    or
    var gameObject = buttons.getByName(name);\n// var gameObject = buttons.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-buttons/#add-child","title":"Add child","text":"
  • Add button child
    buttons.addButton(gameObject)\n
    • gameObject : A game object, or an array of game objects.
  • Add non-button child, see sizer.add() method.
    buttons.add(gameObject,\n{\nproportion: 0,\nalign: 'center',\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nexpand: false,\nkey: undefined,\nindex: undefined,\nminWidth: undefined,\nminHeight: undefined\n}\n)\n
"},{"location":"ui-buttons/#remove-child","title":"Remove child","text":"
  • Remove button child
    buttons.removeButton(gameObject, destroyChild);\n
    • gameObject :
      • Game object, or array of game objects : Button game object.
      • A number, or array of numbers : Index of button game object.
      • A string, or array of strings : Name of button game object.
    • destroyChild : Set true to destroy button game object.
  • Remove all buttton children
    buttons.clearButtons(destroyChild);\n
    • destroyChild : Set true to destroy button game objects.
  • Remove a button or non-button child, see sizer.remove() method.
    buttons.remove(gameObject, destroyChild);\n
  • Remove all button or non-button children, see sizer.remove() method.
    buttons.removeAll(destroyChild);\n
"},{"location":"ui-buttons/#showhide-button","title":"Show/hide button","text":"

Hidden elements won't be counted when layouting. Call buttons.layout(), or topSizer.layout() after show/hide any button.

  • Show button
    buttons.showButton(index);\n
    • index : A number index, or a button game object.
  • Hide button.
    buttons.hideButton(index);\n
    • index : A number index, or a button game object.
"},{"location":"ui-buttons/#for-each-button","title":"For each button","text":"
buttons.forEachButtton(callback, scope);\n
  • callback :
    function(button, index, buttonArray) {\n// ...\n}\n
"},{"location":"ui-buttons/#checkboxesradio","title":"Checkboxes/radio","text":"
  • Configure buttons to checkboxes/radio
    var buttons = scene.rexUI.add.buttons({\nbuttons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\n\nbuttonsType: 'checkboxes', // or 'radio'\nsetValueCallback: function(button, value, previousValue) {\n// ...\n}, // or setButtonStateCallback\n});\n
    • buttons : Array of button game objects.
      • Property name of each button game object will be used as a key in buttons.data
    • buttonsType : Set type to 'checkboxes', or 'radio'.
    • setValueCallback or setButtonStateCallback : Callback to set value of a button.
      function(button, value) {\n// ...\n}\n
      • button : Button game object.
      • value: true, or false.
      • previousValue : true, or false.
      • Also trigger 'button.statechange' event.
    • State of a button : Stored in buttons.data
    • Get states of all buttons :
      var states = buttons.getAllButtonsState();  // { key: boolean }\n
    • Clear states of all button :
      buttons.clearAllButtonsState();\n
      • Will trigger setValueCallback and 'button.statechange' event.
"},{"location":"ui-buttons/#checkboxes","title":"Checkboxes","text":"
  • Read state
    var state = buttons.getButtonState(key);\n
    • key : name property of a button game object. (i.e. button.name)
    • state : true, or false
  • Set state
    buttons.setButtonState(key, state);\n
    • key : name property of a button game object. (i.e. button.name)
    • state : true, or false
"},{"location":"ui-buttons/#radio","title":"Radio","text":"
  • Read state
    var value = buttons.getSelectedButtonName();\n
    or
    var value = buttons.value;\n
    • value : name property of a button game object. (i.e. button.name)
  • Set state
    buttons.setSelectedButtonName(key);\n
    or
    buttons.value = key;\n
    • key : name property of a button game object. (i.e. button.name)
"},{"location":"ui-buttons/#events_1","title":"Events","text":"
  • On button state changed. For Checkboxes/radio
    buttons.on('button.statechange', function(button, index, value, previousValue) {\n// ...\n}, scope);\n
    or
    buttons.on('button.statechange', function(button, groupName, index, value, previousValue) {\n// ...\n}, scope);\n
    • Can be used to replace setValueCallback.
"},{"location":"ui-chart/","title":"Chart","text":""},{"location":"ui-chart/#introduction","title":"Introduction","text":"

Draw chart on canvas.

  • Author: Rex
  • Game object
"},{"location":"ui-chart/#live-demos","title":"Live demos","text":"
  • Radar chart
"},{"location":"ui-chart/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-chart/#install-plugin","title":"Install plugin","text":""},{"location":"ui-chart/#install-chartjs","title":"Install chart.js","text":"

Chart.js is not included in rexUI, installs it before creating any chart.

scene.load.script('chartjs', 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js');\n
or
scene.load.script('chartjs', 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js');\n

"},{"location":"ui-chart/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.script('chartjs', 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/Chart.min.js');\nscene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add chart object
    var chart = scene.rexUI.add.chart(config);\n
"},{"location":"ui-chart/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add chart object
    var chart = scene.rexUI.add.chart(config);\n
"},{"location":"ui-chart/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Chart } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add chart object
    var chart = new Chart(scene, config);\nscene.add.existing(chart);\n
"},{"location":"ui-chart/#add-chart-object","title":"Add chart object","text":"
var chart = scene.rexUI.add.chart(x, y, width, height, config);\n
  • x, y : Position of this object.
  • width, height : Canvas size.
  • config : Configuration for creating chart.
    • Set undefined to not create chart at beginning.
"},{"location":"ui-chart/#custom-class","title":"Custom class","text":"
  • Define class
    class MyChart extends RexPlugins.UI.Chart {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var chart = new MyChart(scene, x, y, width, height, config);\n
"},{"location":"ui-chart/#create-chart","title":"Create chart","text":"

Create chart (if not creating at beginning).

chart.setChart(config);\n
  • config : Configuration for creating chart.
"},{"location":"ui-chart/#chart-data","title":"Chart data","text":"
  • Get dataset
    var dataset = chart.getChartDataset(datasetIndex);\n
    • datasetIndex : Index number or label string.
  • Get data
    var data = chart.getChartData(datasetIndex, dataIndex);\n
    • datasetIndex : Index number or label string.
    • dataIndex : Index number or label string.
  • Set
    chart.setChartData(datasetIndex, dataIndex, value).updateChart();\n
    • datasetIndex : Index number or label string.
    • dataIndex : Index number or label string.
"},{"location":"ui-chart/#manipulate-chart-object","title":"Manipulate chart object","text":"
  1. Get chart object
    var chart = chart.chart;\n
  2. Set properties of chart
    • Array of dataset
      var datasets = chart.data.datasets;\n
      • Label of dataset
        var label = chart.data.datasets[i].label;\n
    • Labels
      var labels = chart.data.labels;\n
    • Set chart data
      chart.data.datasets[datasetIndex].data[dataIndex] = value;\n
  3. Update chart
    chart.update();\n
"},{"location":"ui-colorcomponents/","title":"Color components","text":""},{"location":"ui-colorcomponents/#introduction","title":"Introduction","text":"

Edit color value by RGB, or HSV input fields. Clicking fist label can switch color format between RGB and HSV

  • Author: Rex
  • Game object
"},{"location":"ui-colorcomponents/#live-demos","title":"Live demos","text":"
  • Color components
"},{"location":"ui-colorcomponents/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-colorcomponents/#install-plugin","title":"Install plugin","text":""},{"location":"ui-colorcomponents/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add color-components object
    var colorComponents = scene.rexUI.add.colorComponents(config);\n
"},{"location":"ui-colorcomponents/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add color-components object
    var colorComponents = scene.rexUI.add.colorComponents(config);\n
"},{"location":"ui-colorcomponents/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ColorComponents } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add color-components object
    var colorComponents = new ColorComponents(scene, config);\nscene.add.existing(colorComponents);\n
"},{"location":"ui-colorcomponents/#add-colorcomponents-object","title":"Add colorComponents object","text":"
var colorComponents = scene.rexUI.add.colorComponents({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\n\nformatLabel: {\nbackground: {\nradius: 0,\ncolor: undefined, alpha: undefined,\nstrokeColor: undefined, strokeAlpha: undefined, strokeWidth: 2\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},\nalign: 'left',  // 'left'|'center'|'right'|'justify'\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n},\n\nspace: {left: 0, right: 0, top: 0, bottom: 0}\n},\n\n// formatLabel: labelGameObject,\n\ninputText: {\nwidth: undefined, height: undefined,\n\npadding: 0,  // {left: 0, right: 0, top: 0, bottom: 0}\n\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null,\n\n// Style when focus\n// 'focus.color': ...\n// 'focus.color2': ...\n// 'focus.stroke': ...\n},\nfocusStyle: undefined,\n\ninnerBounds: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBY: undefined,\noffsetX: 0,\noffsetY: 0,\n\n// Style when cursor move on\n// 'cursor.color': ...\n// 'cursor.backgroundColor': ...\n// 'cursor.xxx': ...\n},\ncursorStyle: undefined,\n\nwrap: {\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n},\nlineHeight: undefined,\nmaxLines: undefined,\nwrapWidth: undefined,\nletterSpacing: 0,\nhAlign: 0,\nvAlign: 'center',  // For single line text input\ncharWrap: true,    // For single line text input\n},\n\n// enterClose: true,\n// readOnly: false,\n\n// Callbacks\n// onOpen: function (textObject, hiddenInputText) {\n// },\n\n// onClose: function (textObject, hiddenInputText) {\n// },\n\n// onUpdate: function (text, textObject, hiddenInputText) {\n//     return text;\n// },   \n\n// onAddChar: function(child, index, canvasInput) {\n//    child.modifyStyle({...})\n// },\n\n// onCursorOut: function(child, cursorIndex, canvasInput) {\n//     child.modifyStyle({\n//         \n//     });\n// },\n\n// onCursorIn: function(child, cursorIndex, canvasInput) {\n//     child.modifyStyle({\n//         \n//     });\n// },\n},\n\n// inputText0: canvasInputGameObject,\n// inputText1: canvasInputGameObject,\n// inputText2: canvasInputGameObject,\n\n// proportion: { formatLabel: 0 },\n\nvaluechangeCallback: function(newValue, oldValue, knob) {\n},\nvaluechangeCallbackScope: undefined,\n\nvalue: 0xffffff,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\nitem: 0\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,    \n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of colorComponents.
  • formatLabel : Clicking this label can switch color format between RGB and HSV
    • A label game object, or a text game object.
    • A plain object
      {\nbackground: {\nradius: 0,\ncolor: undefined, alpha: undefined,\nstrokeColor: undefined, strokeAlpha: undefined, strokeWidth: 2\n},\n\ntext: textStyle,\n\nspace: {left: 0, right: 0, top: 0, bottom: 0}\n}\n
      • formatLable.background : Parameters to create round rectangle game object.
      • formatLable.text : Text style to create [text.md] game object.
      • formatLabel.space : Padding space around format label.
  • inputText : Configuration of canvasInput
  • inputText0, inputText1, inputText2 : 3 canvas input game objects if parameter inputText is not given.
  • proportion :
    • proportion.formatLabel : Default value is 0.
  • valuechangeCallback : callback function when value changed.
  • value : Initial color value (0 ~ 0xffffff).
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between swatch and inputText.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-colorcomponents/#custom-class","title":"Custom class","text":"
  • Define class
    class MyColorComponents extends RexPlugins.UI.ColorComponents {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var colorComponents = new MyColorComponents(scene, config);\n
"},{"location":"ui-colorcomponents/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

colorComponents.layout();\n

See also - dirty

"},{"location":"ui-colorcomponents/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = colorComponents.getElement('background');\n
    • Format-label game object
      var icon = colorComponents.getElement('formatLabel');\n
    • Color component input text game objects
      var textObjects = colorComponents.getElement('components');\n
      • textObjects : An arrray with 3 canvas input game objects.
  • Get by name
    var gameObject = colorComponents.getElement('#' + name);\n// var gameObject = colorComponents.getElement('#' + name, recursive);\n
    or
    var gameObject = colorComponents.getByName(name);\n// var gameObject = colorComponents.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-colorcomponents/#value","title":"Value","text":"

Change value will also change the position of marker on H-palette and SV-palette

  • Get color value
    var value = colorComponents.value;\n// var value = colorComponents.color;\n
  • Set color value
    colorComponents.setValue(value);\n// colorComponents.setColor(value);\n
    or
    colorComponents.value = value;\ncolorComponents.color = value;\n
"},{"location":"ui-colorcomponents/#events","title":"Events","text":"
  • On value changed
    colorComponents.on('valuechange', function(newValue, oldValue, colorComponents){\n//\n}, scope);\n
"},{"location":"ui-colorcomponents/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-colorinput/","title":"Color input","text":""},{"location":"ui-colorinput/#introduction","title":"Introduction","text":"

Color number (0x0~0xffffff) or color string ('#000000'~'#ffffff', or 'red') input field.

  • Author: Rex
  • Game object
"},{"location":"ui-colorinput/#live-demos","title":"Live demos","text":"
  • Color input
"},{"location":"ui-colorinput/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-colorinput/#install-plugin","title":"Install plugin","text":""},{"location":"ui-colorinput/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add color-input object
    var colorInput = scene.rexUI.add.colorInput(config);\n
"},{"location":"ui-colorinput/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add color-input object
    var colorInput = scene.rexUI.add.colorInput(config);\n
"},{"location":"ui-colorinput/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ColorInput } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add color-input object
    var colorInput = new ColorInput(scene, config);\nscene.add.existing(colorInput);\n
"},{"location":"ui-colorinput/#add-colorinput-object","title":"Add colorInput object","text":"
var colorInput = scene.rexUI.add.colorInput({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\n\nswatch: undefined,\n// swatch: { shape: 'circle' },\n// swatch: { size: 30 },\n// swatch: swatchGameObject,\n// swatch: false,\n\n// swatchSize: undefined,  // or swatch: { size }\n// squareExpandSwatch: true,\n\ninputText: inputTextConfig,\n// inputText: false,\n\ncolorPicker : {\nwidth: 160, height: 170,\n\nbackground: {\nradius: 0,\ncolor: undefined, alpha: undefined,\nstrokeColor: undefined, strokeAlpha: undefined, strokeWidth: 2\n},\n// createBackgroundCallback: function(scene) {\n//     return gameObject;\n// }\n\n// hPalettePosition: 'bottom',\n\n// space: { left: 10, right: 10, top: 10, bottom: 10, item: 8 }\n},\n\ncolorComponents: {\n// height: undefined,\n\n// formatLabel: undefined,\n\n// inputText: undefined,\n\n// space: { item: 8 }\n},\n// colorComponents: false,\n\nvaluechangeCallback: function(newValue, oldValue, colorInput) {\n},\nvaluechangeCallbackScope: undefined,\n\nvalue: 0xffffff,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0,\ntext: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,    \n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of colorInput.
  • swatch : Display color value on a square, circle shape, or an image game object with tint.
    • undefein : A square swatch. Default game object.
    • A plain object : A circle, or a round square swatch.
      { shape: 'circle' }\n
      or
      { radius: 10 }\n
      or
      { radius: 10, size: 30 }\n
      • shape : (Round-) Rectangle or circle
        • 0, or 'rectangle' : (Round-) Rectangle shape.
        • 1, or 'circle' : Circle shape.
      • radius : Radius of round rectangle.
      • size : Size of swatch. Equal to swatchSize parameter.
    • An Image or Sprite game object : Tint this game object for displaying color value.
    • false : No swatch game object.
  • swatchSize :
    • A number : Size of swatch.
    • undefined : Expand size to fit inner height of color input. Default behavior.
  • squareExpandSwatch
    • true : Expand size to fit inner height of color input. Default behavior if swatchSize is set to undefined, or not given
    • false : Keep current size of swatch.
  • inputText : Configuration of canvasInput
  • colorPicker : Configuration of a drop-down color picker, triggered by clicking swatch.
    • colorPicker.width, colorPicker.height : Sizer of color picker. Default value is 180x170
    • colorPicker.background : Parameters to create round rectangle game object, optional.
    • colorPicker.createBackgroundCallback : Callback to create background game object, optional.
      function(scene) {\nreturn gameObject;\n}\n
    • colorPicker.hPalettePosition : Position of h-palette.
      • 'bottom' or 0 : Place h-palette at bottom side of sv-palette.
      • 'left' or 1 : Place h-palette at left side of sv-palette.
      • 'top' or 2 : Place h-palette at top side of sv-palette.
      • 'right' or 3 : Place h-palette at right side of sv-palette.
    • colorPicker.space : Padding space around color picker. Default value is
      { left: 10, right: 10, top: 10, bottom: 10, item: 8 }\n
    • false : No color picker.
  • colorComponents : Configuration of color components inside the drop down color picker.
    • colorComponents.height : Height of color components.
    • colorComponents.formatLabel : Clicking this label can switch color format between RGB and HSV
      • undefined : Will create a label with default text game object.
      • A plain object
        {\nbackground: {\nradius: 0,\ncolor: undefined, alpha: undefined,\nstrokeColor: undefined, strokeAlpha: undefined, strokeWidth: 2\n},\n\ntext: textStyle,\n\nspace: {left: 0, right: 0, top: 0, bottom: 0}\n}            
    • colorComponents.inputText : Configuration of canvasInput used in this color components. Will use inputText of color input if this parameter is not given.
    • colorComponents.space : Padding space around color components. Default value is
      { item: 8 }\n
    • false : No color components.
  • valuechangeCallback : callback function when value changed.
  • value : Initial color value (0 ~ 0xffffff).
    • Number : 0 ~ 0xffffff
    • String :
      • 0x0~0xffffff
      • '#000000'~'#ffffff'
      • 'red'
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between swatch and inputText.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-colorinput/#custom-class","title":"Custom class","text":"
  • Define class
    class MyColorInput extends RexPlugins.UI.ColorInput {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var colorInput = new MyColorInput(scene, config);\n
"},{"location":"ui-colorinput/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

colorInput.layout();\n

See also - dirty

"},{"location":"ui-colorinput/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = colorInput.getElement('background');\n
    • Swatch game object
      var icon = colorInput.getElement('swatch');\n
    • Input text game object
      var textObject = colorInput.getElement('inputText');\n
  • Get by name
    var gameObject = colorInput.getElement('#' + name);\n// var gameObject = colorInput.getElement('#' + name, recursive);\n
    or
    var gameObject = colorInput.getByName(name);\n// var gameObject = colorInput.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-colorinput/#value","title":"Value","text":"

Change value will also change the position of marker on H-palette and SV-palette

  • Get color value
    var value = colorInput.value;\n// var value = colorInput.color;\n
  • Set color value
    colorInput.setValue(value);\n// colorInput.setColor(value);\n
    or
    colorInput.value = value;\ncolorInput.color = value;\n
"},{"location":"ui-colorinput/#events","title":"Events","text":"
  • On value changed
    colorInput.on('valuechange', function(newValue, oldValue, colorInput){\n//\n}, scope);\n
"},{"location":"ui-colorinput/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-colorpicker/","title":"Color picker","text":""},{"location":"ui-colorpicker/#introduction","title":"Introduction","text":"

Pick color value from H and SV palettes.

  • Author: Rex
  • Game object
"},{"location":"ui-colorpicker/#live-demos","title":"Live demos","text":"
  • Color picker
"},{"location":"ui-colorpicker/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-colorpicker/#install-plugin","title":"Install plugin","text":""},{"location":"ui-colorpicker/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add color-picker object
    var colorPicker = scene.rexUI.add.colorPicker(config);\n
"},{"location":"ui-colorpicker/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add color-picker object
    var colorPicker = scene.rexUI.add.colorPicker(config);\n
"},{"location":"ui-colorpicker/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ColorPicker } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add color-picker object
    var colorPicker = new ColorPicker(scene, config);\nscene.add.existing(colorPicker);\n
"},{"location":"ui-colorpicker/#add-colorpicker-object","title":"Add colorPicker object","text":"
var colorPicker = scene.rexUI.add.colorPicker({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\n\nhPalette: {\nposition: 'bottom',\nsize: 10,\nwidth: undefined,\nheight: undefined,       },\n\nsvPalette: {\nwidth: undefined,\nheight: undefined,\n},\n\nvaluechangeCallback: function(newValue, oldValue, knob) {\n},\nvaluechangeCallbackScope: undefined,\n\nvalue: 0xffffff,\n\n// space: { left: 0, right:0, top:0, bottom:0, item:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,    \n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of colorPicker.
  • hPalette : Configuration of h-palette. H-palette is rendered on a canvas game object.
    • hPalette.position : Position of h-palette.
      • 'bottom' or 0 : Place h-palette at bottom side of sv-palette.
      • 'left' or 1 : Place h-palette at left side of sv-palette.
      • 'top' or 2 : Place h-palette at top side of sv-palette.
      • 'right' or 3 : Place h-palette at right side of sv-palette.
    • hPalette.size : Width (if position of h-palette is at left or right side) or height (if position of h-palette is at top or bottom side) of h-palette.
    • hPalette.width : Width (if position of h-palette is at left or right side) of h-palette.
    • hPalette.height : Height (if position of h-palette is at top or bottom side) of h-palette.
  • svPalette : Configuration of sv-palette. SV-palette is rendered on a canvas game object.
    • svPalette.width : Width of sv-palette.
    • svPalette.height : Height of sv-palette.
  • valuechangeCallback : callback function when value changed.
  • value : Initial color value (0 ~ 0xffffff).
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between sv-palette and h-palette.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-colorpicker/#custom-class","title":"Custom class","text":"
  • Define class
    class MyColorPicker extends RexPlugins.UI.ColorPicker {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var colorPicker = new MyColorPicker(scene, config);\n
"},{"location":"ui-colorpicker/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

colorPicker.layout();\n

See also - dirty

"},{"location":"ui-colorpicker/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = colorPicker.getElement('background');\n
    • H-palette game object
      var icon = colorPicker.getElement('hPalette');\n
    • SV-palette game object
      var textObject = colorPicker.getElement('svPalette');\n
  • Get by name
    var gameObject = colorPicker.getElement('#' + name);\n// var gameObject = colorPicker.getElement('#' + name, recursive);\n
    or
    var gameObject = colorPicker.getByName(name);\n// var gameObject = colorPicker.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-colorpicker/#value","title":"Value","text":"

Change value will also change the position of marker on H-palette and SV-palette

  • Get color value
    var value = colorPicker.value;\n// var value = colorPicker.color;\n
  • Set color value
    colorPicker.setValue(value);\n// colorPicker.setColor(value);\n
    or
    colorPicker.value = value;\ncolorPicker.color = value;\n
"},{"location":"ui-colorpicker/#events","title":"Events","text":"
  • On value changed
    colorPicker.on('valuechange', function(newValue, oldValue, colorPicker){\n//\n}, scope);\n
"},{"location":"ui-colorpicker/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-confirmaction/","title":"Confirm action","text":""},{"location":"ui-confirmaction/#introduction","title":"Introduction","text":"

Create a modal confirm dialog temporary, invoke callback after clicking button.

  • Author: Rex
  • Method
"},{"location":"ui-confirmaction/#live-demos","title":"Live demos","text":"
  • Confirm action
"},{"location":"ui-confirmaction/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-confirmaction/#install-plugin","title":"Install plugin","text":""},{"location":"ui-confirmaction/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Run confirm action
    var dialog = scene.rexUI.confirmAction(scene, config);\n
    • dialog : Confirm dialog will be destroy after clicking any button.
"},{"location":"ui-confirmaction/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Run confirm action
    var dialog = scene.rexUI.confirmAction(scene, config)\n
    • dialog : Confirm dialog will be destroy after clicking any button.
"},{"location":"ui-confirmaction/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ConfirmAction } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Run confirm action
    var dialog = ConfirmAction(scene, config)\n
    • dialog : Confirm dialog will be destroy after clicking any button.
"},{"location":"ui-confirmaction/#run-confirm-action","title":"Run confirm action","text":"
var dialog = scene.rexUI.confirmAction(scene, {    style: confirmDialogConfig\n\ncontent: confirmDialogResetChoiceDisplayContentConfig,\n\n// modal: confirmDialogModalConfig,\n\n// onCreateDialog: function(dialog) { },\n\nconfirm: function() {},\n// confirmScope: \n// confirmButtonIndex: 0,\n\n// cancel: function() {},\n// cancelScope: \n// cancelButtonIndex: 1,\n})\n
  • Build confirm dialog
    • style : Config parameter of Confirm dialog
    • content : Content strings of title, content, button.
    • modal : Config parameter of modal method
    • onCreateDialog : Callback invoking after creating dialog.
      function(dialog) {\n\n}\n
  • Callbacks
    • confirm, confirmScope : Callback invoking when click confirm/OK button of Confirm dialog
    • confirmButtonIndex : Index of confirm/OK button on Confirm dialog. Default value is 0.
    • cancel, cancelScope : Callback invoking when click cancel/cancel button of Confirm dialog
    • cancelButtonIndex : Index of cancel/cancel button on Confirm dialog. Default value is 1.
  • dialog : Confirm dialog will be destroy after clicking any button.
"},{"location":"ui-confirmactionbutton/","title":"Confirm action button","text":""},{"location":"ui-confirmactionbutton/#introduction","title":"Introduction","text":"

Click this label to invoke ConfirmAction. It will create a modal confirm dialog temporary, invoke callback after clicking button.

  • Author: Rex
  • Game object
"},{"location":"ui-confirmactionbutton/#live-demos","title":"Live demos","text":"
  • Open page
"},{"location":"ui-confirmactionbutton/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-confirmactionbutton/#install-plugin","title":"Install plugin","text":""},{"location":"ui-confirmactionbutton/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add button object
    var button = scene.rexUI.add.confirmActionButton(config);\n
"},{"location":"ui-confirmactionbutton/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add button object
    var button = scene.rexUI.add.confirmActionButton(config);\n
"},{"location":"ui-confirmactionbutton/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ConfirmActionButton } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add button object
    var button = new ConfirmActionButton(scene, config);\nscene.add.existing(button);\n
"},{"location":"ui-confirmactionbutton/#add-button-object","title":"Add button object","text":"
var button = scene.rexUI.confirmActionButton({\n// Parameters of Label\n\n\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\n\nicon: iconGameObject,\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntext: textGameObject,\nexpandTextWidth: false,\nexpandTextHeight: false,\n\naction: actionGameObject,\n// actionMask: false,\n// squareFitAction: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nalign: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\n\nicon: 0, iconTop: 0, iconBottom: 0, iconLeft: 0, iconRight: 0,\n\ntext: 0,\nactionTop: 0, actionBottom: 0, actionLeft: 0, actionRight: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n\n\n// Parameter of building confirm dialog\nconfirmDialog: {\nstyle: confirmDialogConfig\n// content: confirmDialogResetChoiceDisplayContentConfig,\n// modal: confirmDialogModalConfig,\n// onCreateDialog: function(dialog) { },\n\n// confirmButtonIndex: 0,\n// cancelButtonIndex: 1,\n\n},\n\n// Callbacks\nconfirm: function() {},\n// confirmScope:\n\n// cancel: function() {},\n// cancelScope: \n});\n
  • Parameters of Label...
  • Parameter of building confirm dialog
    • confirmDialog.style : Config parameter of Confirm dialog
    • confirmDialog.content : Content strings of title, content, button. Can assign this value later.
    • confirmDialog.modal : Config parameter of modal method
    • confirmDialog.onCreateDialog : Callback invoking after creating dialog.
      function(dialog) {\n\n}\n
    • confirmDialog.confirmButtonIndex : Index of confirm/OK button on Confirm dialog. Default value is 0.
    • confirmDialog.cancelButtonIndex : Index of cancel/cancel button on Confirm dialog. Default value is 1.
  • Callbacks
    • confirm, confirmScope : Callback invoking when click confirm/OK button of Confirm dialog
    • cancel, cancelScope : Callback invoking when click cancel/cancel button of Confirm dialog

Destroy confirm dialog after clicking confirm/OK, or cancel/cancel button.

"},{"location":"ui-confirmactionbutton/#custom-class","title":"Custom class","text":"
  • Define class
    class MyButton extends RexPlugins.UI.ConfirmActionButton {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var button = new MyButton(scene, config);\n
"},{"location":"ui-confirmactionbutton/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

button.layout();\n

See also - dirty

"},{"location":"ui-confirmactionbutton/#get-element","title":"Get element","text":"

See Get element

"},{"location":"ui-confirmactionbutton/#set-callbacks","title":"Set callbacks","text":"
  • Callback after clicking confirm/OK button of confirm dialog
    button.setConfirmCallback(callback);\n// button.setConfirmCallback(callback, scope);\n
    • callback : Any function object
      function() {\n\n}\n
  • Callback after clicking cancel/cancel button of confirm dialog
    button.setCancelCallback(callback);\n// button.setCancelCallback(callback, scope);\n
    • callback : Any function object
      function() {\n\n}\n
"},{"location":"ui-confirmactionbutton/#set-display-content-of-confirm-dialog","title":"Set display content of confirm dialog","text":"
button.setConfirmDialogContent({\ntitle: '',\ncontent: '',\nbuttonA: '',\nbuttonB: '',\n});\n

or

button.setConfirmDialogContent({\ntitle: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\ncontent: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nbuttonA: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nbuttonB: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nchoices: [\n{\ntext: '', value: undefined,\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n},        // ...\n]\n});\n
  • title, content,buttonA, buttonB : Display content
    • A string : Set text of simple lable
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
  • choices : Array of display content
    • A string : Set text of simple lable, also use this string as option value.
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
      • Property value : Option value.
"},{"location":"ui-confirmactionbutton/#set-style-of-confirm-dialog","title":"Set style of confirm dialog","text":"
button.setConfitmDialogStyle(style);\n
  • style : See Config parameter of Confirm dialog
"},{"location":"ui-confirmactionbutton/#set-configuration-of-confirm-dialogs-modal-behavior","title":"Set configuration of confirm dialog's modal behavior","text":"
button.setConfitmDialogModalConfig(config);\n
  • config : See Config parameter of modal method
"},{"location":"ui-confirmactionbutton/#disalbe-confirm-dialog","title":"Disalbe confirm dialog","text":"

Run confirm callback directly without confirm dialog.

button.setConfirmDialogEnable(false);\n
"},{"location":"ui-confirmactionbutton/#other-properties","title":"Other properties","text":"

See label, sizer object, base sizer object, container-lite.

"},{"location":"ui-confirmdialog/","title":"Confirm dialog","text":""},{"location":"ui-confirmdialog/#introduction","title":"Introduction","text":"

Using json style to create confirm dialog, composed of simple-label title, simple-label content, with simple-label 0, 1, or 2 action button(s).

  • Author: Rex
  • Game object
"},{"location":"ui-confirmdialog/#live-demos","title":"Live demos","text":"
  • Yes-no buttons
  • Ok button
  • Any-touch closing
  • TextArea content
  • Radio-choices
"},{"location":"ui-confirmdialog/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-confirmdialog/#install-plugin","title":"Install plugin","text":""},{"location":"ui-confirmdialog/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add dialog object
    var dialog = scene.rexUI.add.confirmDialog(style).resetDisplayContent(config);\n// var dialog = scene.rexUI.add.confirmDialog(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-confirmdialog/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add dialog object
    var dialog = scene.rexUI.add.confirmDialog(style).resetDisplayContent(config);\n// var dialog = scene.rexUI.add.confirmDialog(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-confirmdialog/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ConfirmDialog } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add dialog object
    var dialog = new ConfirmDialog(scene, config);\n// var dialog = new ConfirmDialog(scene, config, creators);\nscene.add.existing(dialog);\ndialog.resetDisplayContent(config);\n
"},{"location":"ui-confirmdialog/#add-dialog-object","title":"Add dialog object","text":"
var dialog = scene.rexUI.add.confirmDialog({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\nbackground: backgroundStyle,\n// background: null,\n\ntitle: titleStyle,  // SimpleLabelConfig\n// title: null,\n\ncontent: contentStyle, // SimpleLabelConfig, or TextAreaStyle\n// content: null,\n\nbuttonMode: 0,  // 0|1|2\n\nbutton: SimpleLabelConfig,\n// buttonA: SimpleLabelConfig\n// buttonB: SimpleLabelConfig\n\n// choice: SimpleLabelConfig,\n// choicesType\n// choicesWidth: undefined,\n// choicesHeight: undefined,\n\n// Space\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\ntitle: 0,\ntitleLeft: 0,\ntitleRight: 0,\n\ncontent: 0,\ncontentLeft: 0,\ncontentRight: 0,\n\nactionsLeft: 0,\nactionsRight: 0,\naction: 0,\n\nchoices: 0,\nchoicesLeft: 0,\nchoicesRight: 0,\nchoice: 0,\nchoiceLine: 0,\nchoiceColumn: 0, choiceRow: 0,\nchoicesBackgroundLeft: 0,\nchoicesBackgroundRight: 0,\nchoicesBackgroundTop: 0,\nchoicesBackgroundBottom: 0,\n},\n\nproportion: {\ntitle: 0,\ncontent: 0,\nactions: 0,\nchoices: 0,\n},\n\nexpand: {\ntitle: true,\ncontent: true,\nactions: false,\nchoices: true,\n},\n\nalign: {\ntitle: 'center',\ncontent: 'center',\nactions: 'center',\nchoices: 'center',\n},\n\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n},\n\nmodal: {\ncover: {\ncolor: 0x0,\nalpha: 0.8,\ntransitIn: function(gameObject, duration) { },\ntransitOut: function(gameObject, duration) { },\n},\n// cover: false, \n\n// When to close modal dialog?\ntouchOutsideClose: false,\nanyTouchClose: false,\ntimeOutClose: false,\nmanualClose: false,\n\nduration: {\nin: 200,\nhold: 2000,\nout: 200\n}\n\ntransitIn: 0,\ntransitOut: 0,\n\ndestroy: true,\n\ndefaultBehavior: true,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n\n// confirmButtonIndex: 0,\n// cancelButtonIndex: 1,\n\n}, creators);\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as background element.
    • null : Don't create any game object.
  • title :
    • Styles of simple-label
    • null : Don't create any game object.
  • content :
    • Styles of simple-label : Create Label as content element.
    • Style of TextArea : Create TextArea as content element.
    • null : Don't create any game object.
  • buttonMode : 0, 1, or 2
    • 0 : No action button, any touch can close modal dialog
    • 1, 2 : Dialog with 1 or 2 action buttons, clicking any action button to close modal dialog.
  • button, buttonA, buttonB, choice :
    • Styles of simple-label, optional.
  • choicesType : Sizer type (Buttons/FixWidthButtons/GridButtons) and behavior (''/'radio'/'checkboxes') of choice buttons.
    • undefined, '', or 'y' : Buttons in vertical/horizontal without any extra behavior, default behavior.
    • 'radio', or 'x-radio' : Buttons in vertical/horizontal, with radio behavior.
      • Name of selected button game object (gameObject.name) will be returned via method dialog.setChoicesSelectedButtonName().
    • 'checkboxes', or 'x-checkboxes' : Buttons in vertical/horizontal, with checkboxes behavior.
      • Name of selected button game object (gameObject.name) will be return via method dialog.getChoicessButtonStates().
    • 'wrap' : FixWidthButtons without any extra behavior, default behavior.
    • 'wrap-radio' : FixWidthButtons with radio behavior.
      • Name of Selected button game object (gameObject.name) will be returned via method dialog.setChoicesSelectedButtonName()
    • 'wrap-checkboxes' : FixWidthButtons with checkboxes behavior.
      • Name of selected button game object (gameObject.name) will be return via method dialog.getChoicessButtonStates().
  • choicesWidth, choicesHeight : Minimum width, minimum height of choices.
    • Must assign choicesHeight value if using GridButtons choices.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.title : Space between title game object and below game object.
    • space.titleLeft, space.titleRight : Extra left/right padding of title game object.
    • space.content : Space between content game object and below game object.
    • space.contentLeft, space.contentRight : Extra left/right padding of content game object.
    • space.action : Space between each action-button game objects.
  • proportion : Keep height of element, or expand height of element.
    • proportion.title : Set to 1 to expand height of title. Default is 0.
    • proportion.content : Set to 1 to expand height of content. Default is 0.
    • proportion.actions : Set to 1 to expand height of actions. Default is 0.
  • expand : Expand width of element
    • expand.title : Set true to expand width of title game object. Default is true.
    • expand.content : Set true to expand width of content game object. Default is true.
    • expand.actions : Set true to expand width of actions game object. Default is false.
  • align : Align element
    • align.title
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value. Will add Spaces at right and left sides.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center. Will add a Space at right side.
    • align.content : Align content game object to 'left'/'center'/'right', if expand.content is false.
    • align.actions : Align action game objects to 'left'/'center'/'right', if expand.actions is false.
  • click: Configuration of button clicking.
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
  • modal : Configuration of modal, See Modal behavior.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false..
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • confirmButtonIndex, cancelButtonIndex : Button index for firing 'confirm', 'cancel' events. Default values are 0, 1.
  • creators : Callbacks for creating components.
    {\nbackground: undefined,\ntitle: undefined,\ncontent: undefined,\nbutton: undefined,\nbuttonA: undefined,\nbuttonB: undefined,\n}\n
    • creators.background : Callback to create background of dialog. Default behavior is creating a round-rectangle-shape.
      function(scene, config)  {\nreturn gameObject;\n}\n
    • creators.title, creators.content, creators.button, creators.buttonA, creators.buttonB : Creators of simple-label, included these properties
      {\nbackground: undefined,\ntext: undefined,\nicon: undefined,\naction: undefined,\n}\n
"},{"location":"ui-confirmdialog/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDialog extends RexPlugins.UI.ConfirmDialog {\nconstructor(scene, config, creators) {\nsuper(scene, config, creators);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var dialog = new MyDialog(scene, config, creators);\n
"},{"location":"ui-confirmdialog/#reset-display-content","title":"Reset display content","text":"
dialog.resetDisplayContent({\ntitle: '',\ncontent: '',\nbuttonA: '',\nbuttonB: '',\n});\n

or

dialog.resetDisplayContent({\ntitle: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\ncontent: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nbuttonA: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nbuttonB: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nchoices: [\n{\ntext: '', value: undefined,\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n},        // ...\n]\n});\n
  • title, content : Display content
    • A string : Set text of simple lable
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
    • null : Hide title or content element.
  • buttonA, buttonB : Display content
    • A string : Set text of simple lable
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
  • choices : Array of display content
    • A string : Set text of simple lable, also use this string as option value.
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
      • Property value : Option value.

Run dialog.layout() after this method, to layout children again.

"},{"location":"ui-confirmdialog/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

dialog.layout();\n

See also - dirty

"},{"location":"ui-confirmdialog/#modal","title":"Modal","text":"

Pop this dialog as modal dialog, close this modal dialog under these conditions :

  • Clicking any action button.
  • Clicking any choice button and no action button on dialog.
dialog.modal(onClose);  // Use default modal config\n

or

dialog.modal({\n// cover: {\n//     color: 0x0,\n//     alpha: 0.8,\n//     transitIn: function(gameObject, duration) { },\n//     transitOut: function(gameObject, duration) { },\n// },\n// cover: false, \n\n// When to close modal dialog?\n// touchOutsideClose: false,\n// anyTouchClose: false,\n// timeOutClose: false,\n// manualClose: false,\n\n// duration: {\n//     in: 200,\n//     hold: 2000,\n//     out: 200\n// }\n\n// transitIn: 0,\n// transitOut: 0,\n\n// destroy: true\n}, onClose);\n

or

dialog\n.modalPromise(config)\n.then(function(data){\n\n})\n
  • config : See Modal behavior
    • config.defaultBehavior :
      • undefined, or true : Will close modal dialog when clicking any action button.
      • false : Disable default behavior.
  • onClose : Callback when closing modal dialog
    function(data) {\n// var index = data.index;\n// var text = data.text;\n// var value = data.value;\n// var button = data.button;\n// var dialog = data.dialog;\n}\n
    • data : Contains these properties
      • data.index : Index of clicking action button
      • data.text : button.text, this property is valided if button game object is a label.
      • data.value :
        • A single value : Return selected value, if choicesType is 'radio'
        • A dictionary contains {value: boolean} : Return selected values, if choicesType is 'checkboxes'
        • undefined : Default value
      • data.button : Clicked button game object.
      • data.dialog : This dialog game object.
"},{"location":"ui-confirmdialog/#button-index","title":"Button index","text":"
  • Confirm button
    • Get
      var confirmButtonIndex = dialog.confirmButtonIndex;\n
    • Set
      dialog.setConfirmButtonIndex(index);\n// dialog.confirmButtonIndex = index;\n
  • Cancel button
    • Get
      var cancelButtonIndex = dialog.cancelButtonIndex;\n
    • Set
      dialog.setCancelButtonIndex(index);\n// dialog.cancelButtonIndex = index;\n
"},{"location":"ui-confirmdialog/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = dialog.getElement('background');\n
    • Title game object
      var title = dialog.getElement('title');\n
    • Content game object
      var content = dialog.getElement('content');\n
    • Buttons game object
      var buttonA = dialog.getElement('buttonA');\nvar buttonB = dialog.getElement('buttonB');\n
  • Get by name
    var gameObject = dialog.getElement('#' + name);\n// var gameObject = dialog.getElement('#' + name, recursive);\n
    or
    var gameObject = dialog.getByName(name);\n// var gameObject = dialog.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-confirmdialog/#other-properties","title":"Other properties","text":"

See dialog, sizer object, base sizer object, container-lite.

"},{"location":"ui-confirmdialog/#events","title":"Events","text":"
  • Click confirm button
    dialog.on('confirm', function (data) {\n// var index = data.index;\n// var text = data.text;\n// var value = data.value;\n// var button = data.button;\n// var dialog = data.dialog;\n}, scope);\n
    • data : See modal
  • Click cancel button
    dialog.on('cancel', function (data) {\n// var index = data.index;\n// var text = data.text;\n// var value = data.value;\n// var button = data.button;\n// var dialog = data.dialog;\n}, scope);\n
    • data : See modal
"},{"location":"ui-dialog/","title":"Dialog","text":""},{"location":"ui-dialog/#introduction","title":"Introduction","text":"

A container with a title, content, buttons and background.

  • Author: Rex
  • Game object
"},{"location":"ui-dialog/#live-demos","title":"Live demos","text":"
  • Dialog
  • Yes-no dialog
  • Action buttons with Space
  • Radio choices dialog
  • Horizontal-radio choices dialog
  • Wrap-radio choices dialog
  • Wrap-checkboxes choices dialog
  • Grid-checkboxes choices dialog
  • Popup/scaledown
    • Pop-up dialog
  • Ease-in, ease-out
  • Show/hide buttons
  • Add button
  • Wrap label
  • Modal dialog
  • Content sizer
"},{"location":"ui-dialog/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-dialog/#install-plugin","title":"Install plugin","text":""},{"location":"ui-dialog/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add dialog object
    var dialog = scene.rexUI.add.dialog(config);\n
"},{"location":"ui-dialog/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add dialog object
    var dialog = scene.rexUI.add.dialog(config);\n
"},{"location":"ui-dialog/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Dialog } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add dialog object
    var dialog = new Dialog(scene, config);\nscene.add.existing(dialog);\n
"},{"location":"ui-dialog/#add-dialog-object","title":"Add dialog object","text":"
var dialog = scene.rexUI.add.dialog({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\nbackground: backgroundGameObject,\n\ntitle: titleGameObject,\n\ntoolbarBackground: toolbarBackgroundGameObject,\ntoolbar: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\n\nleftToolbarBackground: leftToolbarBackgroundGameObject,\nleftToolbar: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\n\ncontent: contentGameObject,\n\ndescription: descriptionGameObject,\n\nchoicesType: '',\n// choicesWidth: undefined,\n// choicesHeight: undefined,  // Used when choicesType is `'grid'`, `'grid-radio'`, or `'grid-checkboxes'`\nchoicesBackground: choicesBackgroundGameObject,\nchoices: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\n\nactionsBackground: actionsBackgroundGameObject,\nactions: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\n\n// Space\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\ntitle: 0,\ntitleLeft: 0,\ntitleRight: 0,\ntitleTop: 0,\n\ntoolbarItem: 0,\nleftToolbarItem: 0,\n\ncontent: 0,\ncontentLeft: 0,\ncontentRight: 0,\n\ndescription: 0,\ndescriptionLeft: 0,\ndescriptionRight: 0\n\nchoices: 0,\nchoicesLeft: 0,\nchoicesRight: 0,\n\n// choiceLine: 0,   // Used when choicesType is `'wrap'`, `'wrap-radio'`, or `'wrap-checkboxes'`\n// choiceColumn: 0, // Used when choicesType is `'grid'`, `'grid-radio'`, or `'grid-checkboxes'`\n// choiceRow: 0,    // Used when choicesType is `'grid'`, `'grid-radio'`, or `'grid-checkboxes'`\nchoicesBackgroundLeft: 0,\nchoicesBackgroundRight: 0,\nchoicesBackgroundTop: 0,\nchoicesBackgroundBottom: 0,\n\naction: 0,\nactionsLeft: 0,\nactionsRight: 0,\nactionsBottom: 0,\n\n},\n\nproportion: {\ntitle: 0,\ncontent: 0,\ndescription: 0,\nchoices: 0,\nactions: 0,\n},\n\nexpand: {\ntitle: true,\ncontent: true,\ndescription: true,\nchoices: true,\nactions: false,\n},\n\nalign: {\ntitle: 'center',\ncontent: 'center',\ndescription: 'center',\nchoices: 'center',\nactions: 'center',\n},\n\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n}\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of dialog.
  • title : Game object of title, optional.
  • toolbar : Array of Game objects for toolbar-buttons group which arranged from left to right, optional.
    • [] : Assign an empty array if user will add button later.
  • toolbarBackground : Game object of toolbar buttons background, optional. This background game object will be resized to fit the size of dialog.
  • leftToolbar : Array of Game objects for left-toolbar-buttons group which arranged from left to right, optional.
    • [] : Assign an empty array if user will add button later.
  • leftToolbarBackground : Game object of leftToolbar buttons background, optional. This background game object will be resized to fit the size of dialog.
  • content : Game object of content, optional.
  • description : Game object of description, optional.
  • choices : Array of Game objects for choice-buttons group which arranged from top to bottom, optional.
    • Array of Game objects, for Buttons/FixWidthButtons choices.
      • [] : Assign an empty array if user will add button later.
    • 2d Array of Game objects, for GridButtons choices..
  • choicesBackground : Game object of choices buttons background, optional. This background game object will be resized to fit the size of dialog.
  • choicesType : Sizer type (Buttons/FixWidthButtons/GridButtons) and behavior (''/'radio'/'checkboxes') of choice buttons.
    • undefined, 'x', or 'y' : Buttons in vertical/horizontal without any extra behavior, default behavior.
    • 'radio', or 'x-radio' : Buttons in vertical/horizontal, with radio behavior.
      • Name of selected button game object (gameObject.name) will be returned via method dialog.setChoicesSelectedButtonName().
    • 'checkboxes', or 'x-checkboxes' : Buttons in vertical/horizontal, with checkboxes behavior.
      • Name of selected button game object (gameObject.name) will be return via method dialog.getChoicessButtonStates().
    • 'wrap' : FixWidthButtons without any extra behavior, default behavior.
    • 'wrap-radio' : FixWidthButtons with radio behavior.
      • Name of Selected button game object (gameObject.name) will be returned via method dialog.setChoicesSelectedButtonName()
    • 'wrap-checkboxes' : FixWidthButtons with checkboxes behavior.
      • Name of selected button game object (gameObject.name) will be return via method dialog.getChoicessButtonStates().
    • 'grid' : GridButtons without any extra behavior, default behavior.
    • 'grid-radio' : GridButtons with radio behavior.
      • Name of Selected button game object (gameObject.name) will be returned via method dialog.setChoicesSelectedButtonName()
    • 'grid-checkboxes' : GridButtons with checkboxes behavior.
      • Name of selected button game object (gameObject.name) will be return via method dialog.getChoicessButtonStates().
  • choicesWidth, choicesHeight : Minimum width, minimum height of choices.
    • Must assign choicesHeight value if using GridButtons choices.
  • actions : Array of Game objects, or Space (scene.rexUI.add.space()) for action-buttons group which arranged from left to right, optional.
    • [] : Assign an empty array if user will add button later.
  • choicesBackground : Game object of choices buttons background, optional. This background game object will be resized to fit the size of dialog.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.title : Space between title game object and below game object.
    • space.titleLeft, space.titleRight : Extra left/right padding of title game object.
    • space.content : Space between content game object and below game object.
    • space.contentLeft, space.contentRight : Extra left/right padding of content game object.
    • space.description : Space between description game object and below game object.
    • space.descriptionLeft, space.descriptionRight : Extra left/right padding of description game object.
    • space.choices : Space between last choice-button and below game object.
    • space.choicesLeft, space.choicesRight : Extra left/right padding of choice buttons.
    • space.actionsLeft, space.actionsRight : Extra left/right padding of actions buttons.
    • space.toolbarItem : Space between each toolbar item game objects.
    • space.leftToolbarItem : Space between each left-toolbar item game objects.
    • space.choice : Space between each choice-button game objects.
    • space.choicesBackgroundLeft, space.choicesBackgroundRight, space.choicesBackgroundTop, space.choicesBackgroundBottom : Padding space around choices-background.
    • space.action : Space between each action-button game objects.
  • proportion : Keep height of element, or expand height of element.
    • proportion.title : Set to 1 to expand height of title. Default is 0.
    • proportion.content : Set to 1 to expand height of content. Default is 0.
    • proportion.description : Set to 1 to expand height of description. Default is 0.
    • proportion.choices : Set to 1 to expand height of choices. Default is 0.
    • proportion.actions : Set to 1 to expand height of actions. Default is 0.
  • expand : Expand width of element
    • expand.title : Set true to expand width of title game object. Default is true.
    • expand.content : Set true to expand width of content game object. Default is true.
    • expand.description : Set true to expand width of description game object. Default is true.
    • expand.choices : Set true to expand width of choices game object. Default is true.
    • expand.actions : Set true to expand width of actions game object. Default is false.
  • align : Align element
    • align.title
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value. Will add Spaces at right and left sides.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center. Will add a Space at right side.
    • align.content : Align content game object to 'left'/'center'/'right', if expand.content is false.
    • align.description : Align description game object to 'left'/'center'/'right', if expand.description is false.
    • align.choices : Align choices game object to 'left'/'center'/'right', if expand.choices is false.
    • align.actions : Align action game objects to 'left'/'center'/'right', if expand.actions is false.
  • click: Configuration of button clicking.
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false..
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-dialog/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDialog extends RexPlugins.UI.Dialog {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var dialog = new MyDialog(scene, config);\n
"},{"location":"ui-dialog/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

dialog.layout();\n

See also - dirty

"},{"location":"ui-dialog/#modal","title":"Modal","text":"

Pop this dialog as modal dialog, clicking any action button to close this modal dialog.

dialog.modal({\n// cover: {\n//     color: 0x0,\n//     alpha: 0.8,\n//     transitIn: function(gameObject, duration) { },\n//     transitOut: function(gameObject, duration) { },\n// },\n// cover: false, \n\n// When to close modal dialog?\n// touchOutsideClose: false,\n// anyTouchClose: false,\n// timeOutClose: false,\n// manualClose: false,\n\n// duration: {\n//     in: 200,\n//     hold: 2000,\n//     out: 200\n// }\n\n// transitIn: 0, // 0|'popUp'|1|'fadeIn'\n// transitIn: function(gameObject, duration) { },\n\n// transitOut: 0, // 0|'scaleDown'|1|'fadeOut'\n// transitOut: function(gameObject, duration) { },\n\n// destroy: true,\n\n// defaultBehavior: true,\n});\n// dialog.modal(config, onClose);\n

or

dialog\n.modalPromise(config)\n.then(function(data){\n\n})\n
  • config : See Modal behavior
    • config.defaultBehavior :
      • undefined, or true : Will close modal dialog when clicking any action button.
      • false : Disable default behavior. User has to invoke dialog.modalClose(data) manually.
  • onClose : Callback when closing modal dialog
    function(data) {\n// var index = data.index;\n// var text = data.text;\n// var button = data.button;\n// var dialog = data.dialog;\n}\n
    • data : Contains these properties
      • data.index : Index of clicking action button
      • data.text : button.text, this property is valided if button game object is a label.
      • data.button : Clicked button game object.
      • data.dialog : This dialog game object.
"},{"location":"ui-dialog/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-dialog/#events","title":"Events","text":"
  • Click button
    dialog.on('button.click', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
    or
    dialog.on('choice.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('action.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('toolbar.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('leftToolbar.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'choices', 'actions', or 'toolbar', 'leftToolbar'.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-over button
    dialog.on('button.over', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
    or
    dialog.on('choice.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('action.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('toolbar.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('leftToolbar.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Triggered button game object
    • groupName : 'choices', 'actions', 'toolbar', or 'leftToolbar'.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-out button
    dialog.on('button.out', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
    or
    dialog.on('choice.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('action.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('toolbar.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('leftToolbar.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'choices', 'actions', 'toolbar', or 'leftToolbar'
    • index : Index of triggered button game object.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Enable button's input
    dialog.on('button.enable', function(button, groupName, index) {\n// ...\n}, scope);\n
    or
    dialog.on('choice.enable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('action.enable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('toolbar.enable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('leftToolbar.enable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'choices', 'actions', 'toolbar', or 'leftToolbar'
    • index : Index of triggered button game object.
  • Disable button's input
    dialog.on('button.disable', function(button, groupName, index) {\n// ...\n}, scope);\n
    or
    dialog.on('choice.disable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('action.disable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('toolbar.disable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('leftToolbar.disable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'choices', 'actions', 'toolbar', or 'leftToolbar'
    • index : Index of triggered button game object.
"},{"location":"ui-dialog/#emit-button-click-event","title":"Emit button click event","text":"
  • Emit choice/action/toolbar/left-toolbar button's click event
    dialog.emitChoiceClick(index);\ndialog.emitActionClick(index);\ndialog.emitToolbarClick(index);\ndialog.emitLeftToolbarClick(index);\n
    • index : A number index, or a button game object.
"},{"location":"ui-dialog/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = dialog.getElement('background');\n
    • Title game object
      var title = dialog.getElement('title');\n
    • Content game object
      var content = dialog.getElement('content');\n
    • Description game object
      var description = dialog.getElement('description');\n
    • Choice button game object
      var buttons = dialog.getElement('choices');\n
      or
      var button = dialog.getChoice(index);\n
      or
      var button = dialog.getElement('choices[' + index + ']');\n
    • Action button game object
      var buttons = dialog.getElement('actions');\n
      or
      var button = dialog.getAction(index);\n
      or
      var button = dialog.getElement('actions[' + index + ']');\n
    • Toolbar button game object
      var buttons = dialog.getElement('toolbar');\n
      or
      var button = dialog.getToolbar(index);\n
      or
      var button = dialog.getElement('toolbar[' + index + ']');\n
    • Left-toolbar button game object
      var buttons = dialog.getElement('leftToolbar');\n
      or
      var button = dialog.getLeftToolbar(index);\n
      or
      var button = dialog.getElement('leftToolbar[' + index + ']');\n
  • Get by name
    var gameObject = dialog.getElement('#' + name);\n// var gameObject = dialog.getElement('#' + name, recursive);\n
    or
    var gameObject = dialog.getByName(name);\n// var gameObject = dialog.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-dialog/#add-button","title":"Add button","text":"

Add choice/action/toolbar/left-toolbar button

dialog.addChoice(gameObject);\ndialog.addAction(gameObject);\ndialog.addToolbar(gameObject);\ndialog.addLeftToolbar(gameObject);\n
  • gameObject : A game object, or an array of game objects.
"},{"location":"ui-dialog/#remove-button","title":"Remove button","text":"
  • Remove a choice/action/toolbar/left-toolbar button
    dialog.removeChoice(index, destroyChild);\ndialog.removeAction(index, destroyChild);\ndialog.removeToolbar(index, destroyChild);\ndialog.removeLeftToolbar(index, destroyChild);\n
    • index : A number index, a string name, or a button game object.
    • destroyChild : Set true to destroy button game object.
  • Remove all choice/action/toolbar/left-toolbar buttons
    dialog.clearChoices(destroyChild);\ndialog.clearActions(destroyChild);\ndialog.clearToolbar(destroyChild);\ndialog.clearLeftToolbar(destroyChild);\n
    • destroyChild : Set true to destroy button game object.
"},{"location":"ui-dialog/#enabledisable-input-of-button","title":"Enable/disable input of button","text":"
  • Enable choice/action/toolbar/left-toolbar button
    dialog.setChoiceEnable(index);\ndialog.setActionEnable(index);\ndialog.setToolbarEnable(index);\ndialog.setLeftToolbarEnable(index);\n
    • index : A number index, or a button game object.
  • Enable all buttons
    dialog.setAllButtonsEnable();\n
  • Disable choice/action/toolbar/left-toolbar button's input
    dialog.setChoiceEnable(index, false);\ndialog.setActionEnable(index, false);\ndialog.setToolbarEnable(index, false);\ndialog.setLeftToolbarEnable(index, false);\n
    • index : A number index, or a button game object.
  • Disable all buttons
    dialog.setAllButtonsEnable(false);\n
  • Toggle choice/action/toolbar/left-toolbar button's input
    dialog.toggleChoiceEnable(index);\ndialog.toggleActionEnable(index);\ndialog.toggleToolbarEnable(index);\ndialog.toggleLeftToolbarEnable(index);\n
    • index : A number index, or a button game object.
  • Get choice/action/toolbar/left-toolbar button's input enable
    var enabled = dialog.getChoiceEnable(index);\nvar enabled = dialog.getActionEnable(index);\nvar enabled = dialog.getToolbarEnable(index);\nvar enabled = dialog.getLeftToolbarEnable(index);\n
    • index : A number index, or a button game object.
"},{"location":"ui-dialog/#showhide-button","title":"Show/hide button","text":"

Hidden elements won't be counted when layouting. Call dialog.layout(), or topSizer.layout() after show/hide any button.

  • Show choice/action/toolbar/left-toolbar button
    dialog.showChoice(index);\ndialog.showAction(index);\ndialog.showToolbar(index);\ndialog.showLeftToolbar(index);\n
    • index : A number index, a string name, or a button game object.
  • Hide choice/action/toolbar/left-toolbar button.
    dialog.hideChoice(index);\ndialog.hideAction(index);\ndialog.hideToolbar(index);\ndialog.hideLeftToolbar(index);\n
    • index : A number index, a string name, or a button game object.
"},{"location":"ui-dialog/#for-each-button","title":"For each button","text":"
dialog.forEachChoice(callback, scope);\ndialog.forEachAction(callback, scope);\ndialog.forEachToolbar(callback, scope);\ndialog.forEachLeftToolbar(callback, scope);\n
  • callback :
    function(button, index, buttons) {\n// ...\n}\n
"},{"location":"ui-dialog/#state-of-choices-buttons","title":"State of choices buttons","text":""},{"location":"ui-dialog/#radio","title":"Radio","text":"
  • Read state
    var value = dialog.getChoicesSelectedButtonName();\n
  • Set state
    dialog.setChoicesSelectedButtonName(name);\n
"},{"location":"ui-dialog/#checkboxes","title":"Checkboxes","text":"
  • Read states
    var states = dialog.getChoicesButtonStates();\n
    • states : {name: boolean}
  • Set state
    dialog.setChoicesButtonState(name, state);\n
    • name : Name of button game object
    • state : Set true if button is selected
  • Clear all states to false
    dialog.clearChoicesButtonStates();\n
"},{"location":"ui-dialog/#events_1","title":"Events","text":"
  • On button state changed. For Checkboxes/radio
    dialog.on('button.statechange', function(button, groupName, index, value, previousValue) {\n// ...\n}, scope);\n
    • Can be used to replace setValueCallback.
"},{"location":"ui-dropdownlist/","title":"Drop down list","text":""},{"location":"ui-dropdownlist/#introduction","title":"Introduction","text":"

A label can open a drop-down list panel.

  • Author: Rex
  • Game object
"},{"location":"ui-dropdownlist/#live-demos","title":"Live demos","text":"
  • Drop-down list
  • Drop-down wrap-list
  • Custom transit
  • Align to right side
  • Cursor select
  • Drop-down scrollable-list
"},{"location":"ui-dropdownlist/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-dropdownlist/#install-plugin","title":"Install plugin","text":""},{"location":"ui-dropdownlist/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add drop-down list object
    var dropDownList = scene.rexUI.add.dropDownList(config);\n
"},{"location":"ui-dropdownlist/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add drop-down list object
    var dropDownList = scene.rexUI.add.dropDownList(config);\n
"},{"location":"ui-dropdownlist/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { DropDownList } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add dropDownList object
    var dropDownList = new DropDownList(scene, config);\nscene.add.existing(dropDownList);\n
"},{"location":"ui-dropdownlist/#add-drop-down-list-object","title":"Add drop-down list object","text":"
var dropDownList = scene.rexUI.add.dropDownList({\noptions: [\noption0,\noption1,\n// ...\n],\n\nlist: {\n// createBackgroundCallback: function(scene) {\n//     // this : dropDownList\n//     return gameObject;\n// },\n\ncreateButtonCallback: function(scene, option, index, options) {\n// this : dropDownList\nreturn gameObject;\n},\n\n// createTrackCallback: function(scene) {\n//     // this : dropDownList\n//     return gameObject;\n// },\n\n// createThumbCallback: function(scene) {\n//     // this : dropDownList\n//     return gameObject;\n// },\n\nmouseWheelScroller: undefined,\n// mouseWheelScroller: {\n//     focus: true,\n//     speed: 0.1\n// },\n\nonButtonClick: function(button, index, pointer, event) {\n// this : dropDownList\n},\n\n// onButtonOver: function(button, index, pointer, event) {\n//     // this : dropDownList\n// },\n\n// onButtonOut: function(button, index, pointer, event) {\n//     // this : dropDownList\n// },\n\n// easeIn: 500,\n// transitIn: undefined,\n// transitIn: function(listPanel, duration) {  },\n\n// easeOut: 100,\n// transitOut: undefined,\n// transitOut: function(listPanel, duration) {  },\n\n// wrap: false,\n// maxHeight: undefined,\n// width: undefined, \n// height: undefined,\n// alignParent: 'text',\n// alignSide: '',\n// expandDirection: 0,\n// bounds: undefined,\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom: 0, item: 0,\n//     line: 0\n// },\n\n// draggable: false\n},\n\nsetValueCallback: function(dropDownList, value, previousValue) {\n\n},\nsetValueCallbackScope: undefined,\nvalue: undefined,\n\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\nicon: iconGameObject,\niconMask: false,\ntext: textGameObject,\nexpandTextWidth: false,\nexpandTextHeight: false,\naction: actionGameObject,\nactionMask: false,\nalign: undefined,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0,\ntext: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • options : Array of strings, or objects.
  • list : Configuration of list panel.
    • list.createBackgroundCallback : Create background of list panel
      function(scene) {\n// this : dropDownList\nreturn gameObject;\n}\n
    • list.createButtonCallback : Create option button of list panel
      function(scene, option, index, options) {\n// this : dropDownList\nreturn gameObject;\n}\n
    • list.createTrackCallback : Create slider's track of list panel, optional.
      function(scene) {\n// this : dropDownList\nreturn gameObject;\n}\n
    • list.createThumbCallback : Create slider's thumb of list panel, optional.
      function(scene) {\n// this : dropDownList\nreturn gameObject;\n}\n
    • list.mouseWheelScroller : Configuration of mouse-wheel-scroller behavior.
      • list.mouseWheelScroller.focus :
        • false, or 0 : Without checking if cursor is over game object or not.
        • true, or 1 : Cursor is inside the rectangle bounds of game object. Default behavior.
        • 2 : Cursor is over game object.
      • list.mouseWheelScroller.speed : Scrolling speed, default value is 0.1.
      • Set to false to skip creating mouse-wheel-scroller. Default behavior.
    • list.onButtonClick : Callback when clicking a button
      function(button, index, pointer, event) {\n// this : dropDownList\n}\n
    • list.onButtonOver : Callback when pointer over a button
      function(button, index, pointer, event) {\n// this : dropDownList\n}\n
    • list.onButtonOut : Callback when pointer out a button
      function(button, index, pointer, event) {\n// this : dropDownList\n}\n
    • list.easeIn : Pop-up duration in ms. Default value is 500.
    • list.transitIn : Tween behavior of opening list panel.
      • undefined : Expand list panel by pop-up, default behavior.
      • Custom callback
        function(listPanel, duration) {\n\n}\n
    • list.easeOut : Scale-down duration in ms. Default value is 100.
    • list.transitOut : Tween behavior of closing list panel.
      • undefined : Closing list panel by scale-down, default behavior.
      • Custom callback
        function(listPanel, duration) {\n\n}\n
    • list.wrap : Layout mode of buttons
      • true : fixwidth-sizer layout.
      • false : sizer layout. Default behavior.
    • list.maxHeight : If height of button list is larger than this maxHeight, put this button list into scrollable panel.
      • undefined, or 0 : Ignore this behavior.
      • > 0 and list.createThumbCallback parameter is given : If height of button list is larger than this maxHeight, put this button list into scrollable panel.
    • list.width : Minimum width.
      • undefined : Minimum width of panel will equal to width of parent label. Default value.
      • A number : Width of panel. Required fields when list.wrap is true.
    • list.height : Minimum height.
      • undefined : Create button list or wrap button list. Default value.
      • > 0 and list.createThumbCallback parameter is given : Create scrollable button list or wrap button list.
    • list.alignParent : Align x position to label.
      • 'icon' : Align x position to icon game object of parent label.
      • 'text' : Align x position to text game object of parent label. Default behavior
      • 'label', or null : Align x position to parent label.
    • list.alignSide : Align list to label's left or right side.
      • undefined, or 'left' : Align list's left side to label's left side. Default behavior.
      • 'right : Align list's right side to label's right side. Default behavior.
    • list.expandDirection :
      • 0, 'down' : Expand list down. i.e. list panel will put below parent label.
      • 1, 'up' : Expand list up. i.e. list panel will put above parent label.
    • list.bounds : Put list panel below parent label if bottom of list panel is inside bounds (Rectangle)
      • undefined : Use viewport as bounds
      • Rectangle
    • list.space : space properties of list panel.
      • left, right, top, bottom, item : For sizer layout. (list.wrap is false)
      • left, right, top, bottom, item, line : For fixwidth-sizer layout. (list.wrap is true)
    • list.draggable : Set true to drag top-most object.
  • value, setValueCallback, setValueCallbackScope : See value
    function(dropDownList, value, previousValue) {\n\n}\n
  • Properties of Label
    • x, y : Position of this object, it is valid when this object is the top object.
    • anchor : See anchor.
      • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
        • Percentage of visible width/height : 'p%', p: 0 ~ 100.
          • 'left'(=0%), 'center'(=50%), 'right'(=100%)
          • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
        • Offset : '+n', or '-n'.
      • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
        • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • Padding : '+n', or '-n'.
      • onResizeCallback : A default resize callback will be assigned interanlly.
    • width, height : Minimum width, minimum height.
    • orientation :
      • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
      • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
    • rtl :
      • true : Layout children from right to left.
      • false : Layout children from left to right. Default behavior.
    • background : Game object of background, optional. This background game object will be resized to fit the size of label.
    • icon : Game object of icon, optional.
    • iconMask : Set true to add a circle mask on icon game object.
      • Phaser 3 engine does not support nested mask, uses circle mask image instead.
    • text : Game object of text, optional.
    • expandTextWidth : Set true to expand width of text object.
    • expandTextHeight : Set true to expand height of text object.
    • action : Game object of action icon, optional.
    • actionMask : Set true to add a circle mask on action icon game object.
      • Phaser 3 engine does not support nested mask, uses circle mask image instead.
    • align : Alignment of icon, text, action-icon game objects.
      • undefined, or 'left', or 'top' : Align game objects at left, or top.
      • 'center' : Align game objects at center.
      • 'right', or 'bottom' : Align game objects at right, or bottom.
    • space : Pads spaces.
      • space.left, space.right, space.top, space.bottom : Space of bounds.
      • space.icon : Space between icon game object and text game object.
      • space.text : Space between text game object and action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-dropdownlist/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDropDownList extends RexPlugins.UI.DropDownList {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var dropDownList = new MyDropDownList(scene, config);\n
"},{"location":"ui-dropdownlist/#options","title":"Options","text":"
  • Set
    dropDownList.setOptions(options);\n
    or
    dropDownList.options = options;\n
    • options : Array of strings, or objects.
  • Get
    var options = dropDownList.options;\n
"},{"location":"ui-dropdownlist/#clicking","title":"Clicking","text":"
  • Enable
    dropDownList.enableClick();\n
  • Disable
    dropDownList.disableClick();\n
  • Register another clicking callback
    dropDownList.onClick(callback, scope);\n
"},{"location":"ui-dropdownlist/#emit-button-click-event","title":"Emit button click event","text":"
dropDownList.emitButtonClick(index);\n// dropDownList.emitButtonClick();\n
  • index : Index of button/option.
    • undefined : Click current focus (over) button.

Will fire 'button.click' event

dropDownList.on('button.click', function(dropDownList, listPanel, button, index, pointer, event) {\n// ...\n}, scope);\n
  • listPanel : listPanel, or undefined if list is not created.
  • button : Button game object, or option if list is not created.
  • pointer : undefined
  • event : undefined

This method won't close list panel.

"},{"location":"ui-dropdownlist/#emit-button-over-event","title":"Emit button over event","text":"
dropDownList.emitButtonOver(index);\n
  • index : Index of button/option.

or

dropDownList.focusNextButton();\ndropDownList.focusPrevButton();\n

Will fire 'button.out', 'button.over' event

dropDownList.on('button.out', function(dropDownList, listPanel, button, index, pointer, event) {\n// ...\n}, scope);\n
dropDownList.on('button.over', function(dropDownList, listPanel, button, index, pointer, event) {\n// ...\n}, scope);\n

  • listPanel : listPanel, or undefined if list is not created.
  • button : Button game object, or option if list is not created.
  • pointer : undefined
  • event : undefined
"},{"location":"ui-dropdownlist/#value","title":"Value","text":"
  • Set value under list.onButtonClick callback.
    dropDownList.setValue(value);\n
    or
    dropDownList.value = value;\n
    • When value changing
      • Will invoke setValueCallback
        function(dropDownList, value, previousValue) {\n\n}\n
      • Will fire 'valuechange' event
  • Get
    var value = dropDownList.value;\n
"},{"location":"ui-dropdownlist/#openclose-list-panel","title":"Open/close list panel","text":""},{"location":"ui-dropdownlist/#open-list-panel","title":"Open list panel","text":"
  • Click parent label to open (create and pop-up) list panel.
  • Or invoke this method dropDownList.openListPanel().
"},{"location":"ui-dropdownlist/#close-list-panel","title":"Close list panel","text":"
  • When list panel is opened, click any where will close (scale-down then destroy) this list panel.
  • Or invoke this method dropDownList.closeListPanel().
"},{"location":"ui-dropdownlist/#toggle-list-panel","title":"Toggle list panel","text":"
dropDownList.toggleListPanel();\n
"},{"location":"ui-dropdownlist/#is-list-opened","title":"Is list opened","text":"
var isOpened = dropDownList.isOpened;\n
"},{"location":"ui-dropdownlist/#other-properties","title":"Other properties","text":"

See label object, sizer object, base sizer object, container-lite.

"},{"location":"ui-dropdownlist/#events","title":"Events","text":"
  • Open list
    dropDownList.on('list.open', function(dropDownList, listPanel) {\n\n})\n
  • Close list
    dropDownList.on('list.close', function(dropDownList, listPanel) {\n\n})\n
  • Click button
    dropDownList.on('button.click', function(dropDownList, listPanel, button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Game object of triggered button on list panel.
    • index : Index of triggered button.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Over button
    dropDownList.on('button.over', function(dropDownList, listPanel, button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Game object of triggered button on list panel.
    • index : Index of triggered button.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Out button
    dropDownList.on('button.out', function(dropDownList, listPanel, button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Game object of triggered button on list panel.
    • index : Index of triggered button.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • On value changing
    dropDownList.on('valuechange', function(dropDownList, value, previousValue) {\n// ...\n}, scope);\n
"},{"location":"ui-expbar/","title":"Exp bar","text":""},{"location":"ui-expbar/#introduction","title":"Introduction","text":"

Disply experience bar on NameValueLabel.

  • Author: Rex
  • Game object
"},{"location":"ui-expbar/#live-demos","title":"Live demos","text":"
  • Exp bar
  • Custom bar
"},{"location":"ui-expbar/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-expbar/#install-plugin","title":"Install plugin","text":""},{"location":"ui-expbar/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add expBar object
    var expBar = scene.rexUI.add.expBar(config);\n
"},{"location":"ui-expbar/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add expBar object
    var expBar = scene.rexUI.add.expBar(config);\n
"},{"location":"ui-expbar/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ExpBar } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add expBar object
    var expBar = new ExpBar(scene, config);\nscene.add.existing(expBar);\n
"},{"location":"ui-expbar/#add-expbar-object","title":"Add expBar object","text":"
var expBar = scene.rexUI.add.expBar({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\nicon: iconGameObject,\niconMask: false,\n\nnameText: nameTextGameObject,\nvalueText: valueTextGameObject,\n// valueTextFormatCallback: function(value, min, max) {\n//     return `${value}/${max}`;\n// },\n// valueTextFormatCallback: null,\n\n// barShape: 'line',   // 'line', or 'circle'\n\n// line bar\nbar: {\ntrackColor: undefined,\ntrackThickness: 2,\ntrackStrokeColor: undefined,\nbarColor: undefined,\nbarColor2: undefined,\n\nskewX: 0,\n\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'linear'\n},\n}, // circle bar\n/*\n    bar: {\n        barColor: undefined,\n        barColor2: undefined,\n        trackColor: undefined,\n        centerColor: undefined,\n        thickness: 0.2,\n        startAngle: Phaser.Math.DegToRad(270),\n        endAngle: Phaser.Math.DegToRad(270+360),\n        anticlockwise: false,\n    }\n    */\n\n// bar: CustomProgressGameObject,\n\n// bar: undefined,\n\naction: actionGameObject,\nactionMask: false,\n\nalign: {        text: 'bottom',  // 'top', 'center', 'bottom'\n},\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0, iconTop: 0, iconBottom: 0,\nname: 0, value: 0,\nbar:0, barBottom: 0, barLeft: 0, barRight: 0,\ntext: 0,\nactionTop: 0, actionBottom: 0,\n},\n\n// easeDuration: 1000,\n\nlevelCounter: {\ntable: function(level) { return level * 100; },\n// table: [0, 100, 200, 300,],        \n// maxLevel: -1,        \n// exp: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of expBar.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • nameText : Game object of nameText.
    • OriginX of nameText will be set to 0.
    • Empty text will be set to a space character ' '. To preserve height of this text game object.
  • valueText : Game object of valueText.
    • OriginX of nameText will be set to 1.
    • Empty text will be set to a space character ' '. To preserve height of this text game object.
  • valueTextFormatCallback : Callback to return a string set to valueText game object when invokeing label.setValue(value, min, max) method.
    • A callback
      function(value, min, max) {\nreturn `${value}/${max}`;\n}\n
    • null, or false : Don't set valueText game object.
  • barShape : 'line' or 'circle'.
  • bar : Game object of bar, or config of horizontal line progress bar, or config of circular progress bar or undefined.
    • Config of horizontal line progress bar
      • bar.trackColor : Fill color of bar's track, in number or css string value.
      • bar.trackStrokeColor : Stroke color of bar's track, in number or css string value.
      • bar.trackThickness : Stroke line width of bar's track.
      • bar.barColor, bar.barColor2 : Fill color of bar, in number or css string value. Assign gradient start color by barColor2.
      • bar.skewX : Horizontal skew of track and bar.
      • bar.rtl :
        • false : Bar starts from left side. Default behavior.
        • true : Bar starts from right side.
    • Config of circular progress bar
      • bar.shape : 'circle'
      • bar.barColor, bar.barColor2 : Fill color of circular bar, in number or css string value. Assign gradient start color by barColor2.
      • bar.trackColor : Color of circular track, in number or css string value.
      • bar.centerColor : Color of center circle, in number or css string value.
      • bar.thickness : 0 ~ 1, thickness of circular bar. Default value is 0.2 (0.2*radius)
      • bar.startAngle : Start angle of circular bar, in radians. Default value is 270 degrees.
      • bar.endAngle : End angle of circular bar, in radians. Default value is 270+360 degrees.
      • bar.anticlockwise : Set true to put anticlockwise circular bar. Default value is false.
    • (CustomProgress) Game object.
    • undefined : No bar game object.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • align :
    • align.text : Alignment of nameText, valueText game objects.
      • 'top', 'center', or 'bottom'. Default value is 'bottom'.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.icon : Space between icon game object and text game object.
    • space.iconTop, space.iconBottom : Space around icon game object.
    • space.name : Left space of nameText game object.
    • space.value : Right space of valueText game object.
    • space.bar, space.barLeft, space.barRight, space.barBottom : Space around bar game object.
    • space.text : Space between text game object and action icon game object.
    • space.actionTop, space.actionBottom : Space around action game object.
  • easeDuration : Total duration of easing value from level-start to level-end. Default value is 1000 ms.
  • levelCounter : Config of level-counter
    • levelCounter.table : Level table, return experience value from level value. Level value starts from 0.
      • A callback
        function(level) {\nreturn experience;\n}\n
      • A number array : Experience value of each level.
    • levelCounter.maxLevel :
      • undefined : Default value
        • No upper limit for callback level table.
        • (table.length - 1) for number array level table.
      • A number : Maximum level value
    • levelCounter.exp : Initial experience value. Default value is 0.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-expbar/#custom-class","title":"Custom class","text":"
  • Define class
    class MyExpBar extends RexPlugins.UI.ExpBar {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var expBar = new MyExpBar(scene, config);\n
"},{"location":"ui-expbar/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

expBar.layout();\n

See also - dirty

"},{"location":"ui-expbar/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = expBar.getElement('background');\n
    • Icon game object
      var icon = expBar.getElement('icon');\n
    • NameText game object
      var nameTextObject = expBar.getElement('name');\n
    • ValueText game object
      var valueTextObject = expBar.getElement('value');\n
    • Bar game object
      var textObject = expBar.getElement('bar');\n
    • Action icon game object
      var action = expBar.getElement('action');\n
  • Get by name
    var gameObject = expBar.getElement('#' + name);\n// var gameObject = expBar.getElement('#' + name, recursive);\n
    or
    var gameObject = expBar.getByName(name);\n// var gameObject = expBar.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-expbar/#accumulate-experience","title":"Accumulate experience","text":"
  • Accumulate experience
    expBar.gainExp(incExp);\n// expBar.exp += incExp;\n
    • Will fire 'levelup' event
  • Reset experience value
    expBar.resetExp(exp);\n
    • Won't fire 'levelup' event.
  • Force level up
    expBar.setLevel(level);\n
    • Will fire 'levelup' event
"},{"location":"ui-expbar/#level-and-experience","title":"Level and experience","text":"
  • Get current experience
    var exp = expBar.getExp();\n// var exp = expBar.exp;\n
  • Get current level
    var level = expBar.getLevel();\n// var level = expBar.level;\n
  • Get current required experience to next level
    var exp = expBar.requiredExp;\n
  • Get experience of level
    var exp = expBar.getExp(level);\n
  • Get level from experience
    var level = expBar.getLevel(exp);\n
  • Get required experience to level
    var exp = expBar.getRequiredExpToNextLevel(level);\n// var exp = expBar.getRequiredExpToNextLevel(level, exp);\n
"},{"location":"ui-expbar/#events","title":"Events","text":"
  • Easing starting of Level-up
    expBar.on('levelup.start', function(level, fromExp, toExp){        }, scope);\n
    • level : Current level
  • Easing end of Level-up
    expBar.on('levelup.end', function(level, fromExp, toExp){        }, scope);\n
    • level : Current level
  • Total easing of Level-up complete
    expBar.on('levelup.complete', function(level){        }, scope);\n
    • level : Current level
"},{"location":"ui-expbar/#other-properties","title":"Other properties","text":"

See NameValueLabel, sizer object, base sizer object, container-lite.

"},{"location":"ui-fileselectorbutton/","title":"File selector button","text":""},{"location":"ui-fileselectorbutton/#introduction","title":"Introduction","text":"

A transparent file chooser button (<input type=\"file\">) above a Label.

  • Author: Rex
  • Game object, DOM Game object
"},{"location":"ui-fileselectorbutton/#live-demos","title":"Live demos","text":"
  • File selector button
"},{"location":"ui-fileselectorbutton/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-fileselectorbutton/#install-plugin","title":"Install plugin","text":""},{"location":"ui-fileselectorbutton/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add file selector button object
    var button = scene.add.fileSelectorButton(config);\n
"},{"location":"ui-fileselectorbutton/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FileChooserPlugin from 'phaser3-rex-plugins/plugins/filechooser-plugin.js';\nvar config = {    parent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add file selector button object
    var button = scene.add.fileSelectorButton(config);\n
"},{"location":"ui-fileselectorbutton/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import { FileSelectorButton } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add file chooser object
    var button = new FileSelectorButton(scene, config);\nscene.add.existing(button);\n
"},{"location":"ui-fileselectorbutton/#add-file-chooser-object","title":"Add file chooser object","text":"
var button = scene.add.fileSelectorButton({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\n\nicon: iconGameObject,\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntext: textGameObject,\nexpandTextWidth: false,\nexpandTextHeight: false,\n\naction: actionGameObject,\n// actionMask: false,\n// squareFitAction: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nalign: undefined,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0,\ntext: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n\n// accept: '',\n// multiple: false,\n});\n// var fileChooser = scene.add.fileSelectorButton(x, y, width, height, config);\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • squareFitIcon :
    • true : Resize icon size to square to fit label height/width.
    • false : Ignore this feature. Default behavior.
  • iconSize : Set display size of icon game object to iconSizexiconSize
  • iconWidth : Set display width of icon game object to iconWidth.
    • If iconHeight is undefined, set scaleY of icon game object to scaleX of icon game object, to keep size ratio.
  • iconHeight : Set display height of icon game object to iconHeight.
    • If iconWidth is undefined, set scaleX of icon game object to scaleY of icon game object, to keep size ratio.
  • text : Game object of text, optional.
  • expandTextWidth :
    • false : Keep width of text to original size. Default behavior.
    • true : Expand width of text object. Will set display width by default.
      • Must set to true if using scene.rexUI.wrapExpandText method with any text game object.
  • expandTextHeight : Set true to expand height of text object.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • squareFitAction :
    • true : Resize action icon size to square to fit label height/width.
    • false : Ignore this feature. Default behavior.
  • actionSize : Set display size of action game object to actionSizexactionSize
  • actionWidth : Set display width of action game object to actionWidth.
    • If actionHeight is undefined, set scaleY of action game object to scaleX of action game object, to keep size ratio.
  • actionHeight : Set display height of action game object to actionHeight.
    • If actionWidth is undefined, set scaleX of action game object to scaleY of action game object, to keep size ratio.
  • align : Alignment of icon, text, action game objects.
    • undefined, or 'left', or 'top' : Align game objects at left, or top.
    • 'center' : Align game objects at center.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.icon : Space between icon game object and text game object.
    • space.text : Space between text game object and action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • accept : A filter for what file types the user can pick from the file input dialog box.
    • 'image/*' : The user can pick all image files.
    • 'audio/*' : The user can pick all sound files.
    • 'video/*' : The user can pick all video files.
    • file_extension : Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can pick from.
  • multiple : Set true to select multiple files.
"},{"location":"ui-fileselectorbutton/#custom-class","title":"Custom class","text":"
  • Define class
    class MyFileSelectorButton extends RexPlugins.UI.FileSelectorButton {\nconstructor(scene, config) {\nsuper(scene, config) {\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var button = new MyFileSelectorButton(scene, config);\n
"},{"location":"ui-fileselectorbutton/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

label.layout();\n

See also - dirty

"},{"location":"ui-fileselectorbutton/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = label.getElement('background');\n
    • Icon game object
      var icon = label.getElement('icon');\n
    • Text game object
      var textObject = label.getElement('text');\n
    • Action icon game object
      var action = label.getElement('action');\n
    • File chooser game object
      var fileChooser = label.getElement('fileChooser');\n
  • Get by name
    var gameObject = label.getElement('#' + name);\n// var gameObject = label.getElement('#' + name, recursive);\n
    or
    var gameObject = label.getByName(name);\n// var gameObject = label.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-fileselectorbutton/#selected-files","title":"Selected files","text":"
var files = fileChooser.files;\n
  • files : Array of file object.
"},{"location":"ui-fileselectorbutton/#set-accept-filter","title":"Set accept filter","text":"
fileChooser.setAccept(accept);\n
  • accept : A filter for what file types the user can pick from the file input dialog box.
    • 'image/*' : The user can pick all image files.
    • 'audio/*' : The user can pick all sound files.
    • 'video/*' : The user can pick all video files.
    • file_extension : Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can pick from.
"},{"location":"ui-fileselectorbutton/#multiple-files","title":"Multiple files","text":"
  • Enable
    fileChooser.setMultiple();\n
  • Disable
    fileChooser.setMultiple(false);\n
"},{"location":"ui-fileselectorbutton/#events","title":"Events","text":"
  • Selected file(s) changed
    button.on('select', function(files, button) {        var file = files[0];\nvar url = URL.createObjectURL(file);\n// ...\n})\n
"},{"location":"ui-fileselectorbutton/#load-file-to-cache","title":"Load file to cache","text":"
fileChooser.loadFile(file, loaderType, key);\n// fileChooser.loadFile(file, loaderType, key, cahceType);\n

or

fileChooser.loadFilePromise(file, loaderType, key, cahceType)\n.then(function(content) {\n\n})\n
  • file : File object, see Events
  • loaderType : image, text, binary, ... See Loader
  • key : Unique string key.
  • cahceType :
    • undefined : Use default value.
  • content : Content of file.
"},{"location":"ui-fileselectorbutton/#create-object-url","title":"Create object URL","text":"
  • Create object url
    var objectURL = URL.createObjectURL(file);\n
  • Release object url
    URL.createObjectURL(objectURL);\n
"},{"location":"ui-fileselectorbutton/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"

See dom-element's Interactive with other game objects

"},{"location":"ui-fileselectorbutton/#other-properties","title":"Other properties","text":"

See label object, sizer object, base sizer object, container-lite.

"},{"location":"ui-fixwidthbuttons/","title":"Fix-width buttons","text":""},{"location":"ui-fixwidthbuttons/#introduction","title":"Introduction","text":"

A container with a group of fix-width buttons.

  • Author: Rex
  • Game object
"},{"location":"ui-fixwidthbuttons/#live-demos","title":"Live demos","text":"
  • Checkboxes/radio
  • Indent left
  • Indent top
"},{"location":"ui-fixwidthbuttons/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-fixwidthbuttons/#install-plugin","title":"Install plugin","text":""},{"location":"ui-fixwidthbuttons/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add fix-Width buttons object
    var buttons = scene.rexUI.add.fixWidthButtons(config);\n
"},{"location":"ui-fixwidthbuttons/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add fix-Width buttons object
    var buttons = scene.rexUI.add.fixWidthButtons(config);\n
"},{"location":"ui-fixwidthbuttons/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { FixWidthButtons } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add fix-Width buttons object
    var buttons = new FixWidthButtons(scene, config);\nscene.add.existing(buttons);\n
"},{"location":"ui-fixwidthbuttons/#add-buttons-object","title":"Add Buttons object","text":"
var buttons = scene.rexUI.add.fixWidthButtons({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\n// background: backgroundGameObject,\n\nbuttons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\n// rtl: false,\nalign: 0,\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n},\n\n// space: 0,\n// space: {\n//     left: 0, right: 0, top: 0, bottom: 0,\n//     item: 0, line: 0,\n//     indentLeftOdd: 0, indentLeftEven: 0,\n//     indentTopOdd: 0, indentTopEven: 0,\n// },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n// eventEmitter: this,\n// groupName: undefined,\n\n// buttonsType: undefined,\n// setValueCallback: undefined,  // or setButtonStateCallback: undefined\n// setValueCallbackScope: undefined  // or setButtonStateCallbackScope: undefined\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of grid table.
  • buttons : 1d/2d array of button game objects.
  • align : Align children of a line.
    • 0, 'left' : Align children of a line to left/top side.
    • 1, 'right' : Align children of a line to right/bottom side.
    • 2, 'center' : Align children of a line to ceter.
    • 3, 'justify', 'justify-left' : If remainder space is less or equal than 25%, then justify children. Else align children to left/top side.
    • 4, 'justify-right' : If remainder space is less or equal than 25%, then justify children. Else align children to right/bottom side.
    • 5, 'justify-cneter' : If remainder space is less or equal than 25%, then justify children. Else align children to center.
  • click: Configuration of button clicking.
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
  • space :
    • A number: Space between 2 button game objects.
    • An object: Padding of button game objects.
      • space.left, space.right, space.top, space.bottom : Space of bounds.
      • space.item : Space betwen each child of a line.
      • space.line : Space between each line.
      • space.indentLeftOdd, space.indentLeftEven : Indent at each odd/even line.
      • space.indentTopOdd, space.indentTopEven : Indent at each odd/even item.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • eventEmitter : Dispatch buttons' touch events to other game obhect, default is this buttons game object.
  • groupName : Optional group name for argument of touch events.
  • buttonsType : Type/behavior of these buttons.
    • undefined : No extra behavior, default value.
    • 'checkboxes' : Set these buttons to checkboxes.
    • 'radio' : Set these buttons to radio.
  • setValueCallback or setButtonStateCallback : Callback to set value of a button.
    • undefined : No callback, default value.
    • A function object.
      function(button, value, previousValue) {\n// ...\n}\n
      • button : Button game object.
      • value: true, or false.
      • previousValue : true, or false.
"},{"location":"ui-fixwidthbuttons/#custom-class","title":"Custom class","text":"
  • Define class
    class MyButtons extends RexPlugins.UI.FixWidthButtons {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var buttons = new MyButtons(scene, config);\n
"},{"location":"ui-fixwidthbuttons/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

buttons.layout();\n

See also - dirty

"},{"location":"ui-fixwidthbuttons/#other-properties","title":"Other properties","text":"

See sizer object

"},{"location":"ui-fixwidthbuttons/#events","title":"Events","text":"
  • Click button
    buttons.on('button.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.click', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
    • groupName : Optional group name.
    • button : Triggered button game object.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-over button
    buttons.on('button.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.over', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-out button
    buttons.on('button.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.out', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Enable button's input
    buttons.on('button.enable', function(button, index) {\n// ...\n}, scope);\n
    or
    buttons.on('button.enable', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Disable button's input
    buttons.on('button.disalbe', function(button, index) {\n// ...\n}, scope);\n
    or
    buttons.on('button.disalbe', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
"},{"location":"ui-fixwidthbuttons/#emit-button-click-event","title":"Emit button click event","text":"
buttons.emitButtonClick(index);\n
  • index : Index of triggered button game object, or a button game object.
"},{"location":"ui-fixwidthbuttons/#enabledisable-input-of-button","title":"Enable/disable input of button","text":"
  • Enable a button's input
    buttons.setButtonEnable(index);\n// buttons.setButtonEnable(index, true);\n
    • index : Index of triggered button game object, or a button game object.
  • Enable all buttons' input
    buttons.setButtonEnable();\n// buttons.setButtonEnable(true);\n
  • Disable
    buttons.setButtonEnable(index, true);\n
    • index : Index of triggered button game object, or a button game object.
  • Disable all buttons' input
    buttons.setButtonEnable(false);\n
  • Toggle
    buttons.toggleButtonEnable(index);\n
  • Toggle all buttons's input
    buttons.toggleButtonEnable();\n
  • Get button's input enable
    var enabled = bottons.getButtonEnable(index);\n
"},{"location":"ui-fixwidthbuttons/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = buttons.getElement('background');\n
    • Button game objects
      var buttonObjects = buttons.getElement('buttons');\n
      or
      var buttonObject = buttons.getButton(index);\n
      or
      var buttonObjects = buttons.getElement('buttons[0]'); // First button\n
  • Get by name
    var gameObject = buttons.getElement('#' + name);\n// var gameObject = buttons.getElement('#' + name, recursive);\n
    or
    var gameObject = buttons.getByName(name);\n// var gameObject = buttons.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-fixwidthbuttons/#add-child","title":"Add child","text":"
  • Add button child
    buttons.addButton(gameObject)\n
    • gameObject : A game object, or an array of game objects.
  • Add non-button child, see fixWidthSizer.add() method.
    buttons.add(gameObject,\n{\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nkey: undefined,\nindex: undefined\n}\n)\n
"},{"location":"ui-fixwidthbuttons/#remove-child","title":"Remove child","text":"
  • Remove button child
    buttons.removeButton(gameObject, destroyChild);\n
    • gameObject :
      • Game object, or array of game objects : Button game object.
      • A number, or array of numbers : Index of button game object.
      • A string, or array of strings : Name of button game object.
    • destroyChild : Set true to destroy button game object.
  • Remove all buttton children
    buttons.clearButtons(destroyChild);\n
    • destroyChild : Set true to destroy button game objects.
  • Remove a button or non-button child, see fixWidthSizer.remove() method.
    buttons.remove(gameObject, destroyChild);\n
  • Remove all button or non-button children, see fixWidthSizer.remove() method.
    buttons.removeAll(destroyChild);\n
"},{"location":"ui-fixwidthbuttons/#showhide-button","title":"Show/hide button","text":"

The same as for each button of buttons.

"},{"location":"ui-fixwidthbuttons/#for-each-button","title":"For each button","text":"

The same as for each button of buttons.

"},{"location":"ui-fixwidthbuttons/#checkboxesradio","title":"Checkboxes/radio","text":"

The same as checkboxes/radio of buttons.

"},{"location":"ui-fixwidthsizer/","title":"Fix-width sizer","text":""},{"location":"ui-fixwidthsizer/#introduction","title":"Introduction","text":"

Layout children game objects into lines.

  • Author: Rex
  • Game object
"},{"location":"ui-fixwidthsizer/#live-demos","title":"Live demos","text":"
  • Fix-width sizer
  • Scrollable, fix-width sizer
  • Indent
  • Drag-drop item
  • Set children interactive
  • vertical & horizontal
"},{"location":"ui-fixwidthsizer/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-fixwidthsizer/#install-plugin","title":"Install plugin","text":""},{"location":"ui-fixwidthsizer/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add sizer object
    var sizer = scene.rexUI.add.fixWidthSizer(config);\n
"},{"location":"ui-fixwidthsizer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add sizer object
    var sizer = scene.rexUI.add.fixWidthSizer(config);\n
"},{"location":"ui-fixwidthsizer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { FixWidthSizer } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add sizer object
    var sizer = new FixWidthSizer(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-fixwidthsizer/#add-sizer-object","title":"Add sizer object","text":"
var sizer = scene.rexUI.add.fixWidthSizer({\n// x: 0,\n// y: 0,\n// anchor: undefined,    \n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// orientation: 0,\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom: 0,\n//     item: 0, line: 0, \n//     indentLeftOdd: 0, indentLeftEven: 0,\n// },\n\n// rtl: false,\n// align: 0,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n

or

var sizer = scene.rexUI.add.fixWidthSizer(x, y, {\n// width: 2,\n// height: 2\n// orientation: 0,\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom: 0,\n//     item: 0, line: 0,\n//     indentLeftOdd: 0, indentLeftEven: 0,\n//     indentTopOdd: 0, indentTopEven: 0,\n// },\n\n// rtl: false,\n// align: 0,\n\n// name: '',\n// draggable: false\n});\n

or

var sizer = scene.rexUI.add.fixWidthSizer(x, y, width, height, {\n// orientation: 0,\n// space: {\n//     left: 0, right: 0, top: 0, bottom: 0,\n//     item: 0, line: 0\n// },\n\n// rtl: false,\n// align: 0,\n\n// name: '',\n// draggable: false\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation : Orientation of the sizer.
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Arrange game objects from left ot right. Default value is 0.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Arrange game objects from top to bottom.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space betwen each child of a line.
    • space.line : Space between each line.
    • space.indentLeftOdd, space.indentLeftEven : Indent at each odd/even line.
    • space.indentTopOdd, space.indentTopEven : Indent at each odd/even item.
  • rtl : Order of children in each line.
    • false : Place children from left-to-right/top-to-bottom, default value.
    • true : Place children from right-to-left/bottom-to-top.
  • align : Align children of a line.
    • 0, 'left' : Align children of a line to left/top side.
    • 1, 'right' : Align children of a line to right/bottom side.
    • 2, 'center' : Align children of a line to ceter.
    • 3, 'justify', 'justify-left' : If remainder space is less or equal than 25%, then justify children. Else align children to left/top side.
    • 4, 'justify-right' : If remainder space is less or equal than 25%, then justify children. Else align children to right/bottom side.
    • 5, 'justify-cneter' : If remainder space is less or equal than 25%, then justify children. Else align children to center.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-fixwidthsizer/#custom-class","title":"Custom class","text":"
  • Define class
    class MySizer extends RexPlugins.UI.FixWidthSizer {\nconstructor(scene, x, y, minWidth, minHeight, orientation, space, config) {\nsuper(scene, x, y, minWidth, minHeight, orientation, space, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var sizer = new MySizer(scene, x, y, minWidth, minHeight, orientation, space, config);\n
"},{"location":"ui-fixwidthsizer/#add-background","title":"Add background","text":"
sizer.addBackground(child);\n

or

sizer.addBackground(child, {left: 0, right: 0, top: 0, bottom: 0}, key);\n
  • left, right, top, bottom : Extra padded space. Default is 0.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
"},{"location":"ui-fixwidthsizer/#add-child","title":"Add child","text":"

Add a game obejct to sizer

sizer.add(child);\n

or

sizer.add(child,\n{\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nkey: undefined,\nindex: undefined\n}\n);\n

or

sizer.add(child, padding, key, index);\n
  • child : A game object
  • padding : Add space between bounds. Default is 0.
    • A number for left/right/top/bottom bounds
    • Or a plain object
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
    • items : Reserved key, for all children item.
  • index : Insert child to.
    • undefined : Insert child at last.
"},{"location":"ui-fixwidthsizer/#insert-child","title":"Insert child","text":"
sizer.insert(index, child, {\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nkey: undefined,\n}\n);\n

or

sizer.insert(index, child, padding, key);\n
"},{"location":"ui-fixwidthsizer/#insert-at-position","title":"Insert at position","text":"
sizer.insertAtPosition(x, y, child, {\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nkey: undefined,\n}\n);\n

or

sizer.insertAtPosition(x, y, index, child, padding, key);\n
"},{"location":"ui-fixwidthsizer/#add-new-line","title":"Add new line","text":"
sizer.addNewLine();\n
"},{"location":"ui-fixwidthsizer/#layout-children","title":"Layout children","text":"

Arrange position of all children.

sizer.layout();\n

See also - dirty

"},{"location":"ui-fixwidthsizer/#hide","title":"Hide","text":"
  • Set invisible, won't layout it
    sizer.hide();\n
    or
    sizer.hide(gameObject);\n
  • Set visible, will layout it
    sizer.show();\n
    or
    sizer.show(gameObject);\n
"},{"location":"ui-fixwidthsizer/#remove-child","title":"Remove child","text":"
  • Remove a child
    sizer.remove(child);\n
  • Remove and destroy a child
    sizer.remove(child, true);\n
  • Remove all children
    sizer.removeAll();\n
  • Remove and destroy all children
    sizer.removeAll(true);\n
  • Remove all children and backgrounds
    sizer.clear();\n
  • Remove and destroy all children and backgrounds
    sizer.clear(true);\n
  • Remove from parent sizer
    sizer.removeFromParentSizer();\n
"},{"location":"ui-fixwidthsizer/#sort-children","title":"Sort children","text":"
  • Sort by data
    sizer.sortChildrenByData(key, descending).layout();\n
    • key : Data key
    • descending :
      • true : Descending order
      • false : Ascending order, default behavior.
  • Sort by property of child
    sizer.sortChildrenByProperty(key, descending).layout();\n
    • key : Property key
    • descending :
      • true : Descending order
      • false : Ascending order, default behavior.
  • Sort by callback
    sizer.sortChildren(function(childA, childB){\n// var valueA = childA.getData(key);\n// var valueB = childB.getData(key);\n// return valueB - valueA\n}).layout();\n
    • childA, childB : 2 children of this size
"},{"location":"ui-fixwidthsizer/#get-element","title":"Get element","text":"
  • Get element
    • All children items
      var items = sizer.getElement('items');\n
  • Get by name
    var gameObject = sizer.getElement('#' + name);\n// var gameObject = sizer.getElement('#' + name, recursive);\n
    or
    var gameObject = sizer.getByName(name);\n// var gameObject = sizer.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-fixwidthsizer/#get-child-index","title":"Get child index","text":"
var index = sizer.getChildIndex(child);\n
  • index : A number, or null.
"},{"location":"ui-fixwidthsizer/#other-properties","title":"Other properties","text":"

See base-sizer object.

"},{"location":"ui-folder/","title":"Folder","text":""},{"location":"ui-folder/#introduction","title":"Introduction","text":"

A container with a title, foldable child, and background.

  • Author: Rex
  • Game object
"},{"location":"ui-folder/#live-demos","title":"Live demos","text":"
  • Scrollable folders
  • Draggable folder
  • Nested folders
"},{"location":"ui-folder/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-folder/#install-plugin","title":"Install plugin","text":""},{"location":"ui-folder/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add folder object
    var folder = scene.rexUI.add.folder(config);\n
"},{"location":"ui-folder/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add folder object
    var folder = scene.rexUI.add.folder(config);\n
"},{"location":"ui-folder/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Folder } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add folder object
    var folder = new Folder(scene, config);\nscene.add.existing(folder);\n
"},{"location":"ui-folder/#add-folder-object","title":"Add folder object","text":"
var folder = scene.rexUI.add.folder({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\n\ntitle: titleGameObject,    child: childGameObject,\n// customChildOrigin: false,\n\ntoggleByTarget: undefined,\ntoggleClickConfig: {\nmode:'pointerup',\nclickInterval: 100,\nthreshold: undefined,\n},\n\nalign: {\ntitle: 'left',\nchild: 'left',\n},\n\nexpand: {\ntitle: true,\nchild: true,\n},\n\nspace: { left: 0, right:0, top:0, bottom:0, item:0,\n\ntitleLeft: 0, titleRight: 0, titleTop: 0, titleBottom: 0,\nchildLeft: 0, childRight: 0, childTop: 0, childBottom: 0,\n},\n\ntransition: {\nduration: 200,\nexpandCallback: undefined,\ncollapseCallback: undefined,\n},\n\nreLayoutTarget: undefined,\n\nonExpandStart: undefined,\nonExpandComplete: undefined,\nonCollapseStart: undefined,\nonCollapseComplete: undefined,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nitem: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of folder.
  • title : Game object of title, required.
  • child : Game object of child, required.
  • customChildOrigin :
    • false : Set origin of child to 0, or 1 (if rtl is set to true). Default behavior.
    • true : Don't change origin of child.
  • toggleByTarget : Toggle expanding/collapsing by clicking this target game object
    • undefined : Toggle by clicking title game object.
  • toggleClickConfig : Configuration of clicking behavior
    • undefined : Use default configuration.
  • align.title, align.child : Alignment of title, child game objects.
    • undefined, or 'left', or 'top' : Align game objects at left, or top. Default behavior.
    • 'center' : Align game objects at center.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
  • expand.title, expand.child : Expand width/height of title, child game objects.
    • true : Expand width/heigh. Default behavior.
    • false : Use origin width/height.
  • transition : Configuration of expanding/collapsing transition.
    • transition.duration : Duration of expanding/collapsing transition.
    • transition.expandCallback : Callback invoked when expading child. Default behavior is scale-up.
    • transition.collapseCallback : Callback invoked when collapsing child. Default behavior is scale-down.
  • reLayoutTarget : Layout topmost sizer when expanding/collapsing start.
    • undefined : Topmost sizer will be layouted again. Default behavior.
    • A sizer : Layout this sizer.
  • onExpandStart : Callback invoked when expanding start. Register this callback on 'expand.start' event.
    function(folder) {  }\n
  • onExpandComplete : Callback invoked when expanding complete. Register this callback on 'expand.complete' event.
    function(folder) {  }\n
  • onCollapseStart : Callback invoked when collapsing start. Register this callback on 'collapse.start' event.
    function(folder) {  }\n
  • onCollapseComplete : Callback invoked when collapsing complete. Register this callback on 'collapse.complete' event.
    function(folder) {  }\n
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.icon : Space between icon game object and text game object.
    • space.text : Space between text game object and action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-folder/#custom-class","title":"Custom class","text":"
  • Define class
    class MyFolder extends RexPlugins.UI.Folder {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var folder = new MyFolder(scene, config);\n
"},{"location":"ui-folder/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

folder.layout();\n

See also - dirty

Note

Layout topmost sizer when expanding/collapsing start.

"},{"location":"ui-folder/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = folder.getElement('background');\n
    • Title game object
      var title = folder.getElement('title');\n
    • Child game object
      var child = folder.getElement('child');\n
  • Get by name
    var gameObject = folder.getElement('#' + name);\n// var gameObject = folder.getElement('#' + name, recursive);\n
    or
    var gameObject = folder.getByName(name);\n// var gameObject = folder.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-folder/#expandcollapse","title":"Expand/collapse","text":"
  • Expand, will re-layout from topmost sizer
    folder.expand();\n// folder.expand(duration);\n
    folder.expand(0);  // Immediately, won't invoke expandCallback\n
  • Collapse, will re-layout from topmost sizer
    folder.collapse();\n// folder.collapse(duration);\n
    folder.collapse(0);  // Immediately, won't invoke collapseCallback\n
  • Toggle, will re-layout from topmost sizer
    folder.toggle();\n// folder.toggle(duration);\n
    folder.toggle(0);  // Immediately, won't invoke expandCallback/collapseCallback\n
  • Set expanded state without re-layouting
    folder.setExpandedState(expanded);  // true, or false\n
  • Get expanded state
    var expanded = folder.expanded;\n
    • expanded : Initial value is undefined
"},{"location":"ui-folder/#transition-callbacks","title":"Transition callbacks","text":"
  • Set transition callbacks
    folder.setExpandCallback(callback);\nfolder.setCollapseCallback(callback);\n
    • callback :
      function(gameObject, duration) {\n}\n
      • gameObject : Child game object
  • Transition duration
    • Set
      folder.setTransitionDuration(duration);\n
    • Get
      var duration = folder.transitionDuration;\n
"},{"location":"ui-folder/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-folder/#events","title":"Events","text":"
  • On expand-start
    folder.on('expand.start', function(folder){\n\n})\n
    title.on('folder.expand', function(folder){\n\n})\n
    child.on('folder.expand', function(folder){\n\n})\n
  • On expand-complete
    folder.on('expand.complete', function(folder){\n\n})\n
  • On collapse-start
    folder.on('collapse.start', function(folder){\n\n})\n
    title.on('folder.collapse', function(folder){\n\n})\n
    child.on('folder.collapse', function(folder){\n\n})\n
  • On collapse-complete
    folder.on('collapse.complete', function(folder){\n\n})\n
"},{"location":"ui-gridbuttons/","title":"Grid buttons","text":""},{"location":"ui-gridbuttons/#introduction","title":"Introduction","text":"

A container with a group of buttons in grids.

  • Author: Rex
  • Game object
"},{"location":"ui-gridbuttons/#live-demos","title":"Live demos","text":"
  • Number pad
  • Checkboxes/radio
"},{"location":"ui-gridbuttons/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-gridbuttons/#install-plugin","title":"Install plugin","text":""},{"location":"ui-gridbuttons/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add buttons object
    var buttons = scene.rexUI.add.gridButtons(config);\n
"},{"location":"ui-gridbuttons/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add buttons object
    var buttons = scene.rexUI.add.gridButtons(config);\n
"},{"location":"ui-gridbuttons/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { GridButtons } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add buttons object
    var buttons = new GridButtons(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-gridbuttons/#add-grid-sizer-object","title":"Add grid sizer object","text":"
var buttons = scene.rexUI.add.gridButtons({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\n// background: backgroundGameObject,\n\nbuttons: [\n[buttonGameObject, buttonGameObject, buttonGameObject, ...],\n[buttonGameObject, buttonGameObject, buttonGameObject, ...],\n[buttonGameObject, buttonGameObject, buttonGameObject, ...],\n...\n],\n// row: 0, \n// column: 0,   // col: 0\n// createCellContainerCallback: function(scene, x, y) {\n//       return cellContainer;\n// },    \nexpand: true,\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n},\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom:0,\n//     column: 0, // [0, 0, 0]\n//     row: 0     // [0, 0, 0]\n// },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n// eventEmitter: this,\n// groupName: undefined,\n\n// buttonsType: undefined,\n// setValueCallback: undefined,  // or setButtonStateCallback: undefined\n// setValueCallbackScope: undefined  // or setButtonStateCallbackScope: undefined\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width : Minimum width. i.e. Width of this gridButtons will larger then this value.
  • height : Minimum height. i.e. Hieght of this gridButtons will larger then this value.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of grid table.
  • buttons : 2d array of button game objects, or create buttons via row, column(or col), and createCellContainerCallback.
  • createCellContainerCallback : Callback to create buttons.
    function(scene, x, y) {\nreturn cellContainer;\n}\n
  • expand : Set true to expand width and height of buton game objects.
  • space : Space around this sizer, and space between columns/rows
    • space.left, space.right, space.top, space.bottom : Space around this sizer.
    • space.column : Space between 2 columns
      • A number
      • A number array
    • space.row : Space between 2 rows
      • A number
      • A number array
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • eventEmitter : Dispatch buttons' touch events to other game object, default is this buttons game object.
  • groupName : Optional group name for argument of touch events.
  • buttonsType : Type/behavior of these buttons.
    • undefined : No extra behavior, default value.
    • 'checkboxes' : Set these buttons to checkboxes.
    • 'radio' : Set these buttons to radio.
  • setValueCallback or setButtonStateCallback : Callback to set value of a button.
    • undefined : No callback, default value.
    • A function object.
      function(button, value, previousValue) {\n// ...\n}\n
      • button : Button game object.
      • value: true, or false.
      • previousValue : true, or false.
"},{"location":"ui-gridbuttons/#custom-class","title":"Custom class","text":"
  • Define class
    class MyGridButtons extends RexPlugins.UI.GridButtons {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var buttons = new MyGridButtons(scene, config);\n
"},{"location":"ui-gridbuttons/#layout-children","title":"Layout children","text":"

Arrange position of all children.

buttons.layout();\n

See also - dirty

"},{"location":"ui-gridbuttons/#other-properties","title":"Other properties","text":"

See grid sizer object.

"},{"location":"ui-gridbuttons/#events","title":"Events","text":"

The same as events of buttons.

"},{"location":"ui-gridbuttons/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = buttons.getElement('background');\n
    • Button game objects
      var buttonObjects = buttons.getElement('buttons');\n
      or
      var buttonObject = buttons.getButton(index);\n
      or
      var buttonObjects = buttons.getElement('buttons[0]'); // First button\n
  • Get by name
    var gameObject = buttons.getElement('#' + name);\n// var gameObject = buttons.getElement('#' + name, recursive);\n
    or
    var gameObject = buttons.getByName(name);\n// var gameObject = buttons.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-gridbuttons/#showhide-button","title":"Show/hide button","text":"

The same as for each button of buttons.

"},{"location":"ui-gridbuttons/#for-each-button","title":"For each button","text":"

The same as for each button of buttons.

"},{"location":"ui-gridbuttons/#checkboxesradio","title":"Checkboxes/radio","text":"

The same as checkboxes/radio of buttons.

"},{"location":"ui-gridsizer/","title":"Grid sizer","text":""},{"location":"ui-gridsizer/#introduction","title":"Introduction","text":"

Layout children game objects in grids.

  • Author: Rex
  • Game object
"},{"location":"ui-gridsizer/#live-demos","title":"Live demos","text":"
  • Create cell-containers
  • Scrollable grids
  • Add new row
  • Add new column
  • Full viewport
  • Set children interactive
  • Destroy cell
  • Reset grid
"},{"location":"ui-gridsizer/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-gridsizer/#install-plugin","title":"Install plugin","text":""},{"location":"ui-gridsizer/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add sizer object
    var sizer = scene.rexUI.add.gridSizer(config);\n
"},{"location":"ui-gridsizer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add sizer object
    var sizer = scene.rexUI.add.gridSizer(config);\n
"},{"location":"ui-gridsizer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { GridSizer } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add sizer object
    var sizer = new GridSizer(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-gridsizer/#add-grid-sizer-object","title":"Add grid sizer object","text":"
var gridSizer = scene.rexUI.add.gridSizer({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\ncolumn: 0,  // col: 0\nrow: 0,\n// columnProportions: undefined,\n// rowProportions: undefined,\n// space: {\n//     left: 0, right: 0, top: 0, bottom:0,\n//     column: 0, // [0, 0, 0]\n//     row: 0,    // [0, 0, 0]\n//     indentLeftOdd: 0, indentLeftEven: 0,\n//     indentTopOdd: 0, indentTopEven: 0,\n// },\n\n// createCellContainerCallback: function(scene, x, y, config) {\n//     config.expand = true;\n//     return cellContainer;\n// },\n\n// name: '',\n// draggable: false\n});\n

or

var gridSizer = scene.rexUI.add.gridSizer(x, y, {\ncolumn: 0,  // col: 0\nrow: 0,\n// columnProportions: undefined,\n// rowProportions: undefined,\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom:0,\n//     column: 0, // [0, 0, 0]\n//     row: 0,    // [0, 0, 0]\n//     indentLeftOdd: 0, indentLeftEven: 0,\n//     indentTopOdd: 0, indentTopEven: 0,\n// },\n\n// createCellContainerCallback: function(scene, x, y, config) {\n//     config.expand = true;\n//     return cellContainer;\n// },\n\n// width: undefined,\n// height: undefined\n});\n

or

var gridSizer = scene.rexUI.add.gridSizer(x, y, width, height, {\ncolumn: 0,   // col: 0\nrow: 0,\n// columnProportions: undefined,\n// rowProportions: undefined,\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom:0,\n//     column: 0, // [0, 0, 0]\n//     row: 0,    // [0, 0, 0]\n//     indentLeftOdd: 0, indentLeftEven: 0,\n//     indentTopOdd: 0, indentTopEven: 0,\n// },\n\n// createCellContainerCallback: function(scene, x, y, config) {\n//     config.expand = true;\n//     return cellContainer;\n// },\n});\n

or

var gridSizer = scene.rexUI.add.gridSizer(x, y, width, height, column, row, {\n// space: {\n//     left: 0, right: 0, top: 0, bottom:0,\n//     column: 0, // [0, 0, 0]\n//     row: 0,    // [0, 0, 0]\n//     indentLeftOdd: 0, indentLeftEven: 0,\n//     indentTopOdd: 0, indentTopEven: 0,\n// },\n\n// createCellContainerCallback: function(scene, x, y, config, gridSizer) {\n//     config.expand = true;\n//     return cellContainer;\n// },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width : Minimum width. i.e. Width of this gridSizer will larger then this value.
  • height : Minimum height. i.e. Hieght of this gridSizer will larger then this value.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • column, or col : Amount of column grids.
  • row : Amount of row grids.
  • columnProportions, rowProportions : Proportion of each column/row.
    • Number : Apply this number proportion to each column/row
    • Number array : Apply proportion of column/row through elements of this number array.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.column : Space between 2 columns
      • A number
      • A number array
    • space.row : Space between 2 rows
      • A number
      • A number array
    • space.indentLeftOdd, space.indentLeftEven : Indent at each odd/even row.
    • space.indentTopOdd, space.indentTopEven : Indent at each odd/even column.
  • createCellContainerCallback : Callback to create container(sizer) of each cell.
    function(scene, x, y, config) {\nreturn cellContainer;\n}\n
    • x, y : Column, row index of this cell.
    • config : Config of adding child
      config.align = 'center';\nconfig.padding = {left: 0, right: 0, top: 0, bottom: 0};\nconfig.expand = false;\nconfig.key = undefined;\n
    • cellContainer : Return a game object for this cell.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-gridsizer/#custom-class","title":"Custom class","text":"
  • Define class
    class MyGridSizer extends RexPlugins.UI.GridSizer {\nconstructor(scene, x, y, minWidth, minHeight, column, row) {\nsuper(scene, x, y, minWidth, minHeight, column, row);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var gridSizer = new MyGridSizer(scene, x, y, minWidth, minHeight, column, row);\n
"},{"location":"ui-gridsizer/#add-background","title":"Add background","text":"
gridSizer.addBackground(child);\n

or

gridSizer.addBackground(child, {left: 0, right: 0, top: 0, bottom: 0}, key);\n
  • left, right, top, bottom : Extra padded space. Default is 0.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
"},{"location":"ui-gridsizer/#add-child","title":"Add child","text":"

Add a game obejct to grid sizer

gridSizer.add(child, column, row);\n

or

gridSizer.add(child,\n{\ncolumn: 0,\nrow: 0,\nalign: 'center',\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nexpand: false,        // expand: {width, height}\nkey: undefined\n}\n);\n

or

gridSizer.add(child, column, row, align, padding, expand, key);\n
  • child : A game object
  • column, row : Index of grid to add.
    • column and row are numbers : Insert game object to cell (column, row).
      • Do nothing if that cell has item already.
    • column and row are undefined : Search each column, each row to find an empty cell for inserting.
      • Add an new row (gridSizer.addEmptyRow()) if last row was full, then find an empty cell in new row.
    • column is undefined, and row is true : Search each row, each column to find an empty cell for inserting.
      • Add an new column (gridSizer.addEmptyColumn()) if last column was full, then find an empty cell in new column.
    • column is a number, and row is undefined : Search each row of column column to find an empty cell for inserting.
      • Add an new row (gridSizer.addEmptyRow()) if last row was full, then find an empty cell in new row.
    • column is undefined and row is a number : Search each column of row row to find an empty cell for inserting.
      • Add an new column (gridSizer.addEmptyColumn()) if last column was full, then find an empty cell in new column.
  • align :
    • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
    • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
    • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game object at top-center.
    • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at bottom-center.
  • padding : Add space between bounds. Default is 0.
    • A number for left/right/top/bottom bounds
    • Or a plain object
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • expand :
    • Boolean value
      • true : Expand width and height of child. Default value.
      • false : Don't expand width or height of child.
    • A plain object
      • {width: true} : Only expand width of child.
      • {height: true} : only expand height of child.
      • {width: true, height: true} : Expand width and height of child.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
"},{"location":"ui-gridsizer/#insert-empty-rowcolumn","title":"Insert empty row/column","text":"
  • Insert an empty row
    gridSizer.insertEmptyRow(rowIndex);\n// gridSizer.insertEmptyRow(rowIndex, proportion, space);\n
    • proportion : Proportion of this new row.
      • undefined : Use proportion of 1st row as default value.
    • space : Space between this new row and previous row.
      • undefined : Use space of 1st row as default value.
  • Add an empty row
    gridSizer.addEmptyRow();\n// gridSizer.addEmptyRow(rowIndex, proportion, space);\n
  • Insert an empty column
    gridSizer.insertEmptyColumn(colIndex);\n// gridSizer.insertEmptyColumn(colIndex, proportion, space);\n
    • proportion : Proportion of this new column.
      • undefined : Use proportion of 1st column as default value.
    • space : Space between this new column and previous column.
      • undefined : Use space of 1st column as default value.
  • Add an empty row
    gridSizer.addEmptyColumn();\n// gridSizer.addEmptyColumn(colIndex, proportion, space);\n
"},{"location":"ui-gridsizer/#proportion","title":"Proportion","text":"

Set proportion of each column or row via

gridSizer.setColumnProportion(columnIndex, proportion);\ngridSizer.setRowProportion(rowIndex, proportion);\n
"},{"location":"ui-gridsizer/#layout-children","title":"Layout children","text":"

Arrange position of all children.

gridSizer.layout();\n

See also - dirty

"},{"location":"ui-gridsizer/#hide","title":"Hide","text":"
  • Set invisible, won't layout it
    sizer.hide();\n
    or
    sizer.hide(gameObject);\n
  • Set visible, will layout it
    sizer.show();\n
    or
    sizer.show(gameObject);\n
"},{"location":"ui-gridsizer/#grid-index-child","title":"Grid index <-> child","text":"
  • Grid index -> child
    var child = gridSizer.getChildAt(columnIndex, rowIndex);\n
  • Child -> grid index
    var gridIndex = gridSizer.childToGridIndex(child);\n// var gridIndex = gridSizer.childToGridIndex(child, out);\n
    • gridIndex : {x, y}, or null if child is not belong this sizer.
"},{"location":"ui-gridsizer/#remove-child","title":"Remove child","text":"
  • Remove a child
    gridSizer.remove(child);\n
    or
    gridSizer.removeAt(columnIndex, rowIndex);\n
  • Remove and destroy a child
    gridSizer.remove(child, true);\n
    or
    gridSizer.removeAt(columnIndex, rowIndex, true);\n
  • Remove all children
    gridSizer.removeAll();\n
  • Remove and destroy all children
    gridSizer.removeAll(true);\n
  • Remove all children and backgrounds
    gridSizer.clear();\n
  • Remove and destroy all children and backgrounds
    gridSizer.clear(true);\n
  • Remove from parent sizer
    sizer.removeFromParentSizer();\n
"},{"location":"ui-gridsizer/#sort-children","title":"Sort children","text":"
  • Sort by data
    gridSizer.sortChildrenByData(key, descending).layout();\n
    • key : Data key
    • descending :
      • true : Descending order
      • false : Ascending order, default behavior.
  • Sort by property of child
    gridSizer.sortChildrenByProperty(key, descending).layout();\n
    • key : Property key
    • descending :
      • true : Descending order
      • false : Ascending order, default behavior.
  • Sort by callback
    gridSizer.sortChildren(function(childA, childB){\n// var valueA = childA.getData(key);\n// var valueB = childB.getData(key);\n// return valueB - valueA\n}).layout();\n
    • childA, childB : 2 children of this size
"},{"location":"ui-gridsizer/#grid-size","title":"Grid size","text":"
  • Amount of column
    var columnCount = gridSizer.columnCount;\n
  • Amount of row
    var rowCount = gridSizer.rowCount;\n
  • Amount of grid = columnCount * rowCount
    var gridCount = gridSizer.gridCount;\n
"},{"location":"ui-gridsizer/#get-element","title":"Get element","text":"
  • Get element
    • All children items
      var items = gridSizer.getElement('items');\n
  • Get by name
    var gameObject = gridSizer.getElement('#' + name);\n// var gameObject = gridSizer.getElement('#' + name, recursive);\n
    or
    var gameObject = gridSizer.getByName(name);\n// var gameObject = gridSizer.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-gridsizer/#get-child-index","title":"Get child index","text":"
var index = sizer.getChildIndex(child);\n
  • index : A number, or null.
"},{"location":"ui-gridsizer/#reset-grid","title":"Reset grid","text":"
sizer.resetGrid(column, row, columnProportions, rowProportions, space);\n
  • column : Amount of column grids.
  • row : Amount of row grids.
  • columnProportions, rowProportions : Proportion of each column/row.
    • Number : Apply this number proportion to each column/row
    • Number array : Apply proportion of column/row through elements of this number array.
  • space :
    • space.column : Space between 2 columns
      • A number
      • A number array
    • space.row : Space between 2 rows
      • A number
      • A number array

Note

Children game objects will be removed without destroyed.

Note

Will invoke createCellContainerCallback to create cellContainer of each cell.

"},{"location":"ui-gridsizer/#other-properties","title":"Other properties","text":"

See base sizer object, container-lite.

"},{"location":"ui-gridtable/","title":"Grid table","text":""},{"location":"ui-gridtable/#introduction","title":"Introduction","text":"

A container with a grid table, slider, and scroller.

  • Author: Rex
  • Game object
"},{"location":"ui-gridtable/#live-demos","title":"Live demos","text":"
  • Grid table
  • Varying cell size
  • Messages
    • Demo 1
    • Demo 2
    • Demo 3
  • Sizer cell:
    • Demo 1
    • Demo 2
  • Click child of cell
  • Two sliders
  • Separator
  • Modal
  • Fixed cell size
  • Drag item
  • Layer + mask padding
  • Fade-out-destroy cell
  • Custom mask
"},{"location":"ui-gridtable/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-gridtable/#install-plugin","title":"Install plugin","text":""},{"location":"ui-gridtable/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add table object
    var table = scene.rexUI.add.gridTable(config);\n
"},{"location":"ui-gridtable/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add table object
    var table = scene.rexUI.add.gridTable(config);\n
"},{"location":"ui-gridtable/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { GridTable } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add table object
    var table = new GridTable(scene, config);\nscene.add.existing(table);\n
"},{"location":"ui-gridtable/#add-table-object","title":"Add table object","text":"
var table = scene.rexUI.add.gridTable({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// scrollMode: 0,\n\n// Elements\nbackground: backgroundGameObject,\n\ntable: {\nwidth: undefined,\nheight: undefined,\n\ncellWidth: undefined,\ncellHeight: undefined,\ncolumns: 1,\n// rows: 1,\n// fixedCellSize: false,\n\nmask: {\npadding: 0,\n// updateMode: 0,\n},\n// enableLayer: false,\ninteractive: true,\nreuseCellContainer: false,\n\n// click: undefined,\n// tap: undefined,\n// press: undefined,\n// swipe: undefined,\n},\n\nslider: {\n// background: sliderBackgroundGameObject,\ntrack: trackGameObject,\n/* \n        track: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\nthumb: thumbGameObject,\n/* \n        thumb: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\n// input: 'drag',\n// position: 'right',\n\n// hideUnscrollableSlider: false,\n// adaptThumbSize: false,\n// minThumbSize: undefined,\n\n// buttons: {\n//     top: topButtonGameObject, bottom: bottomButtonGameObject,\n//     left: leftButtonGameObject, right: rightButtonGameObject,\n//     step: 0.01,\n// }\n},\n\n// sliderX: {...},\n// sliderY: {...},\n\n// scroller: {\n//     threshold: 10,\n//     slidingDeceleration: 5000,\n//     backDeceleration: 2000,\n//     pointerOutRelease: true,\n//     rectBoundsInteractive: true,\n//     dragRate: 1,\n// },\n\n// scrollerX: {...},\n// scrollerY: {...},\n\nmouseWheelScroller: false,\n// mouseWheelScroller: {\n//     focus: true,\n//     speed: 0.1\n// }.\n\n// mouseWheelScrollerX: {...},\n// mouseWheelScrollerY: {...},\n\nclampChildOY: false,\n\nheader: headerGameObject,\nfooter: footerGameObject,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\ntable: 0,\n// table: {\n//    top: 0,\n//    bottom: 0,\n//    left: 0,\n//    right: 0,\n//},\n\nslider: 0,\n// slider: {\n//     top: 0,\n//     bottom: 0,\n//     left: 0,\n//     right: 0,\n// },\n// sliderX: 0,\n// sliderY: 0,\n\nheader: 0,\nfooter: 0,\n},\n\nexpand: {\nheader: true,\nfooter: true,\n},\n\nalign: {\nheader: 'center',\nfooter: 'center',\n},\n\ncreateCellContainerCallback: function(cell, cellContainer) {\nvar scene = cell.scene,\nwidth = cell.width,\nheight = cell.height,\nitem = cell.item,\nitems = cell.items,\nindex = cell.index;\nif (cellContainer === null) { // No reusable cell container, create a new one\n// cellContainer = scene.rexUI.add.label();\n}\n// Set child properties of cell container ...\n\n// cell.setCellContainerAlign();  // Set alignment of cellContainer\n\nreturn cellContainer; // or null\n},\n\nitems: [],\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
    • Set width to undefined, and table.width is not undefined, will count width via table + slider.
    • Set height to undefined, and table.height is not undefined, will count height via table + slider.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • scrollMode : Scroll panel vertically, or horizontally.
    • 0, 'vertical', or 'v', 'y' : Scroll panel vertically. Default value.
    • 1, 'horizontal', or 'h'. 'x' : Scroll panel horizontally.
    • 2, or 'xy' : Two-sliders mode, scroll panel vertically and horizontally.
  • background : Game object of background, optional. This background game object will be resized to fit the size of grid table.
  • table : Configuration of grid table core.
    • table.width : Width of table, in pixels.
      • Set to undefined to expand table width to fit this grid table object.
    • table.height : Height of table, in pixels.
      • Set to undefined to expand table height to fit this grid table object.
    • table.cellHeight : Default height of each cell.
      • Necessary field in vertical scrollMode.
      • undefined : Expand cell height to fit table height, in horizontal scrollMode.
    • table.cellWidth : Width of each cell.
      • Necessary field in horizontal scrollMode.
      • undefined : Expand cell width to fit table width, in vertical scrollMode.
    • table.columns : Columns count of each row. Can be used in vertical or horizontal scroll mode.
    • table.rows : Rows count of each column. Can be used in horizontal scroll mode.
    • table.fixedCellSize : Assign columns according to cellWidth (if scrollMode is 0) or cellHeight (if scrollMode is 1) , when initialize and resizing. \u3000\u3000 - false : Ignore this parameter. Default behavior.
      • true : Set columns according to cellWidth/cellHeight.
    • table.mask : A rectangle mask of cells
      • table.mask.padding : Extra left/right/top/bottom padding spacing of this rectangle mask. Default value is 0.
      • table.mask.updateMode : When to update cells mask
        • 0, or update : Apply mask to cell container only when table.updateTable() is invoked. Default behavior.
        • 1, or everyTick : Apply mask to cell container every tick. Use this mode if game objects of cell are moved after table.updateTable() and still been masked.
      • false : No mask.
    • table.enableLayer :
      • false : Add cell game objects into scene's display list. Default behavior.
      • true : Add cell game objects into an internal layer game object. See also.
    • table.reuseCellContainer :
      • true : Reuse cell container when creating new cell container.
      • false : Destory cell container when cell is invisible, create new cell container when cell is visible. Default behavior.
    • table.interactive : Set true to install touch events (tap/press/over/out/click). Default value is true.
    • table.click : Configuration of cell-click behavior, if table.interactive is true.
      • undefined : Use default click behavior.
    • table.tap : Configuration of cell-tap behavior, if table.interactive is true.
      • undefined : Use default tap behavior.
    • table.press : Configuration of cell-press behavior, if table.interactive is true.
      • undefined : Use default press behavior.
    • table.swipe : Configuration of cell-swipe behavior, if table.interactive is true.
      • undefined : Use default swipe behavior.
  • slider : Componments of slider, optional.
    • slider.background : Game object of slider background, optional.
    • slider.track : Game object of track.
    • slider.thumb : Game object of thumb.
    • slider.input :
      • 'pan', 'drag', or 0 : Control slider by panning/dragging thumb game object. Default setting.
      • 'click', or 1 : Control slider by touching track game object.
      • 'none', or -1 : Disable sider controlling.
    • slider.position : Position of this slider.
      • 0, 'right', 'bottom' : Slider at right/bottom side. Default value.
      • 1, 'left', 'top' : Slider at left/top side.
    • slider.hideUnscrollableSlider :
      • false : Slider is always visible no matter it is scrollable or not. Default behavior.
      • true : Set slider to invisible if it is unscrollable.
    • slider.adaptThumbSize :
      • false : Don't adjust height/width of thumb. Default behavior.
      • true : Adjust height/width of thumb according to ratio of visible child.
        • Minimum height/width of thumb = slider.minThumbSize. If content is larger then a page.
        • Maximum height/width of thumb = height/width of slider.track. If content is less then a page.
    • slider.minThumbSize : Minimum height/width of thumb used in slider.adaptThumbSize mode.
    • slider.buttons : Press button to scroll content in each tick.
      • slider.buttons.top, slider.buttons.bottom : Top and bottom buttons.
      • slider.buttons.left, slider.buttons.right : Left and right buttons
      • slider.buttons.step : Scrolling step in each tick. Default value is 0.01.
    • Set to false to skip creating slider.
  • sliderX, sliderY : Componments of sliderX and sliderY, for two-sliders mode.
  • scroller : Configuration of scroller behavior.
    • scroller.threshold : Minimal movement to scroll. Set 0 to scroll immediately.
    • scroller.slidingDeceleration : Deceleration of slow down when dragging released.
      • Set false to disable it.
    • scroller.backDeceleration : Deceleration of pull back when out of bounds.
      • Set false to disable it.
    • scroller.pointerOutRelease : Set to true to release input control when pointer out of gameObject.
    • scroller.rectBoundsInteractive :
      • false : Detect scrolling by game object's touch input.
      • true : Detect scrolling by rectangle bounds of game object. Default behavior.
    • scroller.dragRate : Rate of dragging distance/dragging speed. Default value is 1.
    • Set to false to skip creating scroller.
  • scrollerX, scrollerY : Configuration of scrollerX, scrollerY behavior, for two-sliders mode.
  • mouseWheelScroller : Configuration of mouse-wheel-scroller behavior.
    • mouseWheelScroller.focus :
      • false, or 0 : Without checking if cursor is over game object or not.
      • true, or 1 : Cursor is inside the rectangle bounds of game object. Default behavior.
      • 2 : Cursor is over game object.
    • mouseWheelScroller.speed : Scrolling speed, default value is 0.1.
    • Set to false to skip creating mouse-wheel-scroller. Default behavior.
  • mouseWheelScrollerX, mouseWheelScrollerY : Configuration of mouse-wheel-scrollerX, or mouse-wheel-scrollerY behavior, for two-sliders mode.
  • clampChildOY : Set true to clamp scrolling.
  • createCellContainerCallback : Callback to return a container object, or null of each visible cell.
    • Properties of cell parameter
      • cell.scene : Scene of this grid table object.
      • cell.width : Width of this cell, in pixels.
      • cell.height : Height of this cell, in pixels.
      • cell.item : Item of this cell to display.
      • cell.items : Array of item data for each cell, equal to items parameter.
      • cell.index : Index of this cell.
    • Alignment of cellContainer :
      cell.setCellContainerAlign(align);\n
      • align :
        • undefined : Set position of cellContainer to left-top of cell space. Default behavior.
        • 'center', or Phaser.Display.Align.CENTER : Align game object at center of cell space.
        • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center of cell space.
        • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center of cell space.
        • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game object at top-center of cell space.
        • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at bottom-center of cell space.
    • If cell.align is undefined (default value), Origin of returned cell container will be set to (0, 0)
    • cellContainer : Cell container picked from object pool for reusing. Set reuseCellContainer to true to enable this feature.
      • null : No cell container available.
      • Game object : Reusable cell container.
  • header : Game object of header, optional.
  • footer : Game object of footer, optional.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.table :
      • A number: Space between table object and slider object.
      • An object: Padding of table object.
        • If scrollMode is 0 (vertical) :
          • space.table.top, space.table.bottom : Top, bottom padding space of table object.
          • space.table.right : Space between table object and slider object.
        • If scrollMode is 1 (horizontal) :
          • space.table.left, space.table.right : Left, right padding space of table object.
          • space.table.bottom : Space between table object and slider object.
    • space.slider :
      • 0 : No space around slider.
      • space.slider.left, space.slider.right, space.slider.top, space.slider.bottom : Space around slider.
    • space.sliderX, space.sliderX : Space configuration of sliderX, sliderX, for two-sliders mode.
      • 0 : No space around slider.
    • space.header : Space between header and table.
    • space.footer : Space between footer and table.
  • expand : Expand width or height of element
    • expand.header : Set true to expand width or height of header game object.
    • expand.footer : Set true to expand width or height of footer game object.
  • align : Align element
    • align.header
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • align.footer
  • items : Array of item data for each cell.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
"},{"location":"ui-gridtable/#scroll-mode","title":"Scroll mode","text":"

If scrollMode parameter is not given :

  • Set scrollMode to 2, if configuration has sliderX, sliderY, or scrollerX, scrollerY parameters.
  • Set scrollMode to 0, if configuration has sliderY, or scrollerY parameters.
  • Set scrollMode to 1, if configuration has sliderX, or scrollerX parameters.
"},{"location":"ui-gridtable/#custom-class","title":"Custom class","text":"
  • Define class
    class MyGridTable extends RexPlugins.UI.GridTable {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var table = new MyGridTable(scene, config);\n
"},{"location":"ui-gridtable/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

table.layout();\n

See also - dirty

"},{"location":"ui-gridtable/#items","title":"Items","text":"
  • Set
    table.setItems(items);\n
    • items : Array of item data for each cell.
    • This method will update each visible cell of grid table.
  • Clear all items
    table.setItems();\n
  • Get
    var items = table.items;\n
  • Add item
    Phaser.Utils.Array.Add(table.items, item);\ntable.refresh();\n
  • Insert item
    Phaser.Utils.Array.AddAt(table.items, item, index);\ntable.refresh();\n
  • Remove item
    Phaser.Utils.Array.Remove(table.items, item);\ntable.refresh();\n
  • Remove item at index
    Phaser.Utils.Array.RemoveAt(table.items, index);\ntable.refresh();\n
  • Remove items between indexes
    Phaser.Utils.Array.RemoveBetween(table.items, startIndex, endIndex);\ntable.refresh();\n
  • Remove random item
    Phaser.Utils.Array.RemoveRandomElement(table.items);\ntable.refresh();\n
"},{"location":"ui-gridtable/#cell-container","title":"Cell container","text":"
  • Get
    var container = table.getCellContainer(cellIndex);\n
"},{"location":"ui-gridtable/#reset-size-of-all-cells","title":"Reset size of all cells","text":"
table.resetAllCellsSize(width, height);\n
"},{"location":"ui-gridtable/#scroll-content","title":"Scroll content","text":"
  • Set
    table.childOY = oy;\n// table.setChildOY(oy);\n
  • Set and clamp
    table.setChildOY(oy, true);\n
  • Add
    table.addChildOY(oy);\n
  • Add and clamp
    table.addChildOY(oy, true);\n
  • Get
    var childOY = table.childOY;\n
  • Top OY
    var topOY = table.topChildOY;\n
  • Bottom OY
    var bottomOY = table.bottomChildOY;\n
  • Is overflow (height of content is larger than display height)
    var isOverflow = textArea.isOverflow;\n
"},{"location":"ui-gridtable/#scroll-by-percentage","title":"Scroll by percentage","text":"
  • Set
    table.t = t;  // t: 0~1\n// table.setT(t);  \n
  • Set and clamp
    table.setT(t, true);\n
  • Get
    var t = table.t;\n
"},{"location":"ui-gridtable/#scroll-to-topbottom","title":"Scroll to top/bottom","text":"
  • Scroll to top
    table.scrollToTop();\n
    • Equal to table.t = 0;
  • Scroll to bottom
    table.scrollToBottom();\n
    • Equal to table.t = 1;
"},{"location":"ui-gridtable/#scroll-to-row","title":"Scroll to row","text":"
  • Scroll to next row
    table.scrollToNextRow();\n
  • Scroll to next n row
    table.scrollToNextRow(n);\n
  • Scroll to row
    table.scrollToRow(rowIndex);\n
  • Get current row index
    var rowIndex = table.startRowIndex;\n
"},{"location":"ui-gridtable/#enabledisable-scrolling","title":"Enable/disable scrolling","text":"
  • Slider
    • Set enable state
      table.setSliderEnable(enabled);\n
      or
      table.sliderEnable = enabled;\n
    • Get enable state
      var enable = table.sliderEnable;\n
  • Scroller
    • Set enable state
      table.setScrollerEnable(enabled);\n
      or
      table.scrollerEnable = enabled;\n
    • Get enable state
      var enable = table.scrollerEnable;\n
  • Mouse-Wheel-Scroller
    • Set enable state
      table.setMouseWheelScrollerEnable(enabled);\n
      or
      table.mouseWheelScrollerEnable = enabled;\n
    • Get enable state
      var enable = table.mouseWheelScrollerEnable;\n
"},{"location":"ui-gridtable/#refresh-table-cells","title":"Refresh table cells","text":"
  • Refresh all visible cells
    table.refresh();\n
    • Equal to table.setItems(table.items).
  • Update a visible cell
    table.updateVisibleCell(cellIndex);\n
"},{"location":"ui-gridtable/#table-size","title":"Table size","text":"
  • Table width
    var tableWidth = table.getElement('table').tableWidth;\n
  • Table height
    var tableHeight = table.getElement('table').tableHeight;\n
"},{"location":"ui-gridtable/#other-properties","title":"Other properties","text":"

See base sizer object, container-lite.

"},{"location":"ui-gridtable/#events","title":"Events","text":"
  • Pointer-down cell
    table.on('cell.down', function(cellContainer, cellIndex, pointer, event) {\n// ...\n}, scope);\n
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-up cell
    table.on('cell.up', function(cellContainer, cellIndex, pointer, event) {\n// ...\n}, scope);\n
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-over cell
    table.on('cell.over', function(cellContainer, cellIndex, pointer, event) {\n// ...\n}, scope);\n
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-out cell
    table.on('cell.out', function(cellContainer, cellIndex, pointer, event) {\n// ...\n}, scope);\n
    • Cancel remaining touched events : event.stopPropagation()
  • Click cell
    table.on('cell.click', function(cellContainer, cellIndex, pointer, event) {\n// ...\n}, scope);\n
    • Cancel remaining touched events : event.stopPropagation()
  • Tap cell
    table.on(tapEventName, function(cellContainer, cellIndex, pointer) {\n// ...\n}, scope);\n
    • tapEventName : 'cell.1tap', 'cell.2tap', 'cell.3tap', etc ...
    • cellContainer : Container game object of triggered cell.
    • cellIndex : Index of triggered cell.
  • Press cell
    table.on(`cell.pressstart`, function(cellContainer, cellIndex, pointer) {\n// ...\n}, scope);\n
    table.on(`cell.pressend`, function(cellContainer, cellIndex, pointer) {\n// ...\n}, scope);\n
  • Swipe cell
    table.on(swipeEventName, function(cellContainer, cellIndex, pointer) {\n// ...\n}, scope);\n
    • swipeEventName : 'cell.swipeleft', 'cell.swiperight', 'cell.swipeup', 'cell.swipedown'.
  • Scroll table
    table.on('scroll', function(table) {\n// ...\n})\n
  • Slider
    • Slider drag start
      table.getElement('slider').on('inputstart', function(panel) {\n// ...\n})\n
    • Slider drag end
      table.getElement('slider').on('inputend', function(panel) {\n// ...\n})\n
  • Scroller
    • Scroller drag start
      table.getElement('scroller').on('dragstart', function(panel) {\n// ...\n})\n
    • Scroller drag end
      table.getElement('scroller').on('dragend', function(panel) {\n// ...\n})\n
"},{"location":"ui-gridtable/#interactive-with-child-of-cell","title":"Interactive with child of cell","text":"
table.on('cell.click', function(cellContainer, cellIndex, pointer, event) {\nvar child;\n// child = cellContainer.getElement(...);\nif (cellContainer.isPointerInBounds(child)) {\n// Pointer on this child\n}\n}, scope);\n

Reference of isPointerInBounds method

"},{"location":"ui-gridtable/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = table.getElement('background');\n
    • Grid table
      var tableBody = table.getElement('table');\n
    • Layer of gridtable, assigned at config table.mask.layer.
      var layer = table.getElement('tableLayer');\n
    • Slider
      • Track
        var track = table.getElement('slider.track');\n
      • Thumb
        var thumb = table.getElement('slider.thumb');\n
    • Scroller
      var scroller = table.getElement('scroller');\n
    • Header game object
      var tableBody = table.getElement('header');\n
    • Footer game object
      var tableBody = table.getElement('footer');\n
  • Get by name
    var gameObject = table.getElement('#' + name);\n// var gameObject = table.getElement('#' + name, recursive);\n
    or
    var gameObject = table.getByName(name);\n// var gameObject = table.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-holygrail/","title":"Holy grail","text":""},{"location":"ui-holygrail/#introduction","title":"Introduction","text":"

Layout elements in Holy grail style.

  • Author: Rex
  • Game object
"},{"location":"ui-holygrail/#live-demos","title":"Live demos","text":"
  • Simple
  • Align
  • Layout modes
  • Change layout mode
"},{"location":"ui-holygrail/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-holygrail/#install-plugin","title":"Install plugin","text":""},{"location":"ui-holygrail/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add holy-grail object
    var holyGrail = scene.rexUI.add.holyGrail(config);\n
"},{"location":"ui-holygrail/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add holy-grail object
    var holyGrail = scene.rexUI.add.holyGrail(config);\n
"},{"location":"ui-holygrail/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { HolyGrail } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add holy-grail object
    var holyGrail = new HolyGrail(scene, config);\nscene.add.existing(holyGrail);\n
"},{"location":"ui-holygrail/#add-holygrail-object","title":"Add holyGrail object","text":"
var holyGrail = scene.rexUI.add.holyGrail({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nlayoutMode: 0,\n\n// Elements\nbackground: backgroundGameObject,\n\nheader: headerGameObject,\n\nleftSide: leftSideGameObject,\n\ncontent: contentGameObject,\n\nrightSide: rightSideGameObject,\n\nfooter: footerGameObject,\n\n// Space\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nheader: 0,  // {left, right, top, bottom}\nfooter: 0,  // {left, right, top, bottom}\nleftSide: 0, // {left, right, top, bottom}\nrightSide: 0, // {left, right, top, bottom}\n},\n\n// proportion: {\n//     header: 0,\n//     footer: 0,\n//     leftSide: 0,\n//     rightSide: 0,\n//     content: 1,\n// },\n\n// expand: {\n//     header: true,\n//     footer: true,\n//     leftSide: true,\n//     rightSide: true,\n//     content: false,\n// },\n\n// align: {\n//     header: 'center',\n//     footer: 'center',\n//     leftSide: 'center',\n//     rightSide: 'center',\n//     content: 'center',\n// },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • layoutMode : Expand left side, right side to bottom row.
    • 0, or 'FFF' : Bottom row is footer. Default behavior
    • 1, or 'LFF' : Left side will expand down to bottom row.
    • 2, or 'FFR' : Right side will expand down to bottom row.
    • 3, or 'LFR' : Left side and right side will expand down to bottom row.
  • background : Game object of background, optional. This background game object will be resized to fit the size of holyGrail.
  • header : Game object of header, optional.
    • Will fixed height (proportion=0) and expand width (expand=true) width default setting.
  • leftSide : Game object of leftSide, optional.
    • Will fixed width (proportion=0) and expand height (expand=true) width default setting.
  • content : Game object of content, optional.
    • Will expand width (proportion=1) and expand height (expand=true) width default setting.
  • rightSide : Game object of rightSide, optional.
    • Will fixed width (proportion=0) and expand height (expand=true) width default setting.
  • footer : Game object of footer, optional.
    • Will fixed height (proportion=0) and expand width (expand=true) width default setting.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.header :
      • A number : Space between header game object and below game object, equal to {bottom}
      • {left, right, top, bottom} : Padding values of header game object.
    • space.footer
      • A number : Space between footer game object and above game object, equal to {top}
      • {left, right, top, bottom} : Padding values of footer game object.
    • space.leftSide :
      • A number : Space between leftSide game object and content game object, equal to {right}
      • {left, right, top, bottom} : Padding values of leftSide game object.
    • space.rightSide :
      • A number : Space between rightSide game object and content game object, equal to {left}
      • {left, right, top, bottom} : Padding values of rightSide game object.
  • expand : Expand width or height of element
    • expand.header : Set true to expand width of header game object. Default is true.
    • expand.footer : Set true to expand width of footer game object. Default is true.
    • expand.leftSide : Set true to expand height of leftSide game object. Default is true.
    • expand.rightSide : Set true to expand height of rightSide game object. Default is true.
    • expand.content : Set true to expand height of content game object. Default is true.
  • proportion : Fixed width or height of element
    • proportion.header :
      • 0 : Fixed height. Default behavior.
      • 1, or other numbers : Expand height.
    • proportion.footer :
      • 0 : Fixed height. Default behavior.
      • 1, or other numbers : Expand height.
    • proportion.leftSide :
      • 0 : Fixed width. Default behavior.
      • 1, or other numbers : Expand width.
    • proportion.rightSide :
      • 0 : Fixed width. Default behavior.
      • 1, or other numbers : Expand width.
    • proportion.content :
      • 0 : Fixed width.
      • 1, or other numbers : Expand width. Default value is 1.
  • align : Align element
    • align.header
    • align.footer
    • align.leftSide
    • align.rightSide
    • align.content
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false..
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-holygrail/#custom-class","title":"Custom class","text":"
  • Define class
    class MyHolyGrail extends RexPlugins.UI.HolyGrail {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var holyGrail = new MyHolyGrail(scene, config);\n
"},{"location":"ui-holygrail/#layout-modes","title":"Layout modes","text":""},{"location":"ui-holygrail/#mode-0","title":"Mode 0","text":"

Bottom row is footer. Default behavior.

Header Left side Content Right side Footer"},{"location":"ui-holygrail/#mode-1","title":"Mode 1","text":"

Left side will expand down to bottom row.

Header Left side Content Right side Footer"},{"location":"ui-holygrail/#mode-2","title":"Mode 2","text":"

Right side will expand down to bottom row.

Header Left side Content Right side Footer"},{"location":"ui-holygrail/#mode-3","title":"Mode 3","text":"

Left side and right side will expand down to bottom row.

Header Left side Content Right side Footer"},{"location":"ui-holygrail/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

holyGrail.layout();\n

See also - dirty

"},{"location":"ui-holygrail/#re-build","title":"Re-build","text":"

Destroy current elements then add elements with new config.

holyGrail\n.build({\n// Elements\nbackground: backgroundGameObject,\n\nheader: headerGameObject,\n\nleftSide: leftSideGameObject,\n\ncontent: contentGameObject,\n\nrightSide: rightSideGameObject,\n\nfooter: footerGameObject,\n\nlayoutMode: 0,\n\n// Space\nspace: {        header: 0,  // {left, right, top, bottom}\nfooter: 0,  // {left, right, top, bottom}\nleftSide: 0, // {left, right, top, bottom}\nrightSide: 0, // {left, right, top, bottom}\n},\n\n// proportion: {\n//     header: 0,\n//     footer: 0,\n//     leftSide: 0,\n//     rightSide: 0,\n//     content: 1,\n// },\n\n// expand: {\n//     header: true,\n//     footer: true,\n//     leftSide: true,\n//     rightSide: true,\n//     content: false,\n// },\n\n// align: {\n//     header: 'center',\n//     footer: 'center',\n//     leftSide: 'center',\n//     rightSide: 'center',\n//     content: 'center',\n// },\n})\n.layout()\n
"},{"location":"ui-holygrail/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-holygrail/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = holyGrail.getElement('background');\n
    • Header game object
      var header = holyGrail.getElement('header');\n
    • Left-side game object
      var leftSide = holyGrail.getElement('leftSide');\n
    • Content game object
      var content = holyGrail.getElement('content');\n
    • Right-side game object
      var rightSide = holyGrail.getElement('rightSide');\n
    • Footer game object
      var footer = holyGrail.getElement('footer');\n
  • Get by name
    var gameObject = holyGrail.getElement('#' + name);\n// var gameObject = holyGrail.getElement('#' + name, recursive);\n
    or
    var gameObject = holyGrail.getByName(name);\n// var gameObject = holyGrail.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-imageinputlabel/","title":"Image input label","text":""},{"location":"ui-imageinputlabel/#introduction","title":"Introduction","text":"

A container with a canvas icon, text, and background. Click icon to popup a (image) file chooser dialog, display selected image on canvas.

  • Author: Rex
  • Game object
"},{"location":"ui-imageinputlabel/#live-demos","title":"Live demos","text":"
  • Save texture
"},{"location":"ui-imageinputlabel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-imageinputlabel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-imageinputlabel/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add image-input label object
    var imageInputLabel = scene.rexUI.add.imageInputLabel(config);\n
"},{"location":"ui-imageinputlabel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin, enable dom element in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\nparent: divId,\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Add image-input label object
    var imageInputLabel = scene.rexUI.add.imageInputLabel(config);\n
"},{"location":"ui-imageinputlabel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import { ImageInputLabel } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add image-input label object
    var imageInputLabel = new ImageInputLabel(scene, config);\nscene.add.existing(imageInputLabel);\n
"},{"location":"ui-imageinputlabel/#add-imageinputlabel-object","title":"Add imageInputLabel object","text":"
var imageInputLabel = scene.rexUI.add.imageInputLabel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\n\ncanvas: {\n// width: 128, \n// height: 128,\n// fill: undefined,\n\n// key: undefined, \n// frame: undefined,        \n},\n\n// scaleUpIcon: false,\n\niconBackground: iconBackgroundGameObject,    // squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntext: textGameObject,\nexpandTextWidth: false,\nexpandTextHeight: false,\n\naction: actionGameObject,\n// actionMask: false,\n// squareFitAction: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nalign: undefined,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0, iconTop: 0, iconBottom: 0, iconLeft: 0, iconRight: 0,\n\ntext: 0,\nactionTop: 0, actionBottom: 0, actionLeft: 0, actionRight: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n\n// clickTarget: undefined,\n// domButton: true,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of imageInputLabel.
  • canvas : Parameters of creating canvas game object.
    • canvas.width, canvas.height, canvas.fill : Create canvas with size (canvas.width x canvas.height), filling by color canvas.fill.
    • canvas.key, canvas.frame : Create canvas then paste texture canvas.key, canvas.frame.
  • iconBackground : Game object of iconBackground, optional.
    • icon game object will be created internally by imageBox with canvas.
  • squareFitIcon :
    • true : Resize icon size to square to fit imageInputLabel height/width.
      • Can't work wit expandTextWidth: true
    • false : Ignore this feature. Default behavior.
  • iconSize : Set display size of icon game object to iconSizexiconSize
  • iconWidth : Set display width of icon game object to iconWidth.
    • If iconHeight is undefined, set scaleY of icon game object to scaleX of icon game object, to keep size ratio.
  • iconHeight : Set display height of icon game object to iconHeight.
    • If iconWidth is undefined, set scaleX of icon game object to scaleY of icon game object, to keep size ratio.
  • scaleUpIcon :
    • true : Scale-up canvas game object if its size is smaller than icon (imageBox).
    • false : Keep current size when its size is smaller than icon (imageBox). Default behavior.
  • text : Game object of text, optional.
  • expandTextWidth :
    • false : Keep width of text to original size. Default behavior.
    • true : Expand width of text object. Will set display width by default.
      • Must set to true if using scene.rexUI.wrapExpandText method with any text game object.
      • Can't work with squareFitIcon: true.
  • expandTextHeight : Set true to expand height of text object.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • squareFitAction :
    • true : Resize action icon size to square to fit imageInputLabel height/width.
    • false : Ignore this feature. Default behavior.
  • actionSize : Set display size of action game object to actionSizexactionSize
  • actionWidth : Set display width of action game object to actionWidth.
    • If actionHeight is undefined, set scaleY of action game object to scaleX of action game object, to keep size ratio.
  • actionHeight : Set display height of action game object to actionHeight.
    • If actionWidth is undefined, set scaleX of action game object to scaleY of action game object, to keep size ratio.
  • align : Alignment of icon, text, action game objects.
    • undefined, or 'left', or 'top' : Align game objects at left, or top.
    • 'center' : Align game objects at center.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.icon : Space between icon game object and text game object.
    • space.iconTop, space.iconBottom, space.iconLeft, space.iconRight : Space around icon game object.
    • space.text : Space between text game object and action icon game object.
    • space.actionTop, space.actionBottom, space.actionLeft, space.actionRight : Space around action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • clickTarget : Click target to open file chooser dialog
    • A string, 'icon', 'text', 'action', 'background' : Click icon, text, action, background game object to open file chooser dialog.
    • undefined : Click this ImageInputLabel game object to open file chooser dialog. Default behavior.
    • null, false : No clickTarget. Open file chooser dialog manually under a touch event.
  • domButton :
    • true : Put DOM buttom above clickTarget, to receive click event.
    • false : Add click event at clickTarget.
      • This mode won't work at ios
"},{"location":"ui-imageinputlabel/#expand-size-of-text","title":"Expand size of text","text":"

Expand width/height of text when expandTextWidth/expandTextHeight is true

To resize text object, text object should have resize method. For example

class MyText extends Phaser.GameObjects.Text {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\nscene.add.existing(this);\n}\nresize(width, height) {\nthis.setFixedSize(width, height);\nreturn this;\n}\n}\n

Or uses bbcode text object, tag text object, canvasInput object.

"},{"location":"ui-imageinputlabel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLabel extends RexPlugins.UI.ImageInputLabel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var imageInputLabel = new MyLabel(scene, config);\n
"},{"location":"ui-imageinputlabel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

imageInputLabel.layout();\n

See also - dirty

"},{"location":"ui-imageinputlabel/#open-file-chooser-dialog","title":"Open file chooser dialog","text":"

Failure

This method can't run at ios.

Note

Open a file chooser dialog under any touch event. i.e. User can't open file chooser dialog directly.

imageInputLabel.openPromise()\n.then(function(file){\n})\n
  • file : File object
imageInputLabel.open()\n
"},{"location":"ui-imageinputlabel/#enable-clicking-open","title":"Enable clicking-open","text":"
  • Enable
    imageInputLabel.setClickOpenEnable();\n// imageInputLabel.setClickOpenEnable(true);\n
  • Disable
    imageInputLabel.setClickOpenEnable(false)\n
"},{"location":"ui-imageinputlabel/#save-texture","title":"Save texture","text":"

Save image on canvas into texture manager.

imageInputLabel.saveTexture(key);\n
"},{"location":"ui-imageinputlabel/#events","title":"Events","text":"
  • Select file
    imageInputLabel.on('select', function(file, imageInputLabel) {\n\n})\n
    • file : File object
"},{"location":"ui-imageinputlabel/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = imageInputLabel.getElement('background');\n
    • Canvas game object (a canvas game object created internally)
      var canvas = imageInputLabel.getElement('canvas');\n
    • Icon background game object
      var iconBackground = imageInputLabel.getElement('iconBackground');\n
    • Icon game object (an imageBox game object created internally)
      var imageBox = imageInputLabel.getElement('icon');\n
    • Text game object
      var textObject = imageInputLabel.getElement('text');\n
    • Action icon game object
      var action = imageInputLabel.getElement('action');\n
    • File chooser game object, if domButton is set to true
      var fileChooser = imageInputLabel.getElement('fileChooser');\n
  • Get by name
    var gameObject = imageInputLabel.getElement('#' + name);\n// var gameObject = imageInputLabel.getElement('#' + name, recursive);\n
    or
    var gameObject = imageInputLabel.getByName(name);\n// var gameObject = imageInputLabel.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-imageinputlabel/#other-properties","title":"Other properties","text":"

See label), sizer object, base sizer object, container-lite.

"},{"location":"ui-knob/","title":"Knob","text":""},{"location":"ui-knob/#introduction","title":"Introduction","text":"

A knob button based on circular progress shape.

  • Author: Rex
  • Game object
"},{"location":"ui-knob/#live-demos","title":"Live demos","text":"
  • Knob
"},{"location":"ui-knob/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-knob/#install-plugin","title":"Install plugin","text":""},{"location":"ui-knob/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add knob object
    var knob = scene.rexUI.add.knob(config);\n
"},{"location":"ui-knob/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add knob object
    var knob = scene.rexUI.add.knob(config);\n
"},{"location":"ui-knob/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Knob } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add knob object
    var knob = new Knob(scene, config);\nscene.add.existing(knob);\n
"},{"location":"ui-knob/#add-knob-object","title":"Add knob object","text":"
var knob = scene.rexUI.add.knob({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\n\nbarColor: undefined,\ntrackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nanticlockwise: false,\n// iterations: 128,\nknobDepth: 0,\n\ntext: undefined,\ntextFormatCallback: undefined,\ntextFormatCallbackScope: undefined,\n\ninput: 'pan',\n\nvalue: 0,\ngap: undefined,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, knob) {\n},\nvaluechangeCallbackScope: undefined,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n\nenable: true,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of knob.
  • barColor : Color of circular bar, in number or css string value.
  • trackColor : Color of circular track, in number or css string value.
  • centerColor : Color of center circle, in number or css string value.
  • thickness : 0 ~ 1, thickness of circular bar. Default value is 0.2 (0.2*radius)
  • startAngle : Start angle of circular bar, in radians. Default value is 270 degrees.
  • anticlockwise : Set true to put anticlockwise circular bar. Default value is false.
  • iterations : Iterations of curve, set larger value to get more smooth rendering result. Default value is 128.
  • knobDepth : Depth of knob (circular progress). Default value is 0.
  • text : Label, Text, BBCodeText, or TagText, which has setText(text) method, optional.
    • Don't set textColor, textStrokeColor if text parameter is provided.
    • Depth of text object ought to larger than knob (circular progress), to put text object in front of knob.
  • Display text :
    • textColor : Color of display text. Default is undefined.
    • textStrokeColor, textStrokeThickness : Stroke color, stroke line width of display text. Default is undefined.
    • textSize, textFamily, textStyle : Size, family, style of display text.
  • textFormatCallback, textFormatCallbackScope : Formating callback of display text. ex:
    function(value) {\nreturn Math.floor(value * 100).toString();\n}\n
    Default value is undefined.
  • input :
    • 'pan', 'drag', or 0 : Control knob by panning circular progress. Default setting.
    • 'click', or 1 : Control knob by touching circular progress.
    • 'none', or -1 : Disable knob controlling.
  • value : Initial value (0 ~ 1).
  • gap : Snap a value to nearest grid slice, using rounding.
    • undefined : Disalbe this feature.
  • easeValue : Easing value when input is 'click'.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
  • valuechangeCallback : callback function when value changed.
  • enable : Set false to disable controlling.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-knob/#custom-class","title":"Custom class","text":"
  • Define class
    class MyKnob extends RexPlugins.UI.Knob {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var knob = new MyKnob(scene, config);\n
"},{"location":"ui-knob/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

knob.layout();\n

See also - dirty

"},{"location":"ui-knob/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = knob.getElement('background');\n
    • Circular progress game object
      var circularProgress = knob.getElement('knob');\n
    • Text game object
      var text = knob.getElement('text');\n
  • Get by name
    var gameObject = knob.getElement('#' + name);\n// var gameObject = knob.getElement('#' + name, recursive);\n
    or
    var gameObject = knob.getByName(name);\n// var gameObject = knob.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-knob/#enable","title":"Enable","text":"
  • Get
    var enable = knob.enable;\n
  • Set
    knob.setEanble(enable);\n
    or
    knob.enable = enable;\n
"},{"location":"ui-knob/#value","title":"Value","text":"

Change value will also change the position of knob thumb and width of knob indicator.

  • Get value
    var value = knob.getValue(min, max); // value : min ~ max\n
    or
    var value = knob.getValue(); // value: 0 ~ 1\n
    or
    var value = knob.value; // value: 0 ~ 1\n
  • Set value
    knob.setValue(value, min, max); // value: min ~ max\n
    or
    knob.setValue(value); // value: 0 ~ 1\n
    or
    knob.value = value; // value: 0 ~ 1\n
  • Increase value
    knob.addValue(inc, min, max); // inc: min ~ max\n
    or
    knob.addValue(inc); // inc: 0 ~ 1\n
    or
    knob.value += inc; // inc: 0 ~ 1\n
"},{"location":"ui-knob/#ease-value","title":"Ease value","text":"
  • Ease value to
    knob.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    knob.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    knob.stopEaseValue();\n
  • Set ease duration
    knob.setEaseValueDuration(duration);\n
  • Set ease function
    knob.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"ui-knob/#other-properties","title":"Other properties","text":"

See overlap sizer object, base sizer object, container-lite.

"},{"location":"ui-knob/#events","title":"Events","text":"
  • On value changed
    knob.on('valuechange', function(newValue, oldValue, knob){\n//\n}, scope);\n
"},{"location":"ui-label/","title":"Label","text":""},{"location":"ui-label/#introduction","title":"Introduction","text":"

A container with an icon, text, and background.

  • Author: Rex
  • Game object
"},{"location":"ui-label/#live-demos","title":"Live demos","text":"
  • Align
  • Add to layer
  • Text wrap in horizontal label
  • Text wrap in vertical label
  • Adjust text font size
  • Square fit icon
  • Icon size
"},{"location":"ui-label/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-label/#install-plugin","title":"Install plugin","text":""},{"location":"ui-label/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add label object
    var label = scene.rexUI.add.label(config);\n
"},{"location":"ui-label/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add label object
    var label = scene.rexUI.add.label(config);\n
"},{"location":"ui-label/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Label } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add label object
    var label = new Label(scene, config);\nscene.add.existing(label);\n
"},{"location":"ui-label/#add-label-object","title":"Add label object","text":"
var label = scene.rexUI.add.label({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\n\nicon: iconGameObject,\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntext: textGameObject,\n// wrapText: false,\n// adjustTextFontSize: false,\n// expandTextWidth: false,\n// expandTextHeight: false,\n\naction: actionGameObject,\n// actionMask: false,\n// squareFitAction: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nalign: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\n\nicon: 0, iconTop: 0, iconBottom: 0, iconLeft: 0, iconRight: 0,\n\ntext: 0,\nactionTop: 0, actionBottom: 0, actionLeft: 0, actionRight: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • squareFitIcon :
    • true : Resize icon size to square to fit label height/width.
      • Can't work wit expandTextWidth: true
    • false : Ignore this feature. Default behavior.
  • iconSize : Set display size of icon game object to iconSizexiconSize
  • iconWidth : Set display width of icon game object to iconWidth.
    • If iconHeight is undefined, set scaleY of icon game object to scaleX of icon game object, to keep size ratio.
  • iconHeight : Set display height of icon game object to iconHeight.
    • If iconWidth is undefined, set scaleX of icon game object to scaleY of icon game object, to keep size ratio.
  • text : Game object of text, optional.
  • wrapText : Enable WrapExpandText feature.
    • false, 0 : No WrapExpandText feature. Default behavior.
    • true, 1, 'word' : Word WrapExpandText.
      • Text-width will be expanding.
    • 2, 'char' : Character WrapExpandText.
      • Text-width will be expanding.
  • adjustTextFontSize : Enable FontSizeExpandText feature.
    • false : No FontSizeExpandText feature. Default behavior.
    • true : Enable FontSizeExpandText feature. Can't work with wrapText: true.
      • Text-width and text-height will be expanding.
      • Use BBCodeText (scene.rexUI.add.BBCodeText) with {valign: 'center'} style.
  • expandTextWidth :
    • false : Keep width of text to original size. Default behavior.
    • true : Expand width of text object. Will set display width by default.
      • Must set to true if using scene.rexUI.wrapExpandText method with any text game object.
      • Can't work with squareFitIcon: true.
  • expandTextHeight : Set true to expand height of text object.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • squareFitAction :
    • true : Resize action icon size to square to fit label height/width.
    • false : Ignore this feature. Default behavior.
  • actionSize : Set display size of action game object to actionSizexactionSize
  • actionWidth : Set display width of action game object to actionWidth.
    • If actionHeight is undefined, set scaleY of action game object to scaleX of action game object, to keep size ratio.
  • actionHeight : Set display height of action game object to actionHeight.
    • If actionWidth is undefined, set scaleX of action game object to scaleY of action game object, to keep size ratio.
  • align : Alignment of icon, text, action game objects.
    • undefined, or 'left', or 'top' : Align game objects at left, or top.
    • 'center' : Align game objects at center.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.icon : Space between icon game object and text game object.
    • space.iconTop, space.iconBottom, space.iconLeft, space.iconRight : Space around icon game object.
    • space.text : Space between text game object and action icon game object.
    • space.actionTop, space.actionBottom, space.actionLeft, space.actionRight : Space around action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-label/#expand-size-of-text","title":"Expand size of text","text":"

Expand width/height of text when expandTextWidth/expandTextHeight is true

To resize text object, text object should have resize method. For example

class MyText extends Phaser.GameObjects.Text {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\nscene.add.existing(this);\n}\nresize(width, height) {\nthis.setFixedSize(width, height);\nreturn this;\n}\n}\n

Or uses bbcode text object, tag text object, or canvasInput object.

"},{"location":"ui-label/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLabel extends RexPlugins.UI.Label {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var label = new MyLabel(scene, config);\n
"},{"location":"ui-label/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

label.layout();\n

See also - dirty

"},{"location":"ui-label/#change-childrens-align-mode","title":"Change children's align mode","text":"
label\n.setChildrenAlignMode(mode)\n.layout();\n
  • mode : Alignment of icon, text, action game objects.
    • undefined, or 'left', or 'top' : Align game objects at left, or top.
      • Remove first and last space children.
    • 'center' : Align game objects at center.
      • Add two spaces as first and last children.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
      • Add space as first child.
"},{"location":"ui-label/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = label.getElement('background');\n
    • Icon game object
      var icon = label.getElement('icon');\n
    • Text game object
      var textObject = label.getElement('text');\n
    • Action icon game object
      var action = label.getElement('action');\n
  • Get by name
    var gameObject = label.getElement('#' + name);\n// var gameObject = label.getElement('#' + name, recursive);\n
    or
    var gameObject = label.getByName(name);\n// var gameObject = label.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-label/#text","title":"Text","text":"
  • Get text string
    var s = label.text;\n
  • Set text string
    label.setText(s);\n
    or
    label.text = s;\n
  • Append text string
    label.appendText(text);\n// label.text += '\\n' + text;\n
    or
    label.appendText(text, false);\n// label.text += text;\n
"},{"location":"ui-label/#icon-texture","title":"Icon texture","text":"
  • Set texture
    label.setTexture(key);\n// label.setTexture(key, frame);\n
  • Set texture via texture object
    label.setTexture(texture);\n// label.setTexture(texture, frame);\n
  • Get texture, frame
    var texture = label.texture;\nvar frame = label.frame;\n
  • Get texture key, frame name
    var textureKey = label.texture.key;\nvar frameName = label.frame.name;\n
"},{"location":"ui-label/#reset-display-content","title":"Reset display content","text":"
label.resetDisplayContent({\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n})\n

or

label.resetDisplayContent(text);\n
  • text : Set text string.
  • icon, iconFrame
    • A string : Set texture of icon game object.
    • undefined, or null : Hide icon game object.
    • true : Show icon game object without change its texture.
  • iconSize : Set display size of icon game object.
  • action, actionFrame
    • A string : Set texture of icon game object.
    • undefined, or null : Hide action game object.
    • true : Show action game object without change its texture.
  • actionSize : Set display size of action game object.

Run label.layout() after this method, to layout children again.

"},{"location":"ui-label/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-menu/","title":"Menu","text":""},{"location":"ui-menu/#introduction","title":"Introduction","text":"

A container with buttons and sub-menu.

  • Author: Rex
  • Game object
"},{"location":"ui-menu/#live-demos","title":"Live demos","text":"
  • Pop-up menu
  • Static menu
  • Drop-down list
  • Expand, collapse
  • Custom transit
"},{"location":"ui-menu/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-menu/#install-plugin","title":"Install plugin","text":""},{"location":"ui-menu/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add menu object
    var menu = scene.rexUI.add.menu(config);\n
"},{"location":"ui-menu/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add menu object
    var menu = scene.rexUI.add.menu(config);\n
"},{"location":"ui-menu/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Menu } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add menu object
    var menu = new Menu(scene, config);\nscene.add.existing(menu);\n
"},{"location":"ui-menu/#add-menu-object","title":"Add menu object","text":"
var menu = scene.rexUI.add.menu({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n\n// popup: true,\n// orientation: 1,\n// subMenuSide: undefined,\nitems: [],\n\ncreateBackgroundCallback: function(items) {\nvar scene = items.scene;\n// background = ...\nreturn background;\n},\ncreateBackgroundCallbackScope: undefined,\n\ncreateButtonCallback: function(item, index, items) {\nvar scene = item.scene;\n// var isFirstButton = (index === 0);\n// var isLastButton = (index === (items.length - 1));\n// container = ...\nreturn container;\n},\ncreateButtonCallbackScope: undefined,\n\neaseIn: 0,\n// easeIn: {\n//     duration: 500,\n//     orientation: undefined,\n//     ease: 'Cubic'\n// },\ntransitIn: undefined,\n// transitIn: function(menu, duration) {  },\n\neaseOut: 0,\n// easeOut: {\n//     duration: 100,\n//     orientation: undefined,\n//     ease: 'Linear'\n// },\ntransitOut: undefined,\n// transitOut: function(menu, duration) {  },\n\n// expandEvent: 'button.click',\n\n// pointerDownOutsideCollapsing: true,\n\n// childrenKey: 'children',\n\nname: '',\n// draggable: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • popup :
    • true : Pop-up menu, will layout automatically, push inside viewport. Default behavior.
    • false : Static menu, can put into another sizer, won't layout automatically.
  • orientation : Main orientation of the menu, default is 1 (top to bottom)
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Arrange buttons from left ot right.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Arrange buttons from top to bottom.
  • items : Array of item data for each button. Each item has
    • children : An array of items for sub-menu, optional. Can change by childrenKey parameter.
    • Other custom properties
  • createBackgroundCallback : Callback to return container object of menu's bckground.
    • Properties of items parameter
      • items.scene : Scene of this menu object.
  • createButtonCallback : Callback to return container object of each item.
    • Properties of item parameter
      • item.scene : Scene of this menu object.
      • Other custom properties
  • easeIn : Duration of expanding menu.
    • A number : Duration of ease, in milliseconds.
    • An object :
      • easeIn.duration : Duration of ease, in milliseconds.
      • easeIn.ease : Ease function, default is 'Cubic'
      • easeIn.orientation : Orientation of ease.
        • undefined : The same orientation with menu's orientation.
        • 'h', 'x', or 0 : Pop-up menu horizontally.
        • 'v', 'y', or 1 : Pop-up menu vertically.
  • transitIn : Tween behavior of expanding menu.
    • undefined : Expand menu by pop-up, default behavior.
    • Custom callback
      function(menu, duration) {\n\n}\n
  • easeOut : Duration of collapsing menu
    • A number : Duration of ease, in milliseconds.
    • An object :
      • easeOut.duration : Duration of ease, in milliseconds.
      • easeOut.ease : Ease function, default is 'Linear'
      • easeOut.orientation : Orientation of ease.
        • undefined : The same orientation with menu's orientation.
        • 'h', 'x', or 0 : Scale-down menu horizontally.
        • 'v', 'y', or 1 : Scale-down menu vertically.
  • transitOut : Tween behavior of collapsing menu.
    • undefined : Collapse menu by scale-down, default behavior.
    • Custom callback
      function(menu, duration) {\n\n}\n
  • expandEvent : Event name of expanding sub-menu.
    • 'button.click' : Default value
    • 'button.over'
  • pointerDownOutsideCollapsing :
    • true : Collapse all menus (popup:true), or sub-menus (popup:false) when pointer-down outside of all menus. Default behavior.
    • false : Ignore pointer-down outside detection.
  • childrenKey : Key of sub-menu in element of items.
    • children : Default value.
  • subMenuSide : Side of sub-menu
    • undefined : Determine side of sub-menu automatically.
    • 'right', or 0 : Put sub-menu at right side. Used with orientation is set to y.
    • 'left', or 2 : Put sub-menu at left side. Used with orientation is set to y.
    • 'up', or 3 : Put sub-menu at up side. Used with orientation is set to x.
    • 'down', or 1 : Put sub-menu at down side. Used with orientation is set to x.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
"},{"location":"ui-menu/#custom-class","title":"Custom class","text":"
  • Define class
    class MyMenu extends RexPlugins.UI.Menu {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var menu = new MyMenu(scene, config);\n
"},{"location":"ui-menu/#collapse","title":"Collapse","text":"
  • Collapse menu
    menu.collapse();\n
  • Collapse sub-menu
    menu.collapseSubMenu();\n
"},{"location":"ui-menu/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-menu/#events","title":"Events","text":"
  • Click button
    menu.on('button.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Game object of triggered button.
    • index : Index of triggered button.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-over button
    menu.on('button.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Game object of triggered button.
    • index : Index of triggered button.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-out button
    menu.on('button.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Game object of triggered button.
    • index : Index of triggered button.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Expand(Pop-up start) sub-menu
    menu.on('expand', function(subMenu, parentButton) {\n// ....\n}, scope)\n
    • subMenu : Sub-menu.
    • parentButton : Game object of triggered button.
    • rootMenu : Root-menu
  • Pop-up root-menu, or sub-menu completely
    menu.on('popup.complete', function(menu) {\n// ....\n}, scope)\n
    • menu : Root-menu, or sub-menu
  • Collapse(Scale-down starting) root-menu, or sub-menu
    menu.on('collapse', function(subMenu, parentButton, rootMenu) {\n// ....\n}, scope)\n
    • subMenu : Sub-menu.
    • parentButton : Game object of triggered button.
    • rootMenu : Root-menu
  • Scale-down root-menu completely
    menu.on('scaledown.complete', function(rootMenu) {\n// ....\n}, scope)\n
    • rootMenu : Root-menu
"},{"location":"ui-nameinputdialog/","title":"Name input dialog","text":""},{"location":"ui-nameinputdialog/#introduction","title":"Introduction","text":"

Enter first name and last name via a dialog.

  • Author: Rex
  • Game object
"},{"location":"ui-nameinputdialog/#live-demos","title":"Live demos","text":"
  • Horizontal-layout
  • Vertical-layout
"},{"location":"ui-nameinputdialog/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-nameinputdialog/#install-plugin","title":"Install plugin","text":""},{"location":"ui-nameinputdialog/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add dialog object
    var dialog = scene.rexUI.add.nameInputDialog(style).resetDisplayContent(config);\n// var dialog = scene.rexUI.add.nameInputDialog(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-nameinputdialog/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add dialog object
    var dialog = scene.rexUI.add.nameInputDialog(style).resetDisplayContent(config);\n// var dialog = scene.rexUI.add.nameInputDialog(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-nameinputdialog/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { NameInputDialog } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add dialog object
    var dialog = new NameInputDialog(scene, config);\n// var dialog = new NameInputDialog(scene, config, creators);\nscene.add.existing(dialog);\ndialog.resetDisplayContent(config);\n
"},{"location":"ui-nameinputdialog/#add-dialog-object","title":"Add dialog object","text":"
var dialog = scene.rexUI.add.nameInputDialog({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\nbackground: backgroundStyle,\n// background: null,\n\ntitle: titleStyle,  // SimpleLabelConfig\n// title: null,\n\nfirstNameTitle: titleStyle,  // SimpleLabelConfig\n// firstNameTitle: null,\n\nfirstNameInput: inputTextStyle, // CanvasInputTextConfig\n\nlastNameTitle: titleStyle,  // SimpleLabelConfig\n// firstNameTitle: null,\n\nlastNameInput: inputTextStyle, // CanvasInputTextConfig\n\ncontent: contentStyle, // SimpleLabelConfig, or TextAreaStyle\n// content: null,\n\nbutton: SimpleLabelConfig,\n\n// Space\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\ntitle: 0,\ntitleLeft: 0,\ntitleRight: 0,\n\nnames: 0,\nnamesLeft: 0,\nnamesRight: 0,\nfirstName: 0,\nfirstNameTitle: 0,\nlastNamTitle: 0,\n\nactionsLeft: 0,\nactionsRight: 0,\naction: 0,\n},\n\nproportion: {\ntitle: 0,\nactions: 0,\n},\n\nexpand: {\ntitle: true,\nactions: false,\n},\n\nalign: {\ntitle: 'center',\nactions: 'center',\n},\n\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n},\n\nmodal: {\ncover: {\ncolor: 0x0,\nalpha: 0.8,\ntransitIn: function(gameObject, duration) { },\ntransitOut: function(gameObject, duration) { },\n},\n// cover: false, \n\n// When to close modal dialog?\ntouchOutsideClose: false,\nanyTouchClose: false,\ntimeOutClose: false,\nmanualClose: false,\n\nduration: {\nin: 200,\nhold: 2000,\nout: 200\n}\n\ntransitIn: 0,\ntransitOut: 0,\n\ndestroy: true,\n\ndefaultBehavior: true,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n\n// nameInputButtonIndex: 0,\n// cancelButtonIndex: 1,\n\n}, creators);\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as background element.
    • null : Don't create any game object.
  • title, firstNameTitle, lastNameTitle :
    • Styles of simple-label
    • null : Don't create any game object.
  • firstNameInput, lastNameInput :
    • Styles of canvas-input
  • button :
    • Styles of simple-label, optional.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.title : Space between title game object and below game object.
    • space.titleLeft, space.titleRight : Extra left/right padding of title game object.
    • space.names : Space between names and action buttons.
    • space.namesLeft, space.namesRight : Extra left/right padding of names.
    • space.firstName : Space between first name and last name.
    • space.firstNameTitle : Space between firstNameTitle and firstNameInput.
    • space.lastNameTitle : Space between lastNameTitle and lastNameInput.
    • space.action : Space between each action-button game objects.
  • proportion : Keep height of element, or expand height of element.
    • proportion.title : Set to 1 to expand height of title. Default is 0.
    • proportion.actions : Set to 1 to expand height of actions. Default is 0.
  • expand : Expand width of element
    • expand.title : Set true to expand width of title game object. Default is true.
    • expand.actions : Set true to expand width of actions game object. Default is false.
  • align : Align element
    • align.title
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value. Will add Spaces at right and left sides.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center. Will add a Space at right side.
    • align.actions : Align action game objects to 'left'/'center'/'right', if expand.actions is false.
  • click: Configuration of button clicking.
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
  • modal : Configuration of modal, See Modal behavior.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false..
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • nameInputButtonIndex, cancelButtonIndex : Button index for firing 'nameInput', 'cancel' events. Default values are 0, 1.
  • creators : Callbacks for creating components.
    {\nbackground: undefined,\ntitle: undefined,\nfirstNameTitle: undefined,\nlastNameTitle: undefined,\nbutton: undefined,\n}\n
    • creators.background : Callback to create background of dialog. Default behavior is creating a round-rectangle-shape.
      function(scene, config)  {\nreturn gameObject;\n}\n
    • creators.title, creators.firstNameTitle, creators.lastNameTitle, creators.button : Creators of simple-label, included these properties
      {\nbackground: undefined,\ntext: undefined,\nicon: undefined,\naction: undefined,\n}\n
"},{"location":"ui-nameinputdialog/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDialog extends RexPlugins.UI.NameInputDialog {\nconstructor(scene, config, creators) {\nsuper(scene, config, creators);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var dialog = new MyDialog(scene, config, creators);\n
"},{"location":"ui-nameinputdialog/#reset-display-content","title":"Reset display content","text":"
dialog.resetDisplayContent({\ntitle: '',\nfirstNameTitle: '',\nlastNameTitle: '',\nbutton: '',\n\nfirstName: '',\nlastName: '',\n});\n

or

dialog.resetDisplayContent({\ntitle: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nfirstNameTitle: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nlastNameTitle: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nbutton: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nfirstName: '',\n\nlastName: ''\n});\n
  • title, firstNameTitle, lastNameTitle : Display content
    • A string : Set text of simple lable
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
    • null : Hide title or firstNameTitle, lastNameTitle element.
  • button : Display content
    • A string : Set text of simple lable
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
  • firstName, lastNmae : A string

Run dialog.layout() after this method, to layout children again.

"},{"location":"ui-nameinputdialog/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

dialog.layout();\n

See also - dirty

"},{"location":"ui-nameinputdialog/#modal","title":"Modal","text":"

Pop this dialog as modal dialog, close this modal dialog when clicking action button.

dialog.modal(onClose);  // Use default modal config\n

or

dialog.modal({\n// cover: {\n//     color: 0x0,\n//     alpha: 0.8,\n//     transitIn: function(gameObject, duration) { },\n//     transitOut: function(gameObject, duration) { },\n// },\n// cover: false, \n\n// When to close modal dialog?\n// touchOutsideClose: false,\n// anyTouchClose: false,\n// timeOutClose: false,\n// manualClose: false,\n\n// duration: {\n//     in: 200,\n//     hold: 2000,\n//     out: 200\n// }\n\n// transitIn: 0,\n// transitOut: 0,\n\n// destroy: true\n}, onClose);\n

or

dialog\n.modalPromise(config)\n.then(function(data){\nvar firstName = data.firstName;\nvar lastName = data.lastName;\n})\n
  • config : See Modal behavior
    • config.defaultBehavior :
      • undefined, or true : Will close modal dialog when clicking any action button.
      • false : Disable default behavior.
  • onClose : Callback when closing modal dialog
    function(data) {\nvar firstName = data.firstName;\nvar lastName = data.lastName;\n}\n
    • data : Contains these properties
      • data.firstName : Enter string of firstNameInput.
      • data.lastName : Enter string of lastNameInput.
"},{"location":"ui-nameinputdialog/#names-input","title":"Names input","text":"
  • First name
    • Get
      var firstName = dialog.firstName;\n
    • Set
      dialog.setFirstName(value);\n// data.firstName = value;\n
  • Last name
    • Get
      var lastName = dialog.lastName;\n
    • Set
      dialog.setLastName(value);\n// data.lastName = value;\n
"},{"location":"ui-nameinputdialog/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = dialog.getElement('background');\n
    • Title game object
      var title = dialog.getElement('title');\n
    • FirstName-title game object
      var firstNameTitle = dialog.getElement('firstNameTitle');\n
    • FirstName-input game object
      var firstNameInput = dialog.getElement('firstNameInput');\n
    • LastName-title game object
      var lastNameTitle = dialog.getElement('lastNameTitle');\n
    • LastName-input game object
      var lastNameInput = dialog.getElement('lastNameInput');\n
    • Button game object
      var button = dialog.getElement('button');\n
  • Get by name
    var gameObject = dialog.getElement('#' + name);\n// var gameObject = dialog.getElement('#' + name, recursive);\n
    or
    var gameObject = dialog.getByName(name);\n// var gameObject = dialog.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-nameinputdialog/#other-properties","title":"Other properties","text":"

See dialog, sizer object, base sizer object, container-lite.

"},{"location":"ui-nameinputdialog/#events","title":"Events","text":"
  • Click confirm button
    dialog.on('confirm', function (data) {\nvar firstName = data.firstName;\nvar lastName = data.lastName;\n}, scope);\n
    • data : See modal
"},{"location":"ui-namevaluelabel/","title":"Name value label","text":""},{"location":"ui-namevaluelabel/#introduction","title":"Introduction","text":"

A container with name text, value text in a row, with a horizontal line progress bar, and an icon, background.

  • Author: Rex
  • Game object
"},{"location":"ui-namevaluelabel/#live-demos","title":"Live demos","text":"
  • Name-value label
  • Custom bar
"},{"location":"ui-namevaluelabel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-namevaluelabel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-namevaluelabel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add label object
    var label = scene.rexUI.add.nameValueLabel(config);\n
"},{"location":"ui-namevaluelabel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add label object
    var label = scene.rexUI.add.nameValueLabel(config);\n
"},{"location":"ui-namevaluelabel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { NameValueLabel } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add label object
    var label = new NameValueLabel(scene, config);\nscene.add.existing(label);\n
"},{"location":"ui-namevaluelabel/#add-label-object","title":"Add label object","text":"
var label = scene.rexUI.add.nameValueLabel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\nicon: iconGameObject,\niconMask: false,\n\nnameText: nameTextGameObject,\nvalueText: valueTextGameObject,\n// valueTextFormatCallback: function(value, min, max) {\n//     return `${value}/${max}`;\n// },\n// valueTextFormatCallback: null,\n\n// barShape: 'line',   // 'line', or 'circle'\n\n// line bar\nbar: {        trackColor: undefined,\ntrackThickness: 2,\ntrackStrokeColor: undefined,\nbarColor: undefined,\nbarColor2: undefined,\n\nskewX: 0,\n\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'linear'\n},\n}, // circle bar\n/*\n    bar: {\n        barColor: undefined,\n        barColor2: undefined,\n        trackColor: undefined,\n        centerColor: undefined,\n        thickness: 0.2,\n        startAngle: Phaser.Math.DegToRad(270),\n        endAngle: Phaser.Math.DegToRad(270+360),\n        anticlockwise: false,\n    }\n    */\n\n// bar: CustomProgressGameObject,\n\n// bar: undefined,\n\naction: actionGameObject,\nactionMask: false,\n\nalign: {        text: 'bottom',  // 'top', 'center', 'bottom'\n},\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0, iconTop: 0, iconBottom: 0,\nname: 0, value: 0,\nbar:0, barBottom: 0, barLeft: 0, barRight: 0,\ntext: 0,\nactionTop: 0, actionBottom: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • nameText : Game object of nameText.
    • OriginX of nameText will be set to 0.
    • Empty text will be set to a space character ' '. To preserve height of this text game object.
  • valueText : Game object of valueText.
    • OriginX of nameText will be set to 1.
    • Empty text will be set to a space character ' '. To preserve height of this text game object.
  • valueTextFormatCallback : Callback to return a string set to valueText game object when invokeing label.setValue(value, min, max) method.
    • A callback
      function(value, min, max) {\nreturn `${value}/${max}`;\n}\n
    • null, or false : Don't set valueText game object.
  • barShape : 'line' or 'circle'.
  • bar : Game object of bar, or config of horizontal line progress bar, or config of circular progress bar or undefined.
    • Config of horizontal line progress bar
      • bar.trackColor : Fill color of bar's track, in number or css string value.
      • bar.trackStrokeColor : Stroke color of bar's track, in number or css string value.
      • bar.trackThickness : Stroke line width of bar's track.
      • bar.barColor, bar.barColor2 : Fill color of bar, in number or css string value. Assign gradient start color by barColor2.
      • bar.skewX : Horizontal skew of track and bar.
      • bar.rtl :
        • false : Bar starts from left side. Default behavior.
        • true : Bar starts from right side.
    • Config of circular progress bar
      • bar.barColor, bar.barColor2 : Fill color of circular bar, in number or css string value. Assign gradient start color by barColor2.
      • bar.trackColor : Color of circular track, in number or css string value.
      • bar.centerColor : Color of center circle, in number or css string value.
      • bar.thickness : 0 ~ 1, thickness of circular bar. Default value is 0.2 (0.2*radius)
      • bar.startAngle : Start angle of circular bar, in radians. Default value is 270 degrees.
      • bar.endAngle : End angle of circular bar, in radians. Default value is 270+360 degrees.
      • bar.anticlockwise : Set true to put anticlockwise circular bar. Default value is false.
    • (CustomProgress) Game object.
    • undefined : No bar game object.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • align :
    • align.text : Alignment of nameText, valueText game objects.
      • 'top', 'center', or 'bottom'. Default value is 'bottom'.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.icon : Space between icon game object and text game object.
    • space.iconTop, space.iconBottom : Space around icon game object.
    • space.name : Left space of nameText game object.
    • space.value : Right space of valueText game object.
    • space.bar, space.barLeft, space.barRight, space.barBottom : Space around bar game object.
    • space.text : Space between text game object and action icon game object.
    • space.actionTop, space.actionBottom : Space around action game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-namevaluelabel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyNameValueLabel extends RexPlugins.UI.NameValueLabel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var label = new MyNameValueLabel(scene, config);\n
"},{"location":"ui-namevaluelabel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

label.layout();\n

See also - dirty

"},{"location":"ui-namevaluelabel/#name-text","title":"Name text","text":"
  • Get nameText string
    var s = label.nameText;\n
  • Set nameText string
    label.setNameText(s);\n
    or
    label.nameText = s;\n
"},{"location":"ui-namevaluelabel/#value-text","title":"Value text","text":"
  • Get valueText string
    var s = label.valueText;\n
  • Set valueText string
    label.setValueText(s);\n
    or
    label.valueText = s;\n
"},{"location":"ui-namevaluelabel/#bar","title":"Bar","text":"
  • Get bar value
    var s = label.barValue;\n
  • Set bar value
    label.setBarValue(value);  // 0~1\n
    or
    label.setBarValue(value, min, max);  // min~max\n
    or
    label.barValue = t;  // 0~1\n
  • Ease bar value
    label.easeBarValueTo(value);  // 0~1\n
    or
    label.easeBarValueTo(value, min, max);    // min~max\n
"},{"location":"ui-namevaluelabel/#icon-texture","title":"Icon texture","text":"
  • Set texture
    label.setTexture(key);\n// label.setTexture(key, frame);\n
  • Set texture via texture object
    label.setTexture(texture);\n// label.setTexture(texture, frame);\n
  • Get texture, frame.
    var texture = label.texture;\nvar frame = label.frame;\n
  • Get texture key, frame name.
    var textureKey = label.texture.key;\nvar frameName = label.frame.name;\n
"},{"location":"ui-namevaluelabel/#set-value","title":"Set value","text":"
  • Set valueText game object and bar game object.
    label.setValue(value, min, max);\n// label.setValue(value);  // min, max are not changed\n
    or
    label.setValue(value);  // min, max are not changed\n
    Will invoke valueTextFormatCallback callback.
  • Ease valueText game object and bar game object.
    label\n.setEaseValueDuration(duration)\n.easeValueTo(value, min, max);\n
    or
    label\n.setEaseValueDuration(duration)\n.easeValueTo(value);  // min, max are not changed\n
    Will invoke valueTextFormatCallback callback.
  • Get values
    var value = label.value;\nvar max = label.maxValue;\nvar min = label.minValue;\n
    • value will ease during label.easeValueTo() task.
"},{"location":"ui-namevaluelabel/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = label.getElement('background');\n
    • Icon game object
      var icon = label.getElement('icon');\n
    • NameText game object
      var nameTextObject = label.getElement('name');\n
    • ValueText game object
      var valueTextObject = label.getElement('value');\n
    • Bar game object
      var textObject = label.getElement('bar');\n
    • Action icon game object
      var action = label.getElement('action');\n
  • Get by name
    var gameObject = label.getElement('#' + name);\n// var gameObject = label.getElement('#' + name, recursive);\n
    or
    var gameObject = label.getByName(name);\n// var gameObject = label.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-namevaluelabel/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-numberbar/","title":"Number bar","text":""},{"location":"ui-numberbar/#introduction","title":"Introduction","text":"

A container with an icon, slider, text, and background.

  • Author: Rex
  • Game object
"},{"location":"ui-numberbar/#live-demos","title":"Live demos","text":"
  • Number bar
  • Color picker
  • Video player
"},{"location":"ui-numberbar/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-numberbar/#install-plugin","title":"Install plugin","text":""},{"location":"ui-numberbar/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin(\n\"rexuiplugin\",\n\"https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js\",\n\"rexUI\",\n\"rexUI\"\n);\n
  • Add number bar object
    var numberBar = scene.rexUI.add.numberBar(config);\n
"},{"location":"ui-numberbar/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from \"phaser3-rex-plugins/templates/ui/ui-plugin.js\";\nvar config = {\n// ...\nplugins: {\nscene: [\n{\nkey: \"rexUI\",\nplugin: UIPlugin,\nmapping: \"rexUI\",\n},\n// ...\n],\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add number bar object
    var numberBar = scene.rexUI.add.numberBar(config);\n
"},{"location":"ui-numberbar/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { NumberBar } from \"phaser3-rex-plugins/templates/ui/ui-components.js\";\n
  • Add number bar object
    var sizer = new NumberBar(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-numberbar/#add-number-bar-object","title":"Add number bar object","text":"
var numberBar = scene.rexUI.add.numberBar({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\nicon: iconGameObject,\niconMask: false,\nslider: {\nbackground: backgroundGameObject,\n/* \n        background: { \n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\ntrack: trackGameObject,\n/* \n        track: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */    indicator: indicatorGameObject,\n/* \n        indicator: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\nthumb: thumbGameObject,\n/* \n        thumb: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\ninput: 'drag',\ngap: undefined,        easeValue: {\nduration: 0,\nease: 'Linear'\n},\n}\ntext: textGameObject,\n\nvaluechangeCallback: function(newValue, oldValue, numberBar) {\n// numberBar.text = Math.round(Phaser.Math.Linear(0, 100, newValue));\n}\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0,\nslider: 0,\n},\n\nenable: true,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of numberBar.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
  • slider : Slider game object which composed of
    • slider.width : Fixed width of slider, optional. Width of slider will be extended if this value is not set.
    • slider.background :
      • Game object of background, optional. This background game object will be resized to fit the size of slider.
      • A plain object to create round rectangle shape
        { radius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.track :
      • Game object of track, optional. This track game object will be resized to fit the size of slider, with space.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.indicator :
      • Game object of indicator, optional.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.thumb :
      • Game object of thumb, optional.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.input :
      • 'pan', 'drag', or 0 : Control knob by panning/dragging thumb game object. Default setting.
      • 'click', or 1 : Control slider by touching track game object.
      • 'none', or -1 : Disable sider controlling.
    • slider.gap : Snap a value to nearest grid slice, using rounding.
      • undefined : Disable this feature.
    • slider.easeValue : Easing value when input is 'click'.
      • slider.easeValue.duration : Duration of value easing, default is 0 (no easing).
      • slider.easeValue.ease : Ease function, default is 'Linear'.
  • text : Game object of text, optional.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds
    • space.icon : Space between icon game object and text game object.
    • space.slider : Space between slider game object and text game object.
  • valuechangeCallback : callback function when value changed.
  • enable : Set false to disable controlling.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-numberbar/#custom-class","title":"Custom class","text":"
  • Define class
    class MyNumberBar extends RexPlugins.UI.NumberBar {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var numberBar = new MyNumberBar(scene, config);\n
"},{"location":"ui-numberbar/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

numberBar.layout();\n

See also - dirty

"},{"location":"ui-numberbar/#get-element","title":"Get element","text":"
  • Get element
  • Background game object
    var background = numberBar.getElement(\"background\");\n
  • Icon game object
    var icon = numberBar.getElement(\"icon\");\n
  • Slider game object
    • Slider background
      var sliderBackground = numberBar.getElement(\"slider.background\");\n
    • Slider track
      var sliderTrack = numberBar.getElement(\"slider.track\");\n
    • Slider indicator
      var sliderIndicator = numberBar.getElement(\"slider.indicator\");\n
    • Slider thumb
      var sliderThumb = numberBar.getElement(\"slider.thumb\");\n
  • Text game object
    var textObject = numberBar.getElement(\"text\");\n
  • Get by name
    var gameObject = numberBar.getElement(\"#\" + name);\n// var gameObject = numberBar.getElement('#' + name, recursive);\n
    or
    var gameObject = numberBar.getByName(\"#\" + name);\n// var gameObject = numberBar.getByName(name, recursive);\n
  • recursive : Set true to search all children recursively.
"},{"location":"ui-numberbar/#enable","title":"Enable","text":"
  • Get
    var enable = numberBar.enable;\n
  • Set
    numberBar.setEanble(enable);\n
    or
    numberBar.enable = enable;\n
"},{"location":"ui-numberbar/#value","title":"Value","text":"

Change value will also change the position of slider thumb and width of slider indicator.

  • Get value
    var value = numberBar.getValue(min, max); // value : min ~ max\n
    or
    var value = numberBar.getValue(); // value: 0 ~ 1\n
    or
    var value = numberBar.value; // value: 0 ~ 1\n
  • Set value
    numberBar.setValue(value, min, max); // value: min ~ max\n
    or
    numberBar.setValue(value); // value: 0 ~ 1\n
    or
    numberBar.value = value; // value: 0 ~ 1\n
  • Increase value
    numberBar.addValue(inc, min, max); // inc: min ~ max\n
    or
    numberBar.addValue(inc); // inc: 0 ~ 1\n
    or
    numberBar.value += inc; // inc: 0 ~ 1\n
"},{"location":"ui-numberbar/#ease-value","title":"Ease value","text":"
  • Ease value to
    numberBar.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    numberBar.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    numberBar.stopEaseValue();\n
  • Set ease duration
    numberBar.setEaseValueDuration(duration);\n
  • Set ease function
    numberBar.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"ui-numberbar/#text","title":"Text","text":"
  • Get text string
    var s = numberBar.text;\n
  • Set text string
    numberBar.setText(s);\n
    or
    numberBar.text = s;\n
"},{"location":"ui-numberbar/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-numberbar/#events","title":"Events","text":"
  • On value changed
    numberBar.on('valuechange', function (newValue, oldValue, numberBar) {\n// numberBar.text = Math.round(Phaser.Math.Linear(0, 100, newValue));\n}, scope);\n
  • On input start
    numberBar.on('inputstart', function(pointer) {\n\n}, scope);\n
  • On input end
    numberBar.on('inputend', function(pointer) {\n\n}, scope);\n
"},{"location":"ui-overlapsizer/","title":"Overlap sizer","text":""},{"location":"ui-overlapsizer/#introduction","title":"Introduction","text":"

Layout children game objects overlapped.

  • Author: Rex
  • Game object
"},{"location":"ui-overlapsizer/#live-demos","title":"Live demos","text":"
  • Overlap
  • Aspect ratio
  • Fit viewport
"},{"location":"ui-overlapsizer/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-overlapsizer/#install-plugin","title":"Install plugin","text":""},{"location":"ui-overlapsizer/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add sizer object
    var sizer = scene.rexUI.add.overlapSizer(config);\n
"},{"location":"ui-overlapsizer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add sizer object
    var sizer = scene.rexUI.add.overlapSizer(config);\n
"},{"location":"ui-overlapsizer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { OverlapSizer } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add sizer object
    var sizer = new OverlapSizer(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-overlapsizer/#add-sizer-object","title":"Add sizer object","text":"
var sizer = scene.rexUI.add.overlapSizer({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,    \n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n

or

var sizer = scene.rexUI.add.overlapSizer(x, y, {\n// width: undefined,\n// height: undefined,\n// anchor: undefined,    \n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n

or

var sizer = scene.rexUI.add.overlapSizer(x, y, width, height, {\n// anchor: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-overlapsizer/#custom-class","title":"Custom class","text":"
  • Define class
    class MySizer extends RexPlugins.UI.OverlapSizer {\nconstructor(scene, x, y, minWidth, minHeight, config) {\nsuper(scene, x, y, minWidth, minHeight, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var sizer = new MySizer(scene, x, y, minWidth, minHeight, config);\n
"},{"location":"ui-overlapsizer/#add-background","title":"Add background","text":"
sizer.addBackground(child);\n

or

sizer.addBackground(child, {left: 0, right: 0, top: 0, bottom: 0}, key);\n
  • left, right, top, bottom : Extra padded space. Default is 0.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
    • items is a reserved key, which is used to store all children.
"},{"location":"ui-overlapsizer/#add-child","title":"Add child","text":"

Add a game obejct to sizer

sizer.add(child);\n

or

sizer.add(child,\n{\nkey: undefined,\nalign: 'center',     offsetX: 0,\noffsetY: 0,   padding: {left: 0, right: 0, top: 0, bottom: 0},\nexpand: true,        // expand: {width, height}\nminWidth: undefined,\nminHeight: undefined,\naspectRatio: 0,\n}\n);\n

or

sizer.add(child, key, align, padding, expand, minWidth, minHeight, offsetX, offsetY);\n
  • child : A game object.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Use current timestamp as key.
    • items is a reserved key, which is used to store all children.
  • align :
    • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
    • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
    • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game object at top-center.
    • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at bottom-center.
    • 'left-top' , or Phaser.Display.Align.TOP_LEFT : Align game object at left-top.
    • 'left-center' , or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
    • 'left-bottom' , or Phaser.Display.Align.BOTTOM_LEFT : Align game object at left-bottom.
    • 'center-top' , or Phaser.Display.Align.TOP_CENTER : Align game object at center-top.
    • 'center-center' , or Phaser.Display.Align.CENTER : Align game object at center-center.
    • 'center-bottom' , or Phaser.Display.Align.BOTTOM_CENTER : Align game object at center-bottom.
    • 'right-top' , or Phaser.Display.Align.TOP_RIGHT : Align game object at right-top.
    • 'right-center' , or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • 'right-bottom' , or Phaser.Display.Align.BOTTOM_RIGHT : Align game object at right-bottom.
  • offsetX, offsetY : Apply offset to x, y coordinate after alignment.
  • padding : Extra padded space. Default is 0.
    • A number for left/right/top/bottom bounds,
    • Or a plain object.
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • expand :
    • Boolean value
      • true : Expand width and height of child. Default value.
      • false : Don't expand width or height of child.
    • A plain object
      • {width: true} : Only expand width of child.
      • {height: true} : only expand height of child.
      • {width: true, height: true} : Expand width and height of child.
  • minWidth : Minimum width of normal (non-sizer) game object, used when expand width mode. Default value is current display width.
  • minHeight : Minimum height of normal (non-sizer) game object, used when expand height mode. Default value is current display height.
  • aspectRatio : Keep aspect ratio after layout.
    • 0 : Don't keep aspect ratio. Default behavior.
    • true : Keep aspect ratio via current size.
    • A number : Keep aspect ratio via given value.
"},{"location":"ui-overlapsizer/#layout-children","title":"Layout children","text":"

Arrange position of all children.

sizer.layout();\n

See also - dirty

"},{"location":"ui-overlapsizer/#hide","title":"Hide","text":"
  • Set invisible, won't layout it
    sizer.hide();\n
    or
    sizer.hide(gameObject);\n
  • Set visible, will layout it
    sizer.show();\n
    or
    sizer.show(gameObject);\n
"},{"location":"ui-overlapsizer/#remove-child","title":"Remove child","text":"
  • Remove a child
    sizer.remove(child);\n
    or
    sizer.remove(key);\n
  • Remove and destroy a child
    sizer.remove(child, true);\n
    or
    sizer.remove(key, true);\n
  • Remove all children
    sizer.removeAll();\n
  • Remove and destroy all children
    sizer.removeAll(true);\n
  • Remove all children and backgrounds
    sizer.clear();\n
  • Remove and destroy all children and backgrounds
    sizer.clear(true);\n
  • Remove from parent sizer
    sizer.removeFromParentSizer();\n
"},{"location":"ui-overlapsizer/#get-element","title":"Get element","text":"
  • Get element
  • A child
    var item = sizer.getElement(key);\n
    or
    var item = sizer.getElement('items[' + key + ']');\n
    • All children items
      var items = sizer.getElement('items');\n
  • Get by name
    var gameObject = sizer.getElement('#' + name);\n// var gameObject = sizer.getElement('#' + name, recursive);\n
    or
    var gameObject = sizer.getByName(name);\n// var gameObject = sizer.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-overlapsizer/#get-child-index","title":"Get child index","text":"
var index = sizer.getChildIndex(child);\n
  • index : A number, string, or null.
"},{"location":"ui-overlapsizer/#other-properties","title":"Other properties","text":"

See base sizer object, container-lite.

"},{"location":"ui-overview/","title":"Overview","text":""},{"location":"ui-overview/#install-ui-plugins","title":"Install ui plugins","text":""},{"location":"ui-overview/#install-from-minify-file","title":"Install from minify file","text":"
  1. Download minify file (link).
  2. Install ui plugin in preload stage
    scene.load.scenePlugin({\nkey: 'rexuiplugin',\nurl: filePath,\nsceneKey: 'rexUI'\n});\n
    • key : Must be 'rexuiplugin'
"},{"location":"ui-overview/#install-from-npm-package","title":"Install from npm package","text":"
  1. Install rex plugins
    npm i phaser3-rex-plugins\n
  2. Install ui plugin in configuration of game
    import RexUIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\n\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: RexUIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"ui-overview/#using-typescript-declaration-file","title":"Using typescript declaration file","text":"
import 'phaser';\nimport RexUIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\ndeclare module 'phaser' {\ninterface Scene {\nrexUI: RexUIPlugin;\n}\n}\n

or

import RexUIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\n\nclass Game extends Phaser.Scene {\nrexUI: RexUIPlugin;  // Declare scene property 'rexUI' as RexUIPlugin type\n\ncreate() {\nvar sizer = this.rexUI.add.sizer({\n// ...\n})\n}\n}\n\nvar game = new Phaser.Game({\nscene: Game,\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: RexUIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n});\n
  • 'phaser3-rex-plugins/templates/ui/ui-plugin' : Factories of rexUI components.
  • 'phaser3-rex-plugins/templates/ui/ui-components' : Class of rexUI components.
    import { Sizer } from 'phaser3-rex-plugins/templates/ui/ui-components';\n

See this example

"},{"location":"ui-overview/#list-of-ui-plugins","title":"List of ui plugins","text":""},{"location":"ui-overview/#ui-components","title":"UI components","text":"
  1. Badge label: A container with badges above a main item.
  2. Buttons: A container with a group of buttons.
  3. Color componets: Edit color value by RGB, or HSV input fields.
  4. Color input: Color number or color string input field.
  5. Color picker: Pick color value from H and SV palettes.
  6. Confirm action button: Create a modal confirm dialog temporary, invoke callback after clicking button.
  7. Confirm dialog: Using json style to create confirm dialog.
  8. Dialog: A container with a title, content, buttons and background.
  9. Drop down list: A label can open a drop-down list panel.
  10. Exp bar: Disply experience bar on NameValueLabel.
  11. File selector button: A transparent file chooser button above a Label.
  12. Fix-width-buttons: A container with a group of fix-width buttons.
  13. Fix-width-sizer: Layout children game objects into lines.
  14. Folder: A container with a title, foldable child, and background.
  15. Grid-buttons: A container with a group of buttons in grids.
  16. Grid-sizer: Layout children game objects in grids.
  17. Grid-table: A container with a grid table, slider, and scroller.
  18. Holy grail: Layout elements in Holy grail style.
  19. Knob: A knob button based on circular progress.
  20. Label: A container with an icon, text, and background.
  21. Menu: A container with buttons and sub-menu.
  22. Name-input dialog: Enter first name and last name via a dialog.
  23. Name-value label: A container with name text, value text in a row, with a horizontal line progress bar, and an icon, background.
  24. Image input label: A container with a canvas icon, text, and background. Click icon to popup a (image) file chooser dialog, display selected image on canvas.
  25. Number-bar: A container with an icon, slider, text, and background.
  26. Overlap sizer: Layout children game objects overlapped.
  27. Pages: A container with pages, only current page is visible.
  28. Perspective card: A container with front and back faces.
  29. Scroll-able panel: A container with a panel, slider, and scroller.
  30. Simple drop down list: Using plain object to create drop down list.
  31. Simple label: Using json style to create label.
  32. Simple title label: Using json style to create title label.
  33. Simple text box: Using json style to create text box.
  34. Sizer: Layout children game objects.
  35. Slider: A container with a track, indicator, thumb and background.
  36. Split panels: A container with left(top) panel, right(bottom) panel, splitter, and background. Drag splitter to resize with left(top) panel, right(bottom) panel.
  37. Tab-pages: A container with tabs and pages, only current page is visible.
  38. Tabs: A container with 4 groups of buttons around a center panel.
  39. TextArea: A container with a text, slider, and scroller.
  40. TextAreaInput: A container with a canvasInput, and slider.
  41. Textbox: A container with an icon, (typing and paging) text, and background.
  42. Title label: A container with title, text in two rows, and an icon, background.
  43. Toast: Show text message for a short while.
  44. Toast queue: Queue messages for a short while.
  45. Trees: A container with trees and leaf-nodes.
  46. Tweaker: Fine-tuning properties of target object.

Scroll-able table

There are 3 kinds of scroll-able tables :

  • Grid-table only creates visible objects. It is suitable for large table.
  • Grid-sizer adds all objects. Put this grid-sizer into scroll-able panel to have a scroll-able table.
  • Fixwidth-sizer adds all objects. Put this fixwidth-sizer into scroll-able panel to have a scroll-able table.
"},{"location":"ui-overview/#basic-container","title":"Basic container","text":"
  1. ContainerLite: Control the position and angle of children game objects.
    var container = scene.rexUI.add.container(x, y);\n
    or
    class MyContainer extends RexPlugins.UI.Container {\nconstructor(scene, x, y, width, height, children) {\nsuper(scene, x, y, width, height, children);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
"},{"location":"ui-overview/#background-objects","title":"Background objects","text":"
  1. Round-rectangle: Round rectangle shape.
    var shape = scene.rexUI.add.roundRectangle(x, y, width, height, radius, fillColor);\n
    or
    class MyRoundRectangle extends RexPlugins.UI.RoundRectangle {\nconstructor(scene, x, y, width, height, radius, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, radius, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  2. Nine-patch: Stretchable imaage.
    var ninePatch = scene.rexUI.add.ninePatch(x, y, width, height, key, columns, rows, config);\n
    var ninePatch = scene.rexUI.add.ninePatch2(x, y, width, height, key, columns, rows, config);\n
    or
    class MyNinePatch extends RexPlugins.UI.NinePatch {\nconstructor(scene, x, y, width, height, key, columns, rows, config) {\nsuper(scene, x, y, width, height, key, columns, rows, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
    class MyNinePatch extends RexPlugins.UI.NinePatch2 {\nconstructor(scene, x, y, width, height, key, columns, rows, config) {\nsuper(scene, x, y, width, height, key, columns, rows, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  3. Quad shape: Quad shape, offsets can be given on four vertices, and additional points can be added on the four sides.
    var quad = scene.rexUI.add.quadShapes(x, y, width, height, fillColor, fillAlpha);\n
    or
    class MyQuadShape extends RexPlugins.UI.QuadShape {\nconstructor(scene, x, y, width, height, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  4. Custom shapes: Custom shapes on shape.
    var customShapes = scene.rexUI.add.customShapes(x, y, width, height, config);\n
    or
    class MyCustomShapes extends RexPlugins.UI.CustomShapes {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  5. Custom progress: Custom progress on shape.
    var customProgress = scene.rexUI.add.customProgress(x, y, width, height, config);\n
    or
    class MyCustomProgress extends RexPlugins.UI.CustomProgress {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}    
  6. Canvas-round-rectangle: Round rectangle on canvas.
    var shape = scene.rexUI.add.roundRectangleCanvas(x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
    or
    class MyRoundRectangleCanvas extends RexPlugins.UI.RoundRectangleCanvas {\nconstructor(scene, x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient) {\nsuper(scene, x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  7. Cover: Rectangle shape covered full window, and block all touch events.
    var shape = scene.rexUI.add.cover(config);\n
    or
    class MyCover extends RexPlugins.UI.Cover {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
"},{"location":"ui-overview/#canvasshape-objects","title":"Canvas/Shape objects","text":"
  1. Canvas: Drawing on canvas.
    var canvas = scene.rexUI.add.canvas(x, y, width, height);\n// var canvas = scene.rexUI.add.canvas(x, y, width, height);\n
    or
    class MyCanvas extends RexPlugins.UI.Canvas {\nconstructor(scene, x, y, width, height) {\nsuper(scene, x, y, width, height);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  2. Circle mask image: Load a texture, then apply a circle mask.
    var image = scene.rexUI.add.circleMaskImage(x, y, key, frame, config);\n
    or
    class MyImage extends RexPlugins.UI.CircleMaskImage {\nconstructor(scene, x, y, key, frame, config) {\nsuper(scene, x, y, key, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  3. Alpha mask image: Load a texture, then apply an alpha mask from another texture.
    var image = scene.rexUI.add.alphaMaskImage(x, y, key, frame, config);\n
    or
    class MyImage extends RexPlugins.UI.AlphaMaskImage {\nconstructor(scene, x, y, key, frame, config) {\nsuper(scene, x, y, key, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  4. Circular progress shape: Circular progress bar shape.
    var circularProgress = scene.rexUI.add.circularProgress(x, y, radius, barColor, value, config);\n
    or
    class MyCircularProgress extends RexPlugins.UI.CircularProgress {\nconstructor(scene, x, y, radius, barColor, value, config) {\nsuper(scene, x, y, radius, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  5. Circular progress canvas: Circular progress bar on canvas
    var circularProgress = scene.rexUI.add.circularProgressCanvas(x, y, radius, barColor, value, config);\n
    or
    class MyCircularProgress extends RexPlugins.UI.CircularProgressCanvas {\nconstructor(scene, x, y, radius, barColor, value, config) {\nsuper(scene, x, y, radius, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  6. Line progress shape: Horizontal line progress bar shape.
    var lineProgress = scene.rexUI.add.lineProgress(x, y, width, height, barColor, value, config);\n
    or
    class MyLineProgress extends RexPlugins.UI.LinerProgress {\nconstructor(scene, x, y, width, height, barColor, value, config) {\nsuper(scene, x, y, width, height, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  7. Line progress canvas: Horizontal line progress bar filled with gradient color on canvas.
    var lineProgress = scene.rexUI.add.lineProgressCanvas(x, y, width, height, barColor, value, config);\n
    or
    class MyLineProgress extends RexPlugins.UI.LinerProgressCanvas {\nconstructor(scene, x, y, width, height, barColor, value, config) {\nsuper(scene, x, y, width, height, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  8. Checkbox: Checkbox input with drawing checker path animation.
    var checkbox = scene.rexUI.add.checkbox(x, y, width, height, color, config);\n
    or
    class MyCheckbox extends RexPlugins.UI.Checkbox {\nconstructor(scene, x, y, width, height, color, config) {\nsuper(scene, x, y, width, height, color, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  9. Toggle switch: Toggle-switch input.
    var toggleSwitch = scene.rexUI.add.toggleSwitch(x, y, width, height, color, config);\n
    or
    class MyToggleSwitch extends RexPlugins.UI.ToggleSwitch {\nconstructor(scene, x, y, width, height, color, config) {\nsuper(scene, x, y, width, height, color, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  10. Triangle: Trangle shape inside a rectangle bounds.
    var triangle = scene.rexUI.add.triangle(x, y, width, height, fillColor, fillAlpha);\n
    or
    class MyTriangle extends RexPlugins.UI.Triangle {\nconstructor(scene, x, y, width, height, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  11. AIO-spinner
    var spinner = scene.rexUI.add.aioSpinner(config);\n
    or
    class MySpinner extends RexPlugins.UI.AIOSpinner {\nconstructor(scene, configa) {\nsuper(scene, configa);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  12. Chart: Draw chart on canvas.
"},{"location":"ui-overview/#colored-text-objects","title":"Colored text objects","text":"
  1. BBCode text: Drawing text with BBCode protocol.
    var txt = scene.rexUI.add.BBCodeText(x, y, text, style);\n
    or
    class MyText extends RexPlugins.UI.BBCodeText {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  2. Tag text: Displays text with multi-color, font face, or font size with tags.
    var txt = scene.rexUI.add.tagText(x, y, text, style);\n
    or
    class MyText extends RexPlugins.UI.TagText {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  3. Dynamic text: Control position, angle of each character drawn on a canvas.
    var txt = scene.rexUI.add.dynamicText(config);\n
    or
    class MyText extends RexPlugins.UI.DynamicText {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  4. Text player: Typing characters on dynamic text, waiting click or key enter, play sound effect or backgroun music.
    var txt = scene.rexUI.add.textPlayer(config);\n
    or
    class MyText extends RexPlugins.UI.TextPlayer {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  5. Canvas input: An invisible Input DOM element to receive character input and display on DynamicText.
    var txt = scene.rexUI.add.canvasInput(config);\n
    or
    class MyText extends RexPlugins.UI.CanvasInput {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
"},{"location":"ui-overview/#behaviors-of-text","title":"Behaviors of text","text":"
  1. Hidden text edit: Create an invisible Input DOM element to edit string content.
    var hiddenEdit = this.rexUI.add.hiddenEdit(textObject, config);\n
    • textObject : text, bbocodetext, tagtext, or label.
  2. Text edit: Create an input text object above a text object to edit string content.
    scene.rexUI.edit(textObject, config);\n// scene.rexUI.edit(textObject, config, onClose);\n
  3. Wrap-expand text
    var textObject = scene.rexUI.wrapExpandText(textObject);\n// var textObject = scene.rexUI.wrapExpandText(textObject, minWidth);\n
    • textObject :
      • Text object, bbcode text object, tag text object,
      • Bitmap text object
      • Dynamic text object, With default wrap configuration, ex:
        {\nlineHeight: 24,\npadding: {bottom: 12}\n}\n
  4. Font-size-expand text
    var textObject = scene.rexUI.fontSizeExpandText(textObject);    
    or
    var textObject = scene.rexUI.fontSizeExpandText(textObject, {\nfitHeight: true\n});\n
    • textObject :
      • Text object, bbcode text object, tag text object, bitmap text game object
    • fitHeight :
      • false : Set font size to fit width only. Default behavior.
      • true : Set font size to fit width and height.
  5. Set font-size to fit width
    var textObject = scene.rexUI.setFontSizeFitToWidth(textObject, width);\n
    • textObject :
      • Text object, bbcode text object, tag text object, bitmap text game object
  6. Text typing
    var textTyping = scene.rexUI.add.textTyping(textObject, config);\n
  7. Text page
    var textPage = scene.rexUI.add.textPage(textObject, config);\n
"},{"location":"ui-overview/#scaled-image","title":"Scaled image","text":"
  1. Image box: Keep aspect ratio of image game object after scale-down resizing.
    var image = scene.rexUI.add.imageBox(x, y, texture, frame, config);\n
    or
    class MyImageBox extends RexPlugins.UI.ImageBox {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
"},{"location":"ui-overview/#transition-image","title":"Transition image","text":"
  1. Transition image: Transit texture to another one.
    var image = scene.rexUI.add.transitionImage(x, y, texture, frame, config);\n
    or
    class MyTransitionImage extends RexPlugins.UI.TransitionImage {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  2. Transition image pack: Transit texture to another one, with some pre-build effects, extended from TransitionImage.
    var image = scene.rexUI.add.transitionImagePack(x, y, texture, frame, config);\n
    or
    class MyTransitionImagePack extends RexPlugins.UI.TransitionImagePack {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
"},{"location":"ui-overview/#dom-game-objects","title":"Dom game objects","text":"
  1. Input text: Input DOM element.
    var inputText = scene.rexUI.add.inputText(config);\n
    or
    class MyInputText extends RexPlugins.UI.InputText {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  2. File chooser: Create a transparent file chooser button (<input type=\"file\">).
    var fileChooser = scene.rexUI.add.fileChooser(config);\n
    or
    class MyFileChooser extends RexPlugins.UI.FileChooser {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  3. File drop zone: Create a div element for dropping file(s).
    var fileDropZone = scene.rexUI.add.fileDropZone(config);\n
    or
    class MyFileDropZpne extends RexPlugins.UI.FileDropZpne {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
"},{"location":"ui-overview/#layer-manager","title":"Layer manager","text":"

Layer manager : A dictionary to store Layer game objects.

var layerManager = scene.rexUI.add.layerManager({\n// layers: ['layer0', 'layer1', ...]\n});\n\n// layerManager.addToLayer(name, gameObject);\n
"},{"location":"ui-overview/#touch-input","title":"Touch input","text":"
  1. Click: Fires 'click' event when touch releasd after pressed.
    var click = scene.rexUI.add.click(gameObject, config);\n
    or
    var click = new RexPlugins.UI.Click(gameObject, config);\n
  2. Click-Outside: Fires 'clickoutside' event when pointer-down or pointer-up outside of game object.
    var clickOutside = scene.rexUI.add.clickOutside(gameObject, config);\n
    or
    var clickOutside = new RexPlugins.UI.ClickOutside(gameObject, config);\n
  3. In touching: Fires 'intouch' event every tick when pressing on a game object.
    var inTouching = scene.rexUI.add.inTouching(gameObject, config);\n
    or
    var inTouching = new RexPlugins.UI.inTouching(gameObject, config);\n
  4. Tap: Get tap/multi-taps events of a game object.
    var tap = scene.rexUI.add.tap(gameObject, config);\n
    or
    var tap = new RexPlugins.UI.Tap(gameObject, config);\n
  5. Press: Get press events of a game object.
    var press = scene.rexUI.add.press(gameObject, config);\n
    or
    var press = new RexPlugins.UI.Press(gameObject, config);\n
  6. Swipe: Get swipe events of a game object.
    var swipe = scene.rexUI.add.swipe(gameObject, config);\n
    or
    var swipe = new RexPlugins.UI.Swipe(gameObject, config);\n
  7. Pan: Get pan events of a game object.
    var pan = scene.rexUI.add.pan(gameObject, config);\n
    or
    var pan = new RexPlugins.UI.Pan(gameObject, config);\n
  8. Pinch: Get scale factor from 2 dragging touch pointers.
    var pinch = scene.rexUI.add.pinch(config);\n
    or
    var pinch = new RexPlugins.UI.Pinch(config);\n
  9. Rotste: Get spin angle from 2 dragging touch pointers.
    var rotate = scene.rexUI.add.rotate(config);\n
    or
    var rotate = new RexPlugins.UI.Rotate(config);\n
  10. Touch event stop: Stop touch events propagation.
    var touchEventStop = scene.rexUI.add.touchEventStop(gameObject, config);\n
    or
    var touchEventStop = new RexPlugins.UI.TouchEventStop(gameObject, config);\n
"},{"location":"ui-overview/#behaviors","title":"Behaviors","text":"
  1. Confirm action : Create a modal confirm dialog temporary, invoke callback after clicking button.
    scene.rexUI.confirmAction(scene, config)\n.then(function(data){ })\n
  2. Modal promise : Modal behavior wrapped into promise.
    scene.rexUI.modalPromise(gameObject, config)\n.then(function(closeEventData){ })\n
    • Close modal dialog:
      scene.rexUI.modalClose(gameObject);\n// scene.rexUI.modalClose(gameObject, closeEventData);\n
      or
      gameObject.emit('modal.requestClose');\n// gameObject.emit('modal.requestClose', closeEventData);\n
      • Fire 'modal.requestClose' event on game object, which will invoke modal.requestClose() method. After closing dialog, resolve part of promise will be triggered.
  3. Flip: Flip game object to another face by scaling width/height.
    var flip = scene.rexUI.add.flip(gameObject, config);\n
    or
    var flip = new RexPlugins.UI.Flip(gameObject, config);\n
  4. Fade in, fade out destroy
    scene.rexUI.fadeIn(gameObject, duration);\n// scene.rexUI.fadeIn(gameObject, duration, alpha);\n
    scene.rexUI.fadeOutDestroy(gameObject, duration);\n
  5. Ease-move to, ease-move from
    scene.rexUI.easeMoveTo(gameObject, duration, x, y);\n// scene.rexUI.easeMoveTo(gameObject, duration, x, y, ease);\n
    scene.rexUI.easeMoveFrom(gameObject, duration, x, y);\n// scene.rexUI.easeMoveFrom(gameObject, duration, x, y, ease);\n
  6. Shake
    scene.rexUI.shake(gameObject, config);\n
  7. Perspective: Snapshot children of containerlite, to a perspective render texture.
    var perspective = scene.rexUI.add.perspective(gameObject, config);\n
    or
    var perspective = new RexPlugins.UI.Perspective(gameObject, config);\n
  8. Skew: Snapshot children of containerlite, to a skew render texture.
    var skew = scene.rexUI.add.skew(gameObject, config);\n
    or
    var skew = new RexPlugins.UI.Skew(gameObject, config);\n
"},{"location":"ui-overview/#helper-methods","title":"Helper methods","text":""},{"location":"ui-overview/#get-parent","title":"Get parent","text":"
  • Get parent sizer
    var parentSizer = scene.rexUI.getParentSizer(gameObject);\n
    • gameObject : Any game object added to sizer.
  • Get ancestor sizer matched given name
    var parentSizer = scene.rexUI.getParentSizer(gameObject, name);\n
    • gameObject : Any game object added to sizer.
    • name : Name string.
  • Get topmost sizer
    var topmostSizer = scene.rexUI.getTopmostSizer(gameObject);\n
    • gameObject : Any game object added to sizer.
"},{"location":"ui-overview/#remove-from-parent","title":"Remove from parent","text":"
scene.rexUI.removeFromParent(gameObject);\n
"},{"location":"ui-overview/#showhide","title":"Show/hide","text":"
  • Show
    scene.rexUI.show(gameObject);\nscene.rexUI.getTopmostSizer(gameObject).layout();\n
  • Hide
    scene.rexUI.hide(gameObject);\nscene.rexUI.getTopmostSizer(gameObject).layout();\n
  • Is shown
    var isShown = scene.rexUI.isShown(gameObject);\n
"},{"location":"ui-overview/#is-pointer-in-bounds","title":"Is pointer in bounds","text":"
var isInBounds = scene.rexUI.isInTouching(gameObject);\n// var isInBounds = scene.rexUI.isInTouching(gameObject, pointer);\n
"},{"location":"ui-overview/#event-promise","title":"Event promise","text":"
  • Get event promise
    var promise = scene.rexUI.waitEvent(eventEmitter, eventName)\n.then(function() {\n\n})\n
    • eventEmitter : Any kind of event emitter. for example, game object, or tween task, or scene event
  • Get complete event promise
    var promise = scene.rexUI.waitComplete(eventEmitter)\n.then(function() {\n\n})\n
    • eventEmitter : Event emitter which will fire 'complete' event, for example, tween task.
  • Delay time promise
    var promise = scene.rexUI.delayPromise(time)\n.then(function() {\n\n})\n
"},{"location":"ui-overview/#view-port","title":"View port","text":"

View port is a rectangle of current visible area.

var viewport = scene.rexUI.viewport;\n

Which will be changed after resizing

scene.scale.on('resize', function() {\nvar viewport = scene.rexUI.viewport;\n/*\n    sizer\n        .setPosition(viewport.centerX, viewport.centerY)\n        .setMinSize(viewport.width, viewport.height)\n        .layout();\n    */\n});\n
"},{"location":"ui-overview/#demos","title":"Demos","text":"
  • Dialog
    • Yes/No
    • Choice
    • Pop-up
  • Text input
    • Text edit
    • Hidden text edit
    • Canvas input
  • Menu
  • Text-box
  • Text-area
  • Number bar
  • Grid table
  • Tabs
    • Tabs-tables
  • Scroll-able panel
  • Pages
  • Fix-width sizer
  • Chart
  • Video player
  • Anchor
  • Round-rectangle
"},{"location":"ui-pages/","title":"Pages","text":""},{"location":"ui-pages/#introduction","title":"Introduction","text":"

A container with pages, only current page is visible.

  • Author: Rex
  • Game object
"},{"location":"ui-pages/#live-demos","title":"Live demos","text":"
  • Pages
  • Tabpage
"},{"location":"ui-pages/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-pages/#install-plugin","title":"Install plugin","text":""},{"location":"ui-pages/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add pages object
    var pages = scene.rexUI.add.pages(config);\n
"},{"location":"ui-pages/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add pages object
    var pages = scene.rexUI.add.pages(config);\n
"},{"location":"ui-pages/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Pages } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add pages object
    var pages = new Pages(scene, config);\nscene.add.existing(pages);\n
"},{"location":"ui-pages/#add-pages-object","title":"Add pages object","text":"
var pages = scene.rexUI.add.pages({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0 },\n// swapMode: 0,\n// fadeIn: 0,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
  • swapMode : Set to invisible or destroy swapped page.
    • 0, 'invisible' : Set swapped page to invisible.
    • 1, 'destroy' : Destroy swapped page.
  • fadeIn : Fade-in duration of current page.
    • 0 : No fade-in effect. Default behavior.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-pages/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPages extends RexPlugins.UI.Pages {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var pages = new MyPages(scene, config);\n
"},{"location":"ui-pages/#add-background","title":"Add background","text":"
pages.addBackground(child);\n

or

pages.addBackground(child, {left: 0, right: 0, top: 0, bottom: 0}, key);\n
  • left, right, top, bottom : Extra padded space. Default is 0.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
"},{"location":"ui-pages/#add-page","title":"Add page","text":"
pages.addPage(child, key, align, padding, expand);\n// pages.add(child, key, align, padding, expand);\n

or

pages.addPage(child, {\nkey: 0,\nalign: Phaser.Display.Align.TOP_LEFT,\npadding: {left: 0, right: 0, top: 0, bottom: 0}, expand: true\n}\n);\n// pages.add(child, config);\n
  • child : A game object.
  • key : Unique name of this page.
  • align :
    • 'left-top', or Phaser.Display.Align.TOP_LEFT : Align game object at left-top. Default value.
    • 'left-center', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
    • 'left-bottom', or Phaser.Display.Align.LEFT_BOTTOM : Align game object at left-bottom.
    • 'center-top', or Phaser.Display.Align.TOP_CENTER : Align game object at center-top.
    • 'center-center', or Phaser.Display.Align.CENTER : Align game object at center-center.
    • 'center-bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at center-bottom.
    • 'right-top', or Phaser.Display.Align.TOP_RIGHT : Align game object at right-top.
    • 'right-center', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • 'right-bottom', or Phaser.Display.Align.RIGHT_BOTTOM : Align game object at right-bottom.
  • padding : Add space between bounds. Default is 0.
    • A number for left/right/top/bottom bounds,
    • Or a plain object.
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • expand : Expand width and height of the page.
    • true : Expand width and height.
    • false : Don't expand width or height.
    • A plain object, to expand width or height
      {\nwidth: true,\nheight: true\n}\n
      • expand.width : Expand width.
      • expand.height : Expand height.
"},{"location":"ui-pages/#swap-to-page","title":"Swap to page","text":"
pages.swapPage(key);\n// pages.swapPage(key, fadeInDuration);\n
  • key : Unique name of this page.

Note

This method will run pages.layout() to arrange position of current page.

"},{"location":"ui-pages/#page-name","title":"Page name","text":"
  • Current page name

    var pageName = pages.currentKey;\n

  • Previous page name

    var pageName = pages.previousKey;\n

  • Name of all pages
    var names = pages.keys;\n
"},{"location":"ui-pages/#page-object","title":"Page object","text":"
  • Get page object
    var pageObject = pages.getPage(key);\n
    • pageObject : A game object or null.
  • Current page object
    var pageObject = pages.currentPage;\n
  • Previous page object
    var pageObject = pages.previousPage;\n
"},{"location":"ui-pages/#fade-in-duration","title":"Fade in duration","text":"
pages.setFadeInDuration(duration);\n
  • 0 : No fade-in effect.
"},{"location":"ui-pages/#get-element","title":"Get element","text":"
  • Get element
    • All page game objects
      var gameObjects = pages.getElement('items');\n
  • Get by name
    var gameObject = pages.getElement('#' + name);\n// var gameObject = pages.getElement('#' + name, recursive);\n
    or
    var gameObject = pages.getByName(name);\n// var gameObject = pages.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-pages/#other-properties","title":"Other properties","text":"

See base sizer object, container-lite.

"},{"location":"ui-pages/#events","title":"Events","text":"
  • Set page invisible, triggered when page is swapped out.
    pages.on('pageinvisible', function(pageObject, key, pages) {\n// ...\n}, scope);\n
    • pageObject : Game object of page.
    • key : Page name.
    • pages : Pages object
  • Set page visible, triggered when page is shown.
    pages.on('pagevisible', function(pageObject, key, pages) {\n// ...\n}, scope);\n
    • pageObject : Game object of page.
    • key : Page name.
    • pages : Pages object
"},{"location":"ui-perspectivecard/","title":"Perspective card","text":""},{"location":"ui-perspectivecard/#introduction","title":"Introduction","text":"

A container with front and back faces.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"ui-perspectivecard/#live-demos","title":"Live demos","text":"
  • Flip
  • Rotation
"},{"location":"ui-perspectivecard/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-perspectivecard/#install-plugin","title":"Install plugin","text":""},{"location":"ui-perspectivecard/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add card object
    var card = scene.rexUI.add.perspectiveCard(config);\n
"},{"location":"ui-perspectivecard/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add card object
    var card = scene.rexUI.add.perspectiveCard(config);\n
"},{"location":"ui-perspectivecard/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveCard } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add card object
    var card = new PerspectiveCard(scene, config);\nscene.add.existing(card);\n
"},{"location":"ui-perspectivecard/#add-card-object","title":"Add card object","text":"
var sizer = scene.rexUI.add.perspectiveCard({    // x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nback: backGameObject,\nfront: frontGameObject,\n// face: 0,\n// orientation: 0,\n// snapshotPadding: 0,\n\n// flip : {\n//     frontToBack: 0,\n//     backToFront: 1,\n//     duration: 1000,\n//     ease: 'Cubic',\n//     delay: 0,\n// }\n\n// space: { left: 0, right:0, top:0, bottom:0 },\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • front, back : Any game object for front or back face.
  • face : Show front or back face.
    • 'front', or 0 : Show front face.
    • 'back', or 1 : Show back face.
  • orientation : Flipping orientation.
    • 'horizontal','h', 'x', or 0 : Flipping left-to-right, or right-to-left.
    • 'vertical','v', 'y', or 1 : Flipping top-to-bottom, or bottom-to-top.
  • snapshotPadding : Padding around face when taking a snapshot of a face.
  • flip : Configuration of flipping behavior.
    • flip.frontToBack, flip.backToFront : Flipping direction.
      • 'right', 'left-to-right', or 0 : Flipping from right to left.
      • 'left', 'right-to-left', or 1 : Flipping from left to right.
    • flip.duration : Duration of flipping, in millisecond.
    • flip.delay : Initial delay.
    • flip.ease : Ease function. Default value is 'Cubic'.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-perspectivecard/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveCard extends PerspectiveCard {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var card = new MyPerspectiveCard(scene, config);\n
"},{"location":"ui-perspectivecard/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

card.layout();\n

See also - dirty

"},{"location":"ui-perspectivecard/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = card.getElement('background');\n
    • Front face game object
      var frontFace = card.getElement('front');\n
    • Back face game object
      var backFace = card.getElement('back');\n
  • Get by name
    var gameObject = card.getElement('#' + name);\n// var gameObject = card.getElement('#' + name, recursive);\n
    or
    var gameObject = card.getByName(name);\n// var gameObject = card.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-perspectivecard/#face","title":"Face","text":"
  • Get
    var face = card.face;\n
    • face:
      • 0 : Show front face.
      • 1 : Show back face.
  • Set
    card.setFace(face)\n
    • face
      • 'front', or 0 : Show front face.
      • 'back', or 1 : Show back face.
  • Toggle
    card.toggleFace()\n
"},{"location":"ui-perspectivecard/#face-instances","title":"Face instances","text":"
  • Front face
    var frontFace = card.frontFace;\n// var frontFace = card.faces.front;\n
  • Back face
    var backFace = card.backFace;\n// var backFace = card.faces.back;\n
"},{"location":"ui-perspectivecard/#flip-behavior","title":"Flip behavior","text":""},{"location":"ui-perspectivecard/#start-flipping","title":"Start flipping","text":"
card.flip.flip();\n// card.flip.flip(duration, repeat);\n
  • duration : Overwrite default duration value.
  • repeat : Number of flipping time (repeat + 1) during duration. Default value is 0.

or

  • Flip-right
    card.flip.flipRight();\n// card.flip.flipRight(duration, repeat);\n
  • Flip-left
    card.flip.flipLeft();\n// card.flip.flipLeft(duration, repeat);\n

Note

  • When flipping start:
    • Snapshot face game objects to perspective-card mesh
    • Set face game objects to invisible, and perspective-card mesh to visible
  • When flipping complete:
    • Revert visible of Face game objects and perspective-card mesh
"},{"location":"ui-perspectivecard/#stop-flipping","title":"Stop flipping","text":"
card.flip.stop();\n
"},{"location":"ui-perspectivecard/#set-duration","title":"Set duration","text":"
card.flip.setDuration(duration);\n// card.flip.duration = duration;\n
"},{"location":"ui-perspectivecard/#set-ease","title":"Set ease","text":"
card.flip.setEase(ease);\n// card.flip.ease = ease;\n
"},{"location":"ui-perspectivecard/#events","title":"Events","text":"
  • On flipping start
    card.flip.on('start', function(){\n// ...\n});\n
  • On flipping complete
    card.flip.on('complete', function(){\n// ...\n});\n
"},{"location":"ui-perspectivecard/#status","title":"Status","text":"
  • Is flipping
    var isRunning = card.flip.isRunning;\n
"},{"location":"ui-perspectivecard/#rotation","title":"Rotation","text":"
  • Get rotation angle
    var angleX = card.angleX; // Angle in degrees\nvar angleY = card.angleY; // Angle in degrees\nvar angleZ = card.angleZ; // Angle in degrees\n
    or
    var rotationX = card.rotationX; // Angle in radians\nvar rotationY = card.rotationY; // Angle in radians\nvar rotationZ = card.rotationZ; // Angle in radians\n
  • Set rotation angle
    card.angleX = angleX; // Angle in degrees\ncard.angleY = angleY; // Angle in degrees\ncard.angleZ = angleZ; // Angle in degrees\n
    or
    card.rotationX = rotationX; // Angle in radians\ncard.rotationY = rotationY; // Angle in radians\ncard.rotationZ = rotationZ; // Angle in radians\n

Warning

Can't be used with flipping mode.

"},{"location":"ui-perspectivecard/#other-properties","title":"Other properties","text":"

See overlapSizer.

"},{"location":"ui-scrollablepanel/","title":"Scroll-able panel","text":""},{"location":"ui-scrollablepanel/#introduction","title":"Introduction","text":"

A container with a panel, slider, and scroller.

  • Author: Rex
  • Game object
"},{"location":"ui-scrollablepanel/#live-demos","title":"Live demos","text":"
  • Scroll-able panel + grid sizer
  • Scroll-able panel + table by fix-width sizer
  • Scroll-able panel + fix-width sizer
  • Scroll-able panel + built-in container
    • Container panel
    • Container child
  • Button click
  • Dropdown, scrollable list
  • Add child
  • Scroll to child
  • Drag item
  • Destroy
  • XY sliders
  • Min-width panel
  • Drag, resize panel
    • Single scroller
    • ScrollerX, scrollerY
  • Drag&drop items between panels :
    • With scroller
    • Without scroller
  • Nested scroll-able panel
  • Typing on Label
"},{"location":"ui-scrollablepanel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-scrollablepanel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-scrollablepanel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add scrollable-panel object
    var panel = scene.rexUI.add.scrollablePanel(config);\n
"},{"location":"ui-scrollablepanel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add scrollable-panel object
    var panel = scene.rexUI.add.scrollablePanel(config);\n
"},{"location":"ui-scrollablepanel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ScrollablePanel } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add scrollable-panel object
    var panel = new ScrollablePanel(scene, config);\nscene.add.existing(panel);\n
"},{"location":"ui-scrollablepanel/#add-scroll-able-panel-object","title":"Add scroll-able panel object","text":"
var panel = scene.rexUI.add.scrollablePanel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// scrollMode: 0,\n\n// Elements\nbackground: backgroundGameObject,\n\npanel: {\nchild: panelGameObject,\nmask: {\npadding: 0, // or {left, right, top, bottom}\n// updateMode: 0,\n}\n}.\n\nslider: {\n// background: sliderBackgroundGameObject,\ntrack: trackGameObject,\n/* \n        track: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\nthumb: thumbGameObject,\n/* \n        thumb: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\n// input: 'drag',\n// position: 'right',\n\n// hideUnscrollableSlider: false,\n// adaptThumbSize: false,\n// minThumbSize: undefined,\n\n// buttons: {\n//     top: topButtonGameObject, \n//     bottom: bottomButtonGameObject,\n//     left: leftButtonGameObject, \n//     right: rightButtonGameObject,\n//     step: 0.01,\n// }\n},\n\n// sliderX: {...},\n// sliderY: {...},\n\n// scrollDetectionMode: 0,\n\n// scroller: {\n//     threshold: 10,\n//     slidingDeceleration: 5000,\n//     backDeceleration: 2000,\n//     pointerOutRelease: true,\n//     rectBoundsInteractive: true,\n//     dragRate: 1,\n// },\n\n// scrollerX: {...},\n// scrollerY: {...},\n\nmouseWheelScroller: false,\n// mouseWheelScroller: {\n//     focus: true,\n//     speed: 0.1\n// },\n\n// mouseWheelScrollerX: {...},\n// mouseWheelScrollerY: {...},\n\nclampChildOY: false,\n// clampChildOX: false,\n\nheader: headerGameObject,\nfooter: footerGameObject,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\npanel: 0,\n// panel: {\n//    top: 0,\n//    bottom: 0,\n//    left: 0,\n//    right: 0,\n//},\n\nslider: 0,\n// slider: {\n//     top: 0,\n//     bottom: 0,\n//     left: 0,\n//     right: 0,\n// },\n// sliderX: 0,\n// sliderY: 0,\n\nheader: 0,\nfooter: 0,\n},\n\nexpand: {\nheader: true,\nfooter: true,\npanel: true,\n},\n\nalign: {\nheader: 'center',\nfooter: 'center',\npanel: 'center',\n},\n\n// name: '',\n// draggable: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • scrollMode : Scroll panel vertically, or horizontally.
    • 0, 'vertical', or 'v', 'y' : Scroll panel vertically. Default value.
    • 1, 'horizontal', or 'h'. 'x' : Scroll panel horizontally.
    • 2, or 'xy' : Two-sliders mode, scroll panel vertically and horizontally.
  • background : Game object of background, optional. This background game object will be resized to fit the size of scroll-able panel.
  • panel : Configuration of panel game object.
    • panel.child : Panel game object.
    • panel.mask : Configuration of panel's mask.
      • panel.mask.padding :
        • A number : Extra left/right/top/bottom padding spacing of this rectangle mask. Default value is 0.
        • A plain object {left, right, top, bottom}
      • panel.mask.updateMode : When to update mask
        • 0, or 'update' : Apply mask only when scrolling. Default behavior.
        • 1, or 'everyTick' : Apply mask every tick. Use this mode if children game objects of panel are moved after scrolling and still been masked.
      • false : No mask
  • slider : Componments of slider, optional.
    • slider.background :
      • Game object of background, optional. This background game object will be resized to fit the size of slider.
      • A plain object to create round rectangle shape
        { radius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.track :
      • Game object of track, optional. This track game object will be resized to fit the size of slider, with space.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.indicator :
      • Game object of indicator, optional.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.thumb :
      • Game object of thumb, optional.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.input :
      • 'pan', 'drag', or 0 : Control slider by panning/dragging thumb game object. Default setting.
      • 'click', or 1 : Control slider by touching track game object.
      • 'none', or -1 : Disable sider controlling.
    • slider.position : Position of this slider.
      • 0, 'right', 'bottom' : Slider at right/bottom side. Default value.
      • 1, 'left', 'top' : Slider at left/top side.
    • slider.hideUnscrollableSlider :
      • false : Slider is always visible no matter it is scrollable or not. Default behavior.
      • true : Set slider to invisible if it is unscrollable.
    • slider.adaptThumbSize :
      • false : Don't adjust height/width of thumb. Default behavior.
      • true : Adjust height/width of thumb according to ratio of visible child.
        • Minimum height/width of thumb = slider.minThumbSize. If content is larger then a page.
        • Maximum height/width of thumb = height/width of slider.track. If content is less then a page.
    • slider.minThumbSize : Minimum height/width of thumb used in slider.adaptThumbSize mode.
    • slider.buttons : Press button to scroll content in each tick.
      • slider.buttons.top, slider.buttons.bottom : Top and bottom buttons.
      • slider.buttons.left, slider.buttons.right : Left and right buttons
      • slider.buttons.step : Scrolling step in each tick. Default value is 0.01.
    • Set to false to skip creating slider.
  • sliderX, sliderY : Componments of sliderX and sliderY, for two-sliders mode.
  • scrollDetectionMode :
    • 0 : Dectct drag-scrolling, mouse-wheel-scrolling by game object's touch event. Default behavior.
    • 1 : Dectct drag-scrolling, mouse-wheel-scrolling by rectangle bounds.
  • scroller : Configuration of scroller behavior.
    • scroller.threshold : Minimal movement to scroll. Set 0 to scroll immediately.
    • scroller.slidingDeceleration : Deceleration of slow down when dragging released.
      • Set false to disable it.
    • scroller.backDeceleration : Deceleration of pull back when out of bounds.
      • Set false to disable it.
    • scroller.pointerOutRelease : Set to true to release input control when pointer out of gameObject.
    • scroller.rectBoundsInteractive :
      • false : Detect scrolling by game object's touch input.
      • true : Detect scrolling by rectangle bounds of game object. Default behavior.
    • scroller.dragRate : Rate of dragging distance/dragging speed. Default value is 1.
    • Set to false to skip creating scroller.
  • scrollerX, scrollerY : Configuration of scrollerX, scrollerY behavior, for two-sliders mode.
  • mouseWheelScroller : Configuration of mouse-wheel-scroller behavior.
    • mouseWheelScroller.focus :
      • false, or 0 : Without checking if cursor is over game object or not.
      • true, or 1 : Cursor is inside the rectangle bounds of game object. Default behavior.
      • 2 : Cursor is over game object.
    • mouseWheelScroller.speed : Scrolling speed, default value is 0.1.
    • Set to false to skip creating mouse-wheel-scroller. Default behavior.
  • mouseWheelScrollerX, mouseWheelScrollerY : Configuration of mouse-wheel-scrollerX, or mouse-wheel-scrollerY behavior, for two-sliders mode.
  • clampChildOY : Set true to clamp scrolling.
  • clampChildOX : Set true to clamp scrolling, for two-sliders mode.
  • header : Game object of header, optional.
  • footer : Game object of footer, optional.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.panel :
      • A number: Space between panel object and slider object.
      • An object: Padding of panel object.
        • If scrollMode is 0 (vertical) :
          • space.panel.top, space.panel.bottom : Top, bottom padding space of panel object.
          • space.panel.right : Space between panel object and slider object.
        • If scrollMode is 1 (horizontal) :
          • space.panel.left, space.panel.right : Left, right padding space of panel object.
          • space.panel.bottom : Space between panel object and slider object.
        • If two-sliders mode (scrollMode is 2):
          • space.panel.top, space.panel.bottom, space.panel.left, space.panel.right : Top, bottom, left, right padding space of panel object.
    • space.slider :
      • 0 : No space around slider.
      • space.slider.left, space.slider.right, space.slider.top, space.slider.bottom : Space around slider.
    • space.sliderX, space.sliderX : Space configuration of sliderX, sliderX, for two-sliders mode.
      • 0 : No space around slider.
    • space.header : Space between header and panel.
    • space.footer : Space between footer and panel.
  • expand : Expand width or height of element
    • expand.header : Set true to expand width or height of header game object. Default value is true.
    • expand.footer : Set true to expand width or height of footer game object. Default value is true.
    • expand.panel : Set true to expand width or height of panel game object. Default value is true.
  • align : Align element
    • align.header
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
      • 'top', or Phaser.Display.Align.ALIGN.TOP_CENTER : Align game object at top-center.
      • 'bottom', or Phaser.Display.Align.ALIGN.BOTTOM_CENTER : Align game object at bottom-center.
    • align.footer
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
      • 'top', or Phaser.Display.Align.ALIGN.TOP_CENTER : Align game object at top-center.
      • 'bottom', or Phaser.Display.Align.ALIGN.BOTTOM_CENTER : Align game object at bottom-center.
    • align.panel
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
      • 'top', or Phaser.Display.Align.ALIGN.TOP_CENTER : Align game object at top-center.
      • 'bottom', or Phaser.Display.Align.ALIGN.BOTTOM_CENTER : Align game object at bottom-center.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
"},{"location":"ui-scrollablepanel/#scroll-mode","title":"Scroll mode","text":"

If scrollMode parameter is not given :

  • Set scrollMode to 2, if configuration has sliderX, sliderY, or scrollerX, scrollerY parameters.
  • Set scrollMode to 0, if configuration has sliderY, or scrollerY parameters.
  • Set scrollMode to 1, if configuration has sliderX, or scrollerX parameters.
"},{"location":"ui-scrollablepanel/#child-bounds","title":"Child bounds","text":"

Scrollable panel will mask child if child's bounds (child.getBounds()) is across mask area.

Bitmaptext game object does not have getBounds method. User can inject it by

const Components = Phaser.GameObjects.Components;\nPhaser.Class.mixin(\nPhaser.GameObjects.BitmapText,\n[\nComponents.ComputedSize,\nComponents.GetBounds\n]\n);\n
"},{"location":"ui-scrollablepanel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPanel extends RexPlugins.UI.ScrollablePanel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var panel = new MyPanel(scene, config);\n
"},{"location":"ui-scrollablepanel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

panel.layout();\n

See also - dirty

"},{"location":"ui-scrollablepanel/#scroll-content","title":"Scroll content","text":"
  • Set
    panel.childOY = oy;\n// panel.setChildOY(oy);\n
  • Set and clamp
    panel.setChildOY(oy, true);\n
  • Add
    panel.addChildOY(oy);\n
  • Add and clamp
    panel.addChildOY(oy, true);\n
  • Get
    var childOY = panel.childOY;\n
  • Top OY
    var topOY = panel.topChildOY;\n
  • Bottom OY
    var bottomOY = panel.bottomChildOY;\n
  • Is overflow (height of content is larger than display height)
    var isOverflow = panel.isOverflow;\n
"},{"location":"ui-scrollablepanel/#scroll-by-percentage","title":"Scroll by percentage","text":"
  • Set
    panel.t = t;  // t: 0~1\n// panel.setT(t);  \n
  • Set and clamp
    panel.setT(t, true);\n
  • Get
    var t = panel.t;\n
"},{"location":"ui-scrollablepanel/#scroll-to-topbottom","title":"Scroll to top/bottom","text":"
  • Scroll to top
    panel.scrollToTop();\n
    • Equal to panel.t = 0;
  • Scroll to bottom
    panel.scrollToBottom();\n
    • Equal to panel.t = 1;
"},{"location":"ui-scrollablepanel/#scroll-to-child","title":"Scroll to child","text":"
panel.scrollToChild(child, align);\n
  • align :
    • undefined : Align child to top(left), or bottom(right) of panel. Default value.
    • 'top', 'center', 'bottom' : Align child to top/center/bottom of panel.
    • 'left', 'center', 'right' : Align child to left/center/right of panel.
"},{"location":"ui-scrollablepanel/#enabledisable-scrolling","title":"Enable/disable scrolling","text":"
  • Slider
    • Set enable state
      panel.setSliderEnable(enabled);\n
      or
      panel.sliderEnable = enabled;\n
    • Get enable state
      var enable = panel.sliderEnable;\n
  • Scroller
    • Set enable state
      panel.setScrollerEnable(enabled);\n
      or
      panel.scrollerEnable = enabled;\n
    • Get enable state
      var enable = panel.scrollerEnable;\n
  • Mouse-Wheel-Scroller
    • Set enable state
      panel.setMouseWheelScrollerEnable(enabled);\n
      or
      panel.mouseWheelScrollerEnable = enabled;\n
    • Get enable state
      var enable = panel.mouseWheelScrollerEnable;\n
"},{"location":"ui-scrollablepanel/#event","title":"Event","text":"
  • Scroll
    panel.on('scroll', function(panel) {\n// ...\n})\n
  • Slider
    • Slider drag start
      panel.getElement('slider').on('inputstart', function(panel) {\n// ...\n})\n
    • Slider drag end
      panel.getElement('slider').on('inputend', function(panel) {\n// ...\n})\n
  • Scroller
    • Scroller drag start
      panel.getElement('scroller').on('dragstart', function(panel) {\n// ...\n})\n
    • Scroller drag end
      panel.getElement('scroller').on('dragend', function(panel) {\n// ...\n})\n
"},{"location":"ui-scrollablepanel/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-scrollablepanel/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = panel.getElement('background');\n
    • Child-panel game object
      var childPanel = panel.getElement('panel');\n
    • Child-panel mask game object, which is a graphics game object.
      var maskGameObject = panel.getElement('mask');\n
    • Layer of panel, assigned at config panel.mask.layer.
      var layer = panel.getElement('panelLayer');\n
    • Header game object
      var childPanel = panel.getElement('header');\n
    • Footer game object
      var childPanel = panel.getElement('footer');\n
    • Slider
      • Slider top
        var slider = panel.getElement('slider');\n
      • Track
        var track = panel.getElement('slider.track');\n
      • Thumb
        var thumb = panel.getElement('slider.thumb');\n
    • Scroller
      var scroller = panel.getElement('scroller');\n
    • Scrollable-block, registering scroller and children-interactive on it.
      var scrollableBlock = panel.getElement('scrollableBlock');\n
  • Get by name
    var gameObject = panel.getElement('#' + name);\n// var gameObject = panel.getElement('#' + name, recursive);\n
    or
    var gameObject = panel.getByName(name);\n// var gameObject = panel.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-scrollablepanel/#input-events","title":"Input events","text":"

Two possible solution to register input events to children of scrollable panel.

"},{"location":"ui-scrollablepanel/#individual-input-events","title":"Individual input events","text":"

When scene.input.topOnly is true (default value), input events of children elements will block the drag-scrolling of scrollable panel. (Assmue that the children elememts are above scrollable panel)

  • Set scene.input.topOnly to false to enable drag-scrolling and input events of children elememts both.
    • Or Set scrollDetectionMode: 1 in config of constructor, to using rectangle-bounds input detection.
  • Test if pointer is inside the mask of panel via panel.isInTouching('mask'), during input events' callback.
  • To recognize pointer-down and dragging-start, use press's pressstart event.
"},{"location":"ui-scrollablepanel/#set-children-interactive","title":"Set children interactive","text":"

Applies click, tap, press, swipe behaviors on this scrollable panel, to detect input events of children.

panel.setChildrenInteractive({\n// targetMode: 'parent',\ntargets: targetSizers,\n\n// dropZone: false,\n\n// click: {mode: 'release', clickInterval: 100},\n\n// over: undefined,\n\n// press: {time: 251, threshold: 9},\n\n// tap: {time: 250, tapInterval: 200, threshold: 9, tapOffset: 10, \n//       taps: undefined, minTaps: undefined, maxTaps: undefined,},\n\n// swipe: {threshold: 10, velocityThreshold: 1000, dir: '8dir'},\n\n// inputEventPrefix: 'child.',\n})\n
  • targetMode :
    • 'parent' : targetSizers is an array of hit-targrts' parentSizers. Will run hit-test on parentSizers first, then run hit-test on children of parentSizer. Default behavior.
    • 'direct' : targetSizers is an array of hit-targrts. Will run hit-test directly on these hit-targrts.
  • targetSizers : Array of hit-targrts' parentSizers, or array of hit-targrts. See targetMode parameter.
  • dropZone :
    • true : Enable drop Zone on scrollable area.
    • false : Do nothing.

See Base-sizer/Set children interactive

"},{"location":"ui-scrollablepanel/#events","title":"Events","text":"

See Base-sizer/Set children interactive/Events

"},{"location":"ui-scrollablepanel/#steps-of-building-a-scrollable-panel","title":"Steps of building a scrollable panel","text":"
  1. Build child panel from bottom to top
    • Child panel might be composed of sizers (sizer/fix-width sizer/grid sizer)
    • Return child sizer from method
  2. Build scrollable panel
  3. Add interactive events
"},{"location":"ui-scrollbar/","title":"Scroll bar","text":""},{"location":"ui-scrollbar/#introduction","title":"Introduction","text":"

A container with slider, two buttons, and background.

  • Author: Rex
  • Game object
"},{"location":"ui-scrollbar/#live-demos","title":"Live demos","text":"
  • Scroll bar
"},{"location":"ui-scrollbar/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-scrollbar/#install-plugin","title":"Install plugin","text":""},{"location":"ui-scrollbar/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin(\n\"rexuiplugin\",\n\"https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js\",\n\"rexUI\",\n\"rexUI\"\n);\n
  • Add scroll bar object
    var scrollBar = scene.rexUI.add.scrollBar(config);\n
"},{"location":"ui-scrollbar/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from \"phaser3-rex-plugins/templates/ui/ui-plugin.js\";\nvar config = {\n// ...\nplugins: {\nscene: [\n{\nkey: \"rexUI\",\nplugin: UIPlugin,\nmapping: \"rexUI\",\n},\n// ...\n],\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add scroll bar object
    var scrollBar = scene.rexUI.add.scrollBar(config);\n
"},{"location":"ui-scrollbar/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ScrollBar } from \"phaser3-rex-plugins/templates/ui/ui-components.js\";\n
  • Add scroll bar object
    var sizer = new ScrollBar(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-scrollbar/#add-scroll-bar-object","title":"Add scroll bar object","text":"
var scrollBar = scene.rexUI.add.scrollBar({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\norientation: 0,\n\nbackground: backgroundGameObject,    slider: {\nbackground: backgroundGameObject,\n/* \n        background: { \n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\ntrack: trackGameObject,\n/* \n        track: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */    indicator: indicatorGameObject,\n/* \n        indicator: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\nthumb: thumbGameObject,\n/* \n        thumb: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\ninput: 'drag',\ngap: undefined,        easeValue: {\nduration: 0,\nease: 'Linear'\n},\n},\n\nbuttons: {\ntop: topButtonGameObject, bottom: bottomButtonGameObject,\nleft: leftButtonGameObject, right: rightButtonGameObject,\nstep: 0.01,\n}\n\nvaluechangeCallback: function(newValue, oldValue, scrollBar) {\n// scrollBar.text = Math.round(Phaser.Math.Linear(0, 100, newValue));\n}\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\nitem: 0\n},\n\nenable: true,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation : Main orientation of the sizer.
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Arrange game objects from left ot right.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Arrange game objects from top to bottom.
  • background : Game object of background, optional. This background game object will be resized to fit the size of scrollBar.
  • slider : Slider game object which composed of
    • slider.width : Fixed width of slider, optional. Width of slider will be extended if this value is not set.
    • slider.background :
      • Game object of background, optional. This background game object will be resized to fit the size of slider.
      • A plain object to create round rectangle shape
        { radius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.track :
      • Game object of track, optional. This track game object will be resized to fit the size of slider, with space.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.indicator :
      • Game object of indicator, optional.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.thumb :
      • Game object of thumb, optional.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.input :
      • 'pan', 'drag', or 0 : Control knob by panning/dragging thumb game object. Default setting.
      • 'click', or 1 : Control slider by touching track game object.
      • 'none', or -1 : Disable sider controlling.
    • slider.gap : Snap a value to nearest grid slice, using rounding.
      • undefined : Disable this feature.
    • slider.easeValue : Easing value when input is 'click'.
      • slider.easeValue.duration : Duration of value easing, default is 0 (no easing).
      • slider.easeValue.ease : Ease function, default is 'Linear'.
  • buttons : Press button to scroll content in each tick.
    • buttons.top, buttons.bottom : Top and bottom buttons.
    • buttons.left, buttons.right : Left and right buttons
    • buttons.step : Scrolling step in each tick. Default value is 0.01.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds
    • space.item : Space between 2 children game objects.
  • valuechangeCallback : callback function when value changed.
  • enable : Set false to disable controlling.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
"},{"location":"ui-scrollbar/#custom-class","title":"Custom class","text":"
  • Define class
    class MyScrollBar extends RexPlugins.UI.ScrollBar {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var scrollBar = new MyScrollBar(scene, config);\n
"},{"location":"ui-scrollbar/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

scrollBar.layout();\n

See also - dirty

"},{"location":"ui-scrollbar/#get-element","title":"Get element","text":"
  • Get element
  • Background game object
    var background = scrollBar.getElement(\"background\");\n
  • Slider game object
    • Slider background
      var sliderBackground = scrollBar.getElement(\"slider.background\");\n
    • Slider track
      var sliderTrack = scrollBar.getElement(\"slider.track\");\n
    • Slider indicator
      var sliderIndicator = scrollBar.getElement(\"slider.indicator\");\n
    • Slider thumb
      var sliderThumb = scrollBar.getElement(\"slider.thumb\");\n
  • Button game objects
    var buttons = scrollBar.getElement(\"buttons\");\n
    • buttons : Array of button game objects.
      • buttons[0] : Left or top button.
      • buttons[1] : Right or bottom button.
  • Get by name
    var gameObject = scrollBar.getElement(\"#\" + name);\n// var gameObject = scrollBar.getElement('#' + name, recursive);\n
    or
    var gameObject = scrollBar.getByName(\"#\" + name);\n// var gameObject = scrollBar.getByName(name, recursive);\n
  • recursive : Set true to search all children recursively.
"},{"location":"ui-scrollbar/#enable","title":"Enable","text":"
  • Get
    var enable = scrollBar.enable;\n
  • Set
    scrollBar.setEanble(enable);\n
    or
    scrollBar.enable = enable;\n
"},{"location":"ui-scrollbar/#value","title":"Value","text":"

Change value will also change the position of slider thumb and width of slider indicator.

  • Get value
    var value = scrollBar.getValue(min, max); // value : min ~ max\n
    or
    var value = scrollBar.getValue(); // value: 0 ~ 1\n
    or
    var value = scrollBar.value; // value: 0 ~ 1\n
  • Set value
    scrollBar.setValue(value, min, max); // value: min ~ max\n
    or
    scrollBar.setValue(value); // value: 0 ~ 1\n
    or
    scrollBar.value = value; // value: 0 ~ 1\n
  • Increase value
    scrollBar.addValue(inc, min, max); // inc: min ~ max\n
    or
    scrollBar.addValue(inc); // inc: 0 ~ 1\n
    or
    scrollBar.value += inc; // inc: 0 ~ 1\n
"},{"location":"ui-scrollbar/#ease-value","title":"Ease value","text":"
  • Ease value to
    scrollBar.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    scrollBar.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    scrollBar.stopEaseValue();\n
  • Set ease duration
    scrollBar.setEaseValueDuration(duration);\n
  • Set ease function
    scrollBar.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"ui-scrollbar/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-scrollbar/#events","title":"Events","text":"
  • On value changed
    scrollBar.on('valuechange',\nfunction (newValue, oldValue, scrollBar) {\n// scrollBar.text = Math.round(Phaser.Math.Linear(0, 100, newValue));\n},\nscope\n);\n
  • On input start
    scrollBar.on('inputstart', function(pointer) {\n\n}, scope);\n
  • On input end
    scrollBar.on('inputend', function(pointer) {\n\n}, scope);\n
"},{"location":"ui-simpledropdownlist/","title":"Simple drop down list","text":""},{"location":"ui-simpledropdownlist/#introduction","title":"Introduction","text":"

Using plain object to create drop down list.

  • Author: Rex
  • Game object
"},{"location":"ui-simpledropdownlist/#live-demos","title":"Live demos","text":"
  • Drop-down list
  • Drop-down scrollable-list
"},{"location":"ui-simpledropdownlist/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-simpledropdownlist/#install-plugin","title":"Install plugin","text":""},{"location":"ui-simpledropdownlist/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add drop-down list object
    var dropDownList = scene.rexUI.add.simpleDropDownList(config);\n
"},{"location":"ui-simpledropdownlist/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add drop-down list object
    var dropDownList = scene.rexUI.add.simpleDropDownList(config);\n
"},{"location":"ui-simpledropdownlist/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { DropDownList } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add dropDownList object
    var dropDownList = new SimpleDropDownList(scene, config);\nscene.add.existing(dropDownList);\n
"},{"location":"ui-simpledropdownlist/#add-drop-down-list-object","title":"Add drop-down list object","text":"
var dropDownList = scene.rexUI.add.simpleDropDownList({\nlabel: labelStyle,\nbutton: buttonStyle,\n\ntrack: backgroundStyle,\nthumb: backgroundStyle,\n\nlist: {\n// easeIn: 500,\n// transitIn: undefined,\n// transitIn: function(listPanel, duration) {  },\n\n// easeOut: 100,\n// transitOut: undefined,\n// transitOut: function(listPanel, duration) {  },\n\n// wrap: false,\n// maxHeight: undefined,\n// width: undefined, \n// height: undefined,\n// alignParent: 'text',\n// alignSide: '',\n// expandDirection: 0,\n// bounds: undefined,\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom: 0, item: 0,\n//     line: 0\n// },\n\n// draggable: false        \n}\n\n}, creators);\n
  • label :
    • Styles of simple-label
  • button : Use label parameter if button parameter is not given.
    • Styles of simple-label
  • track, thumb :
    • Styles of background
  • list : Configuration of list panel.
    • list.easeIn : Pop-up duration in ms. Default value is 500.
    • list.transitIn : Tween behavior of opening list panel.
      • undefined : Expand list panel by pop-up, default behavior.
      • Custom callback
        function(listPanel, duration) {\n\n}\n
    • list.easeOut : Scale-down duration in ms. Default value is 100.
    • list.transitOut : Tween behavior of closing list panel.
      • undefined : Closing list panel by scale-down, default behavior.
      • Custom callback
        function(listPanel, duration) {\n\n}\n
    • list.wrap :
      • true : fixwidth-sizer layout, a row within buttons.
      • false : sizer layout, a row within a button. Default behavior.
    • list.maxHeight : If height of button list is larger than this maxHeight, put this button list into scrollable panel.
      • undefined, or 0 : Ignore this behavior.
      • > 0 and list.createThumbCallback parameter is given : If height of button list is larger than this maxHeight, put this button list into scrollable panel.
    • list.width : Minimum width.
      • undefined : Minimum width of panel will equal to width of parent label. Default value.
      • A number : Width of panel. Required fields when list.wrap is true.
    • list.height : Minimum height.
      • undefined : Create button list or wrap button list. Default value.
      • > 0 and thumb parameter is given : Create scrollable button list or wrap button list.
    • list.alignParent : Align x position to label.
      • 'icon' : Align x position to icon game object of parent label.
      • 'text' : Align x position to text game object of parent label. Default behavior
      • 'label', or null : Align x position to parent label.
    • list.alignSide : Align list to label's left or right side.
      • undefined, or 'left' : Align list's left side to label's left side. Default behavior.
      • 'right : Align list's right side to label's right side. Default behavior.
    • list.expandDirection :
      • 0, 'down' : Expand list down. i.e. list panel will put below parent label.
      • 1, 'up' : Expand list up. i.e. list panel will put above parent label.
    • list.bounds : Put list panel below parent label if bottom of list panel is inside bounds (Rectangle)
      • undefined : Use viewport as bounds
      • Rectangle
    • list.space : space properties of list panel.
      • left, right, top, bottom, item : For sizer layout. (list.wrap is false)
      • left, right, top, bottom, item, line : For fixwidth-sizer layout. (list.wrap is true)
    • list.draggable : Set true to drag top-most object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-simpledropdownlist/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDropDownList extends RexPlugins.UI.SimpleDropDownList {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var dropDownList = new MyDropDownList(scene, config);\n
"},{"location":"ui-simpledropdownlist/#options","title":"Options","text":"
  • Set
    dropDownList.setOptions(options);\n
    or
    dropDownList.options = options;\n
    • options : Array of strings, or objects contains these properties.
      {\ntext: string,\nvalue: any\n}\n
  • Get
    var options = dropDownList.options;\n
"},{"location":"ui-simpledropdownlist/#other-properties","title":"Other properties","text":"

See drop-down list, label, sizer object, base sizer object, container-lite.

"},{"location":"ui-simpledropdownlist/#events","title":"Events","text":"

See Events section of drop-down list

"},{"location":"ui-simplelabel/","title":"Simple label","text":""},{"location":"ui-simplelabel/#introduction","title":"Introduction","text":"

Using plain object to create label.

  • Author: Rex
  • Game object
"},{"location":"ui-simplelabel/#live-demos","title":"Live demos","text":"
  • Style
  • Bitmaptext
  • Nine-slice background
  • Bar-rectangle background
  • Wrap text
  • TextArea
  • Buttons
"},{"location":"ui-simplelabel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-simplelabel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-simplelabel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add label object
    var label = scene.rexUI.add.simpleLabel(style).resetDisplayContent(config);\n//var label = scene.rexUI.add.simpleLabel(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-simplelabel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add label object
    var label = scene.rexUI.add.simpleLabel(style).resetDisplayContent(config);\n//var label = scene.rexUI.add.simpleLabel(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-simplelabel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { SimpleLabel } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add label object
    var label = new SimpleLabel(scene, style);\n// var label = new SimpleLabel(scene, style, creators);\nscene.add.existing(label);\nlabel.resetDisplayContent(config)\n
"},{"location":"ui-simplelabel/#add-label-object","title":"Add label object","text":"
var label = scene.rexUI.add.simpleLabel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundStyle,\n// background: null,\n\nicon: iconStyle,\n// icon: null,\n\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntext: textStyle,\n// text: null,\n\n// wrapText: false,\n// adjustTextFontSize: false,\n// expandTextWidth: false,\n// expandTextHeight: false,\n\naction: actionStyle,\n// action: null,\n\n// squareFitAction: false,\n// actionMask: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n\nalign: undefined,  // 'left' | 'top' | 'right' | 'bottom' | 'center\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • background :
    • Style of Background : Create Round-rectangle, Bar-rectangle, Nine-slice, or Image as background element.
    • null : Don't create any game object.
  • text :
    • Style of Text : Create Text, BBCodeText, BitmapText, SimpleLabel, or TextArea as text element.
    • null : Don't create any game object.
  • icon, action :
    • Style of Image : Create Image, Nine-slice, or Round-rectangle as image, action element.
    • null : Don't create any game object.
"},{"location":"ui-simplelabel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLabel extends RexPlugins.UI.SimpleLabel {\nconstructor(scene, config, creators) {\nsuper(scene, config, creators);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var label = new MyLabel(scene, config, creators);\n
"},{"location":"ui-simplelabel/#reset-display-content","title":"Reset display content","text":"

See label

"},{"location":"ui-simplelabel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

label.layout();\n

See also - dirty

"},{"location":"ui-simplelabel/#set-state","title":"Set state","text":"

Override/restore properties of elements.

"},{"location":"ui-simplelabel/#active-state","title":"Active state","text":"
  • Enable active state
    label.setActiveState();\n// label.setActiveState(true);\n
    • Override properties of background declared in config with prefix 'active.' parameters.
  • Disable active state
    label.setActiveState(false);\n
    • Restore properties of background.
"},{"location":"ui-simplelabel/#hover-state","title":"Hover state","text":"
  • Enable active state
    label.setHoverState();\n// label.setHoverState(true);\n
    • Override properties of background declared in config with prefix 'hover.' parameters
  • Disable active state
    label.setHoverState(false);\n
    • Restore properties of background.
"},{"location":"ui-simplelabel/#disable-state","title":"Disable state","text":"
  • Enable disable state
    label.setDisableState();\n// label.setDisableState(true);\n
    • Override properties of background declared in config with prefix 'disable.' parameters
  • Disable disable state
    label.setDisableState(false);\n
    • Restore properties of background.
"},{"location":"ui-simplelabel/#get-element","title":"Get element","text":"

See label

"},{"location":"ui-simplelabel/#other-properties","title":"Other properties","text":"

See label, sizer object, base sizer object, container-lite.

"},{"location":"ui-simpletextbox/","title":"Simple text box","text":""},{"location":"ui-simpletextbox/#introduction","title":"Introduction","text":"

Using plain object to create textBox.

  • Author: Rex
  • Game object
"},{"location":"ui-simpletextbox/#live-demos","title":"Live demos","text":"
  • Inner sizer
"},{"location":"ui-simpletextbox/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-simpletextbox/#install-plugin","title":"Install plugin","text":""},{"location":"ui-simpletextbox/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add textBox object
    var textBox = scene.rexUI.add.simpleTextBox(style).resetDisplayContent(config);\n//var textBox = scene.rexUI.add.simpleTextBox(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-simpletextbox/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add textBox object
    var textBox = scene.rexUI.add.simpleTextBox(style).resetDisplayContent(config);\n//var textBox = scene.rexUI.add.simpleTextBox(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-simpletextbox/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { SimpleTextBox } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add textBox object
    var textBox = new SimpleTextBox(scene, style);\n// var textBox = new SimpleTextBox(scene, style, creators);\nscene.add.existing(textBox);\ntextBox.resetDisplayContent(config)\n
"},{"location":"ui-simpletextbox/#add-textbox-object","title":"Add textBox object","text":"
var textBox = scene.rexUI.add.simpleTextBox({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nlayoutMode: 0,\n\n// rtl: false,\n\nbackground: backgroundStyle,\n// background: null,\n\ninnerBackground: backgroundStyle,\n// innerBackground: null,\n\nicon: iconStyle,\n// icon: null,\n\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntitle: textStyle,\n// title: null,\n// wrapTitle: false,\n// adjustTitleFontSize: false,\n// expandTitleWidth: false,\n// expandTitleHeight: false,\n\ntext: testStyle,\n// text: null,\n// wrapText: false,\n// adjustTextFontSize: false,\n// expandTextWidth: false,\n// expandTextHeight: false,\n\nseparator: separatorStyle,\n// separator: null,\n\naction: actionStyle,\n// action: null,\n\n// squareFitAction: false,\n// actionMask: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n\nalign: {\ntitle: 'left',\ntext: 'left',\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ninnerLeft: 0, innerRight: 0, innerTop: 0, innerBottom: 0,\n\ntitle: 0, titleLeft: 0, titleRight: 0,\nicon: 0, iconTop: 0, iconBottom: 0,\ntext: 0, textLeft: 0, textRight: 0,\nseparator: 0, separatorLeft: 0, separatorRight: 0,\nactionTop: 0, actionBottom: 0,\n},\n\n// page: { \n//    maxLines: undefined,\n//    pageBreak: '\\f\\n',\n// },\n// typing: { \n//    wrap: false,\n//    speed: 333,    \n// },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • background, innerBackground :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as background element.
    • null : Don't create any game object.
  • title :
    • Style of Text : Create Text, BBCodeText, BitmapText, SimpleLabel, or TextArea as title element.
    • null : Don't create any game object.
  • text :
    • Style of Text : Create Text, BBCodeText, BitmapText as text element.
      • Don't use SimpleLabel, or TextArea as text element.
    • null : Don't create any game object.
  • separator :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as separator element.
    • null : Don't create any game object.
  • icon, action :
    • Style of Image : Create Image, Nine-slice, or Round-rectangle as image, action element.
    • null : Don't create any game object.
  • wrapTitle : Enable WrapExpandText feature.
    • false, 0 : No WrapExpandText feature. Default behavior.
    • true, 1, 'word' : Word WrapExpandText.
    • 2, 'char' : Character WrapExpandText.
  • adjustTitleFontSize : Enable FontSizeExpandText feature.
    • false : No FontSizeExpandText feature. Default behavior.
    • true : Enable FontSizeExpandText feature. Can't work with wrapText: true.
      • Text-width and text-height will be expanding.
      • Use BBCodeText (scene.rexUI.add.BBCodeText) with {valign: 'center'} style.
  • wrapText : Enable WrapExpandText feature.
    • false, 0 : No WrapExpandText feature. Default behavior.
    • true, 1, 'word' : Word WrapExpandText.
    • 2, 'char' : Character WrapExpandText.
  • adjustTextFontSize : Enable FontSizeExpandText feature.
    • false : No FontSizeExpandText feature. Default behavior.
    • true : Enable FontSizeExpandText feature. Can't work with wrapText: true.
      • Text-width and text-height will be expanding.
      • Use BBCodeText (scene.rexUI.add.BBCodeText) with {valign: 'center'} style.
"},{"location":"ui-simpletextbox/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTextBox extends RexPlugins.UI.SimpleTextBox {\nconstructor(scene, config, creators) {\nsuper(scene, config, creators);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var textBox = new MyTextBox(scene, config, creators);\n
"},{"location":"ui-simpletextbox/#reset-display-content","title":"Reset display content","text":"

See title-label

"},{"location":"ui-simpletextbox/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

textBox.layout();\n

See also - dirty

"},{"location":"ui-simpletextbox/#typing","title":"Typing","text":"

See textBox

"},{"location":"ui-simpletextbox/#get-element","title":"Get element","text":"

See textBox

"},{"location":"ui-simpletextbox/#events","title":"Events","text":"

See textBox

"},{"location":"ui-simpletextbox/#other-properties","title":"Other properties","text":"

See textBox, sizer object, base sizer object, container-lite.

"},{"location":"ui-simpletitlelabel/","title":"Simple title label","text":""},{"location":"ui-simpletitlelabel/#introduction","title":"Introduction","text":"

Using plain object to create title-label.

  • Author: Rex
  • Game object
"},{"location":"ui-simpletitlelabel/#live-demos","title":"Live demos","text":"
  • Style
"},{"location":"ui-simpletitlelabel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-simpletitlelabel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-simpletitlelabel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add label object
    var label = scene.rexUI.add.simpleLabel(style).resetDisplayContent(config);\n//var label = scene.rexUI.add.simpleLabel(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-simpletitlelabel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add label object
    var label = scene.rexUI.add.simpleLabel(style).resetDisplayContent(config);\n//var label = scene.rexUI.add.simpleLabel(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-simpletitlelabel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { SimpleTitleLabel } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add label object
    var label = new SimpleTitleLabel(scene, style);\n// var label = new SimpleTitleLabel(scene, style, creators);\nscene.add.existing(label);\nlabel.resetDisplayContent(config)\n
"},{"location":"ui-simpletitlelabel/#add-label-object","title":"Add label object","text":"
var label = scene.rexUI.add.simpleLabel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nlayoutMode: 0,\n\n// rtl: false,\n\nbackground: backgroundStyle,\n// background: null,\n\ninnerBackground: backgroundStyle,\n// innerBackground: null,\n\nicon: iconStyle,\n// icon: null,\n\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntitle: textStyle,\n// title: null,\n// wrapTitle: false,\n// adjustTitleFontSize: false,\n// expandTitleWidth: false,\n// expandTitleHeight: false,\n\ntext: testStyle,\n// text: null,\n// wrapText: false,\n// adjustTextFontSize: false,\n// expandTextWidth: false,\n// expandTextHeight: false,\n\nseparator: separatorStyle,\n// separator: null,\n\naction: actionStyle,\n// action: null,\n\n// squareFitAction: false,\n// actionMask: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n\nalign: {\ntitle: 'left',\ntext: 'left',\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ninnerLeft: 0, innerRight: 0, innerTop: 0, innerBottom: 0,\n\ntitle: 0, titleLeft: 0, titleRight: 0,\nicon: 0, iconTop: 0, iconBottom: 0,\ntext: 0, textLeft: 0, textRight: 0,\nseparator: 0, separatorLeft: 0, separatorRight: 0,\nactionTop: 0, actionBottom: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • background, innerBackground :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as background element.
    • null : Don't create any game object.
  • title :
    • Style of Text : Create Text, BBCodeText, BitmapText, SimpleLabel, or TextArea as title element.
    • null : Don't create any game object.
  • text :
    • Style of Text : Create Text, BBCodeText, BitmapText, SimpleLabel, or TextArea as text element.
    • null : Don't create any game object.
  • separator :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as separator element.
    • null : Don't create any game object.
  • icon, action :
    • Style of Image : Create Image, Nine-slice, or Round-rectangle as image, action element.
    • null : Don't create any game object.
"},{"location":"ui-simpletitlelabel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLabel extends RexPlugins.UI.SimpleTitleLabel {\nconstructor(scene, config, creators) {\nsuper(scene, config, creators);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var label = new MyLabel(scene, config, creators);\n
"},{"location":"ui-simpletitlelabel/#reset-display-content","title":"Reset display content","text":"

See title-label

"},{"location":"ui-simpletitlelabel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

label.layout();\n

See also - dirty

"},{"location":"ui-simpletitlelabel/#set-state","title":"Set state","text":"

Override/restore properties of elements.

"},{"location":"ui-simpletitlelabel/#active-state","title":"Active state","text":"
  • Enable active state
    label.setActiveState();\n// label.setActiveState(true);\n
    • Override properties of background declared in config with prefix 'active.' parameters.
  • Disable active state
    label.setActiveState(false);\n
    • Restore properties of background.
"},{"location":"ui-simpletitlelabel/#hover-state","title":"Hover state","text":"
  • Enable active state
    label.setHoverState();\n// label.setHoverState(true);\n
    • Override properties of background declared in config with prefix 'hover.' parameters
  • Disable active state
    label.setHoverState(false);\n
    • Restore properties of background.
"},{"location":"ui-simpletitlelabel/#disable-state","title":"Disable state","text":"
  • Enable disable state
    label.setDisableState();\n// label.setDisableState(true);\n
    • Override properties of background declared in config with prefix 'disable.' parameters
  • Disable disable state
    label.setDisableState(false);\n
    • Restore properties of background.
"},{"location":"ui-simpletitlelabel/#get-element","title":"Get element","text":"

See title-label

"},{"location":"ui-simpletitlelabel/#other-properties","title":"Other properties","text":"

See title-label, sizer object, base sizer object, container-lite.

"},{"location":"ui-sizer/","title":"Sizer","text":""},{"location":"ui-sizer/#introduction","title":"Introduction","text":"

Layout children game objects.

It is inspired from wxSizer.

  • Author: Rex
  • Game object
"},{"location":"ui-sizer/#live-demos","title":"Live demos","text":"
  • Nested sizer
    • Demo 1
    • Demo 2
    • Demo 3
  • Proportion
  • DOM child
  • Set children interactive
  • Drag drop child
  • Bring child to top
  • Fit-ratio
  • Sort
"},{"location":"ui-sizer/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-sizer/#install-plugin","title":"Install plugin","text":""},{"location":"ui-sizer/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add sizer object
    var sizer = scene.rexUI.add.sizer(config);\n
"},{"location":"ui-sizer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add sizer object
    var sizer = scene.rexUI.add.sizer(config);\n
"},{"location":"ui-sizer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Sizer } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add sizer object
    var sizer = new Sizer(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-sizer/#add-sizer-object","title":"Add sizer object","text":"
var sizer = scene.rexUI.add.sizer({\norientation: 0,\n// rtl: false,\n// startChildIndex: 0,\n\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0, item:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n

or

var sizer = scene.rexUI.add.sizer(x, y, {\norientation: 0,\n// rtl: false,\n// startChildIndex: 0,\n\n// width: undefined,\n// height: undefined,\n// anchor: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0, item:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n

or

var sizer = scene.rexUI.add.sizer(x, y, width, height, {\norientation: 0,\n// rtl: false,\n// startChildIndex: 0,\n// anchor: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0, item:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n

or

var sizer = scene.rexUI.add.sizer(x, y, width, height, orientation, {\n// rtl: false,\n// startChildIndex: 0,\n// anchor: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0, item:0 }\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation : Orientation of the sizer.
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Arrange game objects from left ot right. Default value is 0.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Arrange game objects from top to bottom.
  • rtl :
    • false : Layout children from left to right. Default behavior.
    • true : Layout children from right to left.
  • startChildIndex : A number, start index of first layout child. Default value is 0.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between 2 children game objects.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-sizer/#custom-class","title":"Custom class","text":"
  • Define class
    class MySizer extends RexPlugins.UI.Sizer {\nconstructor(scene, x, y, minWidth, minHeight, orientation, config) {\nsuper(scene, x, y, minWidth, minHeight, orientation, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var sizer = new MySizer(scene, x, y, minWidth, minHeight, orientation);\n
"},{"location":"ui-sizer/#add-background","title":"Add background","text":"
sizer.addBackground(child);\n

or

sizer.addBackground(child, {left: 0, right: 0, top: 0, bottom: 0}, key);\n
  • left, right, top, bottom : Extra padded space. Default is 0.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
"},{"location":"ui-sizer/#add-child","title":"Add child","text":"

Add a game obejct to sizer

sizer.add(child);\n

or

sizer.add(child,\n{\nproportion: 0,\nalign: 'center',\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nexpand: false,\nkey: undefined,\nindex: undefined,\nminWidth: undefined,\nminHeight: undefined,\nfitRatio: 0,  // true\n}\n);\n

or

sizer.add(child, proportion, align, padding, expand, key, index);\n// sizer.add(child, proportion, align, padding, expand, key, index);\n
  • child : A game object.
  • proportion :
    • 0, or 'min' : Place next game object closely. Default value.
    • > 0 : Stretch game object via proportion value.
    • null : Don't arrange this child.
  • align :
    • For horizontal orientation sizer :
      • 'center', or Phaser.Display.Align.CENTER : Align game object at vertical-center. Default value.
      • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game object at top-center.
      • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at bottom-center.
      • Use addSpace() to align child at horizontal-center.
    • For vertical orientation sizer :
      • 'center', or Phaser.Display.Align.CENTER : Align game object at horizontal-center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
      • Use addSpace() to align child at vertical-center.
  • padding : Extra padded space. Default is 0.
    • A number for left/right/top/bottom bounds,
    • Or a plain object.
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • expand : Set true to
    • Expand height when orientation is 0 (left-to-right), or
    • Expand width when orientation is 1 (top-to-bottom)
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
  • index : Insert child to.
    • undefined : Insert child at last.
  • minWidth : Minimum width of normal (non-sizer) game object, used when orientation is x, and proportion is not 0, or orientation is y, and expand is true
    • Default value is current display width.
  • minHeight : Minimum height of normal (non-sizer) game object, used when orientation is y, and proportion is not 0, or orientation is x, and expand is true
    • Default value is current display height.
  • fitRatio : Resize child to fit sizer height/width before layout children, when proportion is set to 0.
    • 0, or false : Ignore this feature. Default behavior.
    • true : Fit ratio (width/height) from game object's display size.
    • > 0 : Fit ratio (width/height). 1 is square.
"},{"location":"ui-sizer/#insert-child","title":"Insert child","text":"
sizer.insert(index, child, {\nproportion: 0,\nalign: 'center',\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nexpand: false,\nkey: undefined,\nminWidth: undefined,\nminHeight: undefined,\nfitRatio: 0,\n}\n);\n

or

sizer.insert(index, child, proportion, align, padding, expand, key);\n
"},{"location":"ui-sizer/#insert-at-position","title":"Insert at position","text":"
sizer.insertAtPosition(x, y, child, {\nproportion: 0,\nalign: 'center',\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nexpand: false,\nkey: undefined,\nminWidth: undefined,\nminHeight: undefined,\nfitRatio: 0,\n}\n);\n

or

sizer.insertAtPosition(x, y, index, child, proportion, align, padding, expand, key);\n
"},{"location":"ui-sizer/#add-space","title":"Add space","text":"
  • Add a stretchable space.
    sizer.addSpace();\n// sizer.addSpace(proportion);\n
  • Insert a stretchable space.
    sizer.insertSpace(index);\n// sizer.insertSpace(index, proportion);\n

Use cases :

  • Align child at center
    sizer\n.addSpace()\n.add(child)\n.addSpace()\n
  • Align 2 children at left and right side
    sizer\n.add(childLeft)\n.addSpace()\n.add(childRight)\n
"},{"location":"ui-sizer/#change-childrens-align-mode","title":"Change children's align mode","text":"
sizer\n.setChildrenAlignMode(mode)\n.layout();\n
  • mode : Alignment of icon, text, action game objects.
    • undefined, or 'left', or 'top' : Align game objects at left, or top.
      • Remove first and last space children.
    • 'center' : Align game objects at center.
      • Add two spaces as first and last children.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
      • Add space as first child.
"},{"location":"ui-sizer/#layout-children","title":"Layout children","text":"

Arrange position of all children.

sizer.layout();\n

See also - dirty

"},{"location":"ui-sizer/#hide","title":"Hide","text":"
  • Set invisible, won't layout it
    sizer.hide();\n
    or
    sizer.hide(gameObject);\n
  • Set visible, will layout it
    sizer.show();\n
    or
    sizer.show(gameObject);\n
"},{"location":"ui-sizer/#remove-child","title":"Remove child","text":"
  • Remove a child
    sizer.remove(child);\n
  • Remove and destroy a child
    sizer.remove(child, true);\n
  • Remove all children
    sizer.removeAll();\n
  • Remove and destroy all children
    sizer.removeAll(true);\n
  • Remove all children and backgrounds
    sizer.clear();\n
  • Remove and destroy all children and backgrounds
    sizer.clear(true);\n
  • Remove from parent sizer
    sizer.removeFromParentSizer();\n
"},{"location":"ui-sizer/#sort-children","title":"Sort children","text":"
  • Sort by data
    sizer.sortChildrenByData(key, descending).layout();\n
    • key : Data key
    • descending :
      • true : Descending order
      • false : Ascending order, default behavior.
  • Sort by property of child
    sizer.sortChildrenByProperty(key, descending).layout();\n
    • key : Property key
    • descending :
      • true : Descending order
      • false : Ascending order, default behavior.
  • Sort by callback
    sizer.sortChildren(function(childA, childB){\n// var valueA = childA.getData(key);\n// var valueB = childB.getData(key);\n// return valueB - valueA\n}).layout();\n
    • childA, childB : 2 children of this size
"},{"location":"ui-sizer/#get-element","title":"Get element","text":"
  • Get element
    • All children items
      var items = sizer.getElement('items');\n
  • Get by name
    var gameObject = sizer.getElement('#' + name);\n// var gameObject = sizer.getElement('#' + name, recursive);\n
    or
    var gameObject = sizer.getByName(name);\n// var gameObject = sizer.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-sizer/#get-child-index","title":"Get child index","text":"
var index = sizer.getChildIndex(child);\n
  • index : A number, or null.
"},{"location":"ui-sizer/#rtl","title":"RTL","text":"
  • Set rtl in config of constructor
  • Set rtl : sizer.setRTL(enable)
  • Get rtl : var rtl = sizer.rtl
"},{"location":"ui-sizer/#alignment-of-child","title":"Alignment of child","text":"
  • Set alignment of child in config of adding child
  • Set alignment of child : sizer.setChildAlign(child, align)
    • align :
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
      • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game object at top-center.
      • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at bottom-center.
  • Get alignment of child : var align = sizer.getChildAlign(child)
"},{"location":"ui-sizer/#proportion-of-child","title":"Proportion of child","text":"
  • Set proportion of child in config of adding child
  • Set proportion of child : sizer.setChildProportion(child, proportion)
  • Get proportion of child : var align = sizer.getChildProportion(child)
"},{"location":"ui-sizer/#expand-of-child","title":"Expand of child","text":"
  • Set expand of child in config of adding child
  • Set expand of child : sizer.setChildExpand(child, expand)
  • Get expand of child : var expand = sizer.getChildExpand(child)
"},{"location":"ui-sizer/#other-properties","title":"Other properties","text":"

See base sizer object, container-lite.

"},{"location":"ui-slider/","title":"Slider","text":""},{"location":"ui-slider/#introduction","title":"Introduction","text":"

A container with a track, indicator, thumb and background.

  • Author: Rex
  • Game object
"},{"location":"ui-slider/#live-demos","title":"Live demos","text":"
  • Slider bar
  • Color picker
  • Crop resize
  • Gap
"},{"location":"ui-slider/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-slider/#install-plugin","title":"Install plugin","text":""},{"location":"ui-slider/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add slider object
    var slider = scene.rexUI.add.slider(config);\n
"},{"location":"ui-slider/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add slider object
    var slider = scene.rexUI.add.slider(config);\n
"},{"location":"ui-slider/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Slider } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add slider object
    var slider = new Slider(scene, config);\nscene.add.existing(slider);\n
"},{"location":"ui-slider/#add-slider-object","title":"Add slider object","text":"
var slider = scene.rexUI.add.slider({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\nreverseAxis: false,\n\nbackground: backgroundGameObject,\n/* \n    background: { \n        radius: 0, \n        color: undefined, alpha: 1,\n        strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n        shape: undefined\n    }\n    */\n\ntrack: trackGameObject,\n/* \n    track: { \n        width: 1, height: 1,\n        radius: 0, \n        color: undefined, alpha: 1,\n        strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n        shape: undefined\n    }\n    */    indicator: indicatorGameObject,\n/* \n    indicator: { \n        width: 1, height: 1,\n        radius: 0, \n        color: undefined, alpha: 1,\n        strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n        shape: undefined\n    }\n    */\n\nthumb: thumbGameObject,\n/* \n    thumb: { \n        width: 1, height: 1,\n        radius: 0, \n        color: undefined, alpha: 1,\n        strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n        shape: undefined\n    }\n    */\nthumbOffsetX: 0,\nthumbOffsetY: 0,\n\ninput: 'drag',\n\nvalue: 0,\ngap: undefined,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},    valuechangeCallback: function(newValue, oldValue, slider) {\n},\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n\nenable: true,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Horizontal slider.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Vertical slider.
  • reverseAxis :
    • false : Map left/top to 0, and right/bottom to 1. Default behavior.
    • true : Map left/top to 1, and right/bottom to 0.
  • background :
    • Game object of background, optional. This background game object will be resized to fit the size of slider.
    • A plain object to create round rectangle shape
      { radius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
  • track :
    • Game object of track, optional. This track game object will be resized to fit the size of slider, with space.
    • A plain object to create round rectangle shape
      { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
  • indicator :
    • Game object of indicator, optional.
    • A plain object to create round rectangle shape
      { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
  • thumb :
    • Game object of thumb, optional.
    • A plain object to create round rectangle shape
      { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
  • thumbOffsetX, thumbOffsetY : Shift thumb, default value is 0.
  • input :
    • 'pan', 'drag', or 0 : Control slider by panning/dragging thumb game object. Default setting.
    • 'click', or 1 : Control slider by touching track game object.
    • 'none', or -1 : Disable sider controlling.
  • value : Initial value (0 ~ 1).
  • gap : Snap a value to nearest grid slice, using rounding.
    • undefined : Disalbe this feature.
  • easeValue : Easing value when input is 'click'.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • valuechangeCallback : callback function when value changed.
    function(newValue, oldValue, slider) {\n}\n
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
  • enable : Set false to disable controlling.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-slider/#custom-class","title":"Custom class","text":"
  • Define class
    class MySlider extends RexPlugins.UI.Slider {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var slider = new MySlider(scene, config);\n
"},{"location":"ui-slider/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

slider.layout();\n

See also - dirty

"},{"location":"ui-slider/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = slider.getElement('background');\n
    • Track game object
      var track = slider.getElement('track');\n
    • Indicator game object
      var track = slider.getElement('indicator');\n
    • Thumb track game object
      var action = slider.getElement('thumb');\n
  • Get by name
    var gameObject = slider.getElement('#' + name);\n// var gameObject = slider.getElement('#' + name, recursive);\n
    or
    var gameObject = slider.getByName(name);\n// var gameObject = slider.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-slider/#enable","title":"Enable","text":"
  • Get
    var enable = slider.enable;\n
  • Set
    slider.setEanble(enable);\n
    or
    slider.enable = enable;\n
"},{"location":"ui-slider/#value","title":"Value","text":"

Change value will also change the position of slider thumb and width of slider indicator.

  • Get value
    var value = slider.getValue(min, max); // value : min ~ max\n
    or
    var value = slider.getValue(); // value: 0 ~ 1\n
    or
    var value = slider.value; // value: 0 ~ 1\n
  • Set value
    slider.setValue(value, min, max); // value: min ~ max\n
    or
    slider.setValue(value); // value: 0 ~ 1\n
    or
    slider.value = value; // value: 0 ~ 1\n
  • Increase value
    slider.addValue(inc, min, max); // inc: min ~ max\n
    or
    slider.addValue(inc); // inc: 0 ~ 1\n
    or
    slider.value += inc; // inc: 0 ~ 1\n
"},{"location":"ui-slider/#ease-value","title":"Ease value","text":"
  • Ease value to
    slider.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    slider.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    slider.stopEaseValue();\n
  • Set ease duration
    slider.setEaseValueDuration(duration);\n
  • Set ease function
    slider.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"ui-slider/#gap","title":"Gap","text":"
  • Set
    slider.setGap(gap);  // gap: 0~1\n
    or
    slider.setGap(gap, min, max);  // gap: min~max\n
  • Get
    var gap = slider.gap;  // gap: 0~1\n
"},{"location":"ui-slider/#events","title":"Events","text":"
  • On value changed
    slider.on('valuechange', function(newValue, oldValue, slider){\n//\n}, scope);\n
  • On input start
    slider.on('inputstart', function(pointer) {\n\n}, scope);\n
  • On input end
    slider.on('inputend', function(pointer) {\n\n}, scope);\n
"},{"location":"ui-slider/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-splitpanels/","title":"Split panels","text":""},{"location":"ui-splitpanels/#introduction","title":"Introduction","text":"

A container with left(top) panel, right(bottom) panel, splitter, and background. Drag splitter to resize with left(top) panel, right(bottom) panel.

  • Author: Rex
  • Game object
"},{"location":"ui-splitpanels/#live-demos","title":"Live demos","text":"
  • Split-panels
"},{"location":"ui-splitpanels/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-splitpanels/#install-plugin","title":"Install plugin","text":""},{"location":"ui-splitpanels/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add split-panels object
    var splitPanels = scene.rexUI.add.splitPanels(config);\n
"},{"location":"ui-splitpanels/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add split-panels object
    var splitPanels = scene.rexUI.add.splitPanels(config);\n
"},{"location":"ui-splitpanels/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { SplitPanels } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add split-panels object
    var splitPanels = new SplitPanels(scene, config);\nscene.add.existing(splitPanels);\n
"},{"location":"ui-splitpanels/#add-split-panels-object","title":"Add split-panels object","text":"
var splitPanels = scene.rexUI.add.splitPanels({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\n\nleftPanel: leftPanelGameObject,\n// topPanel: topPanelGameObject,\n\nrightPanel: rightPanelGameObject,\n// bottomPanel: topPanelGameObject,\n\nsplitter: splitterGameObject,\n\nminLeftPanelWidth: 0,\nminTopPanelHeight: 0,\n\nminRightPanelWidth: 0,\nminBottomPanelHeight: 0,\n\nsplitRatio: 0.5\n\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0, item: 0,\n\nleftPanelTop: 0, leftPanelBottom: 0, leftPanelLeft: 0, leftPanelRight: 0,\n// topPanelTop: 0, topPanelBottom: 0, topPanelLeft: 0, topPanelRight: 0,\n\nrightPanelTop: 0, rightPanelBottom: 0, rightPanelLeft: 0, rightPanelRight: 0,\n// bottomPanelTop: 0, bottomPanelBottom: 0, bottomPanelLeft: 0, bottomPanelRight: 0,\n\nsplitterPanelTop: 0, splitterPanelBottom: 0, splitterPanelLeft: 0, splitterPanelRight: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • leftPanel(topPanel), rightPanel(bottomPanel) : First and second panel children.
  • splitter : Game object of splitter.
  • minLeftPanelWidth(minTopPanelHeight), minRightPanelWidth(minBottomPanelHeight) : Minimum width/height of first and second children.
    • 0 : Width/height does not have constraint. Default behavior.
  • splitRatio : Position of splitter. 0~1. Default value is 0.5.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between first child and splitter, splitter and second child.
    • space.leftPanelTop(space.topPanelTop), space.leftPanelBottom(space.topPanelBottom), space.leftPanelLeft(space.topPanelLeft), space.leftPanelRight(space.topPanelRight) : Space around first game object.
    • space.rightPanelTop(space.bottomPanelTop), space.rightPanelBottom(space.bottomPanelBottom), space.rightPanelLeft(space.bottomPanelLeft), space.rightPanelRight(space.bottomPanelRight) : Space around second game object.
    • space.splitterTop, space.splitterBottom, space.splitterLeft, space.splitterRight : Space around splitter game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-splitpanels/#custom-class","title":"Custom class","text":"
  • Define class
    class MySplitPanels extends RexPlugins.UI.SplitPanels {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var splitPanels = new MySplitPanels(scene, config);\n
"},{"location":"ui-splitpanels/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

splitPanels.layout();\n

See also - dirty

"},{"location":"ui-splitpanels/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = splitPanels.getElement('background');\n
    • First game object
      var leftPanel = splitPanels.getElement('leftPanel');\n// var topPanel = splitPanels.getElement('topPanel');\n
    • Second game object
      var rightPanel = splitPanels.getElement('rightPanel');\n// var bottomPanel = splitPanels.getElement('bottomPanel');\n
    • Splitter game object
      var splitter = splitPanels.getElement('splitter');\n
  • Get by name
    var gameObject = splitPanels.getElement('#' + name);\n// var gameObject = splitPanels.getElement('#' + name, recursive);\n
    or
    var gameObject = splitPanels.getByName(name);\n// var gameObject = splitPanels.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-splitpanels/#split-ratio","title":"Split ratio","text":"
  • Get
    var splitRatio = splitPanels.splitRatio;\n
  • Set
    splitPanels.setSplitRatio(value);\n
    or
    splitPanels.splitRatio = value;\n
"},{"location":"ui-splitpanels/#minimum-child-size","title":"Minimum child size","text":"
  • Get
    var minLeftPanelWidth = splitPanels.minLeftPanelWidth;\n// var minTopPanelHeight = splitPanels.minTopPanelHeight;\n\nvar minRightPanelWidth = splitPanels.minRightPanelWidth;\n// var minBottomPanelHeight = splitPanels.minBottomPanelHeight;\n
  • Set
    splitPanels.setMinLeftPanelWidth(value);\n// splitPanels.setMinTopPanelHeight(value);\n\nsplitPanels.setMinRightPanelWidth(value);\n// splitPanels.setMinBottomPanelHeight(value);\n
    or
    splitPanels.minLeftPanelWidth = value;\n// splitPanels.minTopPanelHeight = value;\n\nsplitPanels.minRightPanelWidth = value;\n// splitPanels.minBottomPanelHeight = value;\n
"},{"location":"ui-splitpanels/#enable","title":"Enable","text":"
  • Get
    var enable = splitPanels.splitterEnable;\n
  • Set
    slider.setSplitterEnable(enable);\n
    or
    slider.splitterEnable = enable;\n
"},{"location":"ui-splitpanels/#events","title":"Events","text":"
  • On drag splitter start
    splitPanels.on('splitter.dragstart', function(splitter, splitRatio){\n//\n}, scope);\n
  • On drag splitter end
    splitPanels.on('splitter.dragend', function(splitter, splitRatio){\n//\n}, scope);\n
  • On dragging splitter
    splitPanels.on('splitter.drag', function(splitter, splitRatio){\n//\n}, scope);\n
  • On pointer-over splitter
    splitPanels.on('splitter.over', function(splitter, splitRatio){\n//\n}, scope);\n
  • On pointer-out splitter
    splitPanels.on('splitter.out', function(splitter, splitRatio){\n//\n}, scope);\n
"},{"location":"ui-splitpanels/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-style/","title":"Style","text":""},{"location":"ui-style/#introduction","title":"Introduction","text":"

Style in plain object for creating image, or text.

"},{"location":"ui-style/#style-of-background","title":"Style of Background","text":"

Create Round-rectangle, Nine-slice, Nine-patch, or Image for background.

  • Create Round-rectangle, if style has color, or strokeColor key. Default type of Background.
  • Create Line-progress, if style has bar key.
  • Create Nine-slice, if style has leftWidth key.
  • Create Nine-patch, if style has leftWidth and stretchMode key.
  • Create Image, if style has key key.
"},{"location":"ui-style/#style-of-image","title":"Style of Image","text":"

Create Image, Nine-slice, Nine-patch, or Round-rectangle for image.

  • Create Image, if style has key key. Default type of Background.
  • Create Nine-slice, if style has leftWidth key.
  • Create Nine-patch, if style has leftWidth and stretchMode key.
  • Create Round-rectangle, if style has color, or strokeColor key.
"},{"location":"ui-style/#style-of-text","title":"Style of Text","text":"

Create Text, BBCodetext, BitmapText, SimpleLabel, or TextArea for text.

  • Text, by style, default type of Text.
  • BBCodetext, by style.
  • BitmapText, by style.
  • SimpleLabel, by style.
  • TextArea, by style.
"},{"location":"ui-style/#style-of-image-game-object","title":"Style of Image game object","text":"
{\n// $type: 'image',\n\nkey:\n// frame:\n// tint: 0xffffff,\n// alpha: 1,\n// scale: 1,\n// flipX: false,\n// flipY: false,\n// origin:\n// originX: \n// originY:\n\n// effects: true,\n// Style override in active state\n// 'active.key': undefined,\n// 'active.frame': undefined,\n// 'active.tint': undefined,\n// 'active.alpha': undefined,\n// 'active.scale': undefined,\n// 'active.glowColor': null,\n// ...\n\n// Style override in hover state\n// 'hover.key': undefined,\n// 'hover.frame': undefined,\n// 'hover.tint': undefined,\n// 'hover.alpha': undefined,\n// 'hover.scale': undefined,\n// 'hover.glowColor': null,\n// ...\n\n// Style override in disable state\n// 'disable.key': undefined,\n// 'disable.frame': undefined,\n// 'disable.tint': undefined,\n// 'disable.alpha': undefined,\n// 'disable.scale': undefined,\n// 'disable.glowColor': null,\n// ...    \n}\n
"},{"location":"ui-style/#style-of-nine-slice","title":"Style of Nine-slice","text":"
{\n// $type: 'nineSlice',\n\nkey: ,\nframe: ,\nleftWidth: , rightWidth: ,\ntopHeight: , bottomHeight: ,\n// tint: 0xffffff,\n// alpha: 1,\n// scale: 1,\n// flipX: false,\n// flipY: false,\n// origin:\n// originX: \n// originY:\n// width: 0,\n// height: 0,\n\n// effects: true,\n\n// Style override in active state\n// 'active.key': undefined,\n// 'active.frame': undefined,\n// 'active.tint': undefined,\n// 'active.alpha': undefined,\n// 'active.scale': undefined,\n// 'active.glowColor': null,\n// ...\n\n// Style override in hover state\n// 'hover.key': undefined,\n// 'hover.frame': undefined,\n// 'hover.tint': undefined,\n// 'hover.alpha': undefined,\n// 'hover.scale': undefined,\n// 'hover.glowColor': null,\n// ...\n\n// Style override in disable state\n// 'disable.key': undefined,\n// 'disable.frame': undefined,\n// 'disable.tint': undefined,\n// 'disable.alpha': undefined,\n// 'disable.scale': undefined,\n// 'disable.glowColor': null,\n// ...  \n}\n
"},{"location":"ui-style/#style-of-nine-patch","title":"Style of Nine-patch","text":"
{\n// $type: 'nineSlice',\n\nkey: ,\nframe: ,\nleftWidth: , rightWidth: ,\ntopHeight: , bottomHeight: ,\nstretchMode: ,\n// tint: 0xffffff,\n// alpha: 1,\n// scale: 1,\n// flipX: false,\n// flipY: false,\n// origin:\n// originX: \n// originY:\n// width: 0,\n// height: 0,\n\n// effects: true,\n\n// Style override in active state\n// 'active.key': undefined,\n// 'active.frame': undefined,\n// 'active.tint': undefined,\n// 'active.alpha': undefined,\n// 'active.scale': undefined,\n// 'active.glowColor': null,\n// ...\n\n// Style override in hover state\n// 'hover.key': undefined,\n// 'hover.frame': undefined,\n// 'hover.tint': undefined,\n// 'hover.alpha': undefined,\n// 'hover.scale': undefined,\n// 'hover.glowColor': null,\n// ...\n\n// Style override in disable state\n// 'disable.key': undefined,\n// 'disable.frame': undefined,\n// 'disable.tint': undefined,\n// 'disable.alpha': undefined,\n// 'disable.scale': undefined,\n// 'disable.glowColor': null,\n// ...  \n}\n
"},{"location":"ui-style/#style-of-round-rectangle","title":"Style of Round-rectangle","text":"
{\n// $type: 'roundRectangle',\n\ncolor: 0xffffff,\n// alpha: 1,\n// origin:\n// originX: \n// originY:\nstrokeColor: 0xffffff,\n// strokeAlpha: 1,\n// strokeWidth: 2,\n// radius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n// width: 0,\n// height: 0,\n\n// Style override in active state\n// 'active.color': undefined,\n// 'active.alpha': undefined,\n// 'active.strokeColor': undefined,\n// 'active.strokeAlpha': undefined,\n// 'active.strokeWidth': undefined,\n// 'active.radius': undefined,\n// 'active.xxx': ...\n\n// Style override in hover state\n// 'hover.color': undefined,\n// 'hover.alpha': undefined,\n// 'hover.strokeColor': undefined,\n// 'hover.strokeAlpha': undefined,\n// 'hover.strokeWidth': undefined,\n// 'hover.radius': undefined,\n// 'hover.xxx': ...\n\n// Style override in disable state\n// 'disable.color': undefined,\n// 'disable.alpha': undefined,\n// 'disable.strokeColor': undefined,\n// 'disable.strokeAlpha': undefined,\n// 'disable.strokeWidth': undefined,\n// 'disable.radius': undefined,\n// 'disable.xxx': ...\n}\n
"},{"location":"ui-style/#style-of-bar-rectangle","title":"Style of bar-rectangle","text":"

Bar-rectangle = Line-progress

{\n// $type: 'bar',\n\nbarColor: 0xffffff,\n// easeDuration: 200,\n// ease: 'Quad',\n// rtl: false,\n\n// alpha: 1,\n// origin:\n// originX: \n// originY:\n// color: 0xffffff,\n// strokeColor: 0xffffff,\n// strokeAlpha: 1,\n// strokeWidth: 2,    \n// width: 0,\n// height: 0,\n\n// Style override in active state\n// 'active.barColor': undefined,\n// 'active.color': undefined,\n// 'active.alpha': undefined,\n// 'active.strokeColor': undefined,\n// 'active.strokeAlpha': undefined,\n// 'active.strokeWidth': undefined,\n// 'active.radius': undefined,\n// 'active.xxx': ...\n\n// Style override in hover state\n// 'hover.barColor': undefined,\n// 'hover.color': undefined,\n// 'hover.alpha': undefined,\n// 'hover.strokeColor': undefined,\n// 'hover.strokeAlpha': undefined,\n// 'hover.strokeWidth': undefined,\n// 'hover.radius': undefined,\n// 'hover.xxx': ...,\n// 'hover.bar: true,\n\n// Style override in disable state\n// 'disable.barColor': undefined,\n// 'disable.color': undefined,\n// 'disable.alpha': undefined,\n// 'disable.strokeColor': undefined,\n// 'disable.strokeAlpha': undefined,\n// 'disable.strokeWidth': undefined,\n// 'disable.radius': undefined,\n// 'disable.xxx': ...\n}\n
"},{"location":"ui-style/#style-of-text-game-object","title":"Style of Text game object","text":"
{\n// $type: 'text',\n\n// Normal text-style\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},\nalign: 'left',  // 'left'|'center'|'right'|'justify'\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\nmaxLines: 0,\nlineSpacing: 0,\nfixedWidth: 0,\nfixedHeight: 0,\nrtl: false,\ntestString: '|M\u00c9qgy',\nwordWrap: {\nwidth: null,\ncallback: null,\ncallbackScope: null,\nuseAdvancedWrap: false\n},\nmetrics: false,\n// metrics: {\n//     ascent: 0,\n//     descent: 0,\n//     fontSize: 0\n// },\n\n// tint: 0xffffff,\n// alpha: 1,\n// scale: 1,\n// flipX: false,\n// flipY: false,\n// origin:\n// originX: \n// originY:\n\n// Style override in active state\n'active.fontFamily': undefined,\n'active.fontSize': undefined,\n'active.fontStyle': undefined,\n'active.backgroundColor': undefined,\n'active.color': undefined,\n'active.fill': undefined,\n'active.stroke': undefined,\n'active.strokeThickness': undefined,\n\n// Style override in hover state\n'hover.fontFamily': undefined,\n'hover.fontSize': undefined,\n'hover.fontStyle': undefined,\n'hover.backgroundColor': undefined,\n'hover.color': undefined,\n'hover.fill': undefined,\n'hover.stroke': undefined,\n'hover.strokeThickness': undefined,\n\n// Style override in disable state\n'disable.fontFamily': undefined,\n'disable.fontSize': undefined,\n'disable.fontStyle': undefined,\n'disable.backgroundColor': undefined,\n'disable.color': undefined,\n'disable.fill': undefined,\n'disable.stroke': undefined,\n'disable.strokeThickness': undefined,\n}\n
"},{"location":"ui-style/#style-of-bbcodetext","title":"Style of BBCodeText","text":"
{\n$type: 'bbcodetext', // or 'bbcode'\n\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},\nalign: 'left',  // 'left'|'center'|'right'|'justify'\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\nmaxLines: 0,\nlineSpacing: 0,\nfixedWidth: 0,\nfixedHeight: 0,\nrtl: false,\ntestString: '|M\u00c9qgy',\nwrap: {\nmode: 'none'     // 0|'none'|1|'word'|2|'char'|'character'|3|'mix'\nwidth: null\n},\n// wordWrap: { width: 0 },   // Compatible with Text game object\nmetrics: false,\n// metrics: {\n//     ascent: 0,\n//     descent: 0,\n//     fontSize: 0\n// },\n\n// tint: 0xffffff,\n// alpha: 1,\n// scale: 1,\n// flipX: false,\n// flipY: false,\n// origin:\n// originX: \n// originY:\n}\n
"},{"location":"ui-style/#style-of-bitmaptext","title":"Style of BitmapText","text":"
{\n// $type: 'bitmaptext',  // or 'bitmap'\n\nfont: '',\nfontSize: undefined,\nalign: undefined,\ntint: undefined,\nletterSpacing: undefined,\nlineSpacing: undefined,\n\n// tint: 0xffffff,\n// alpha: 1,\n// scale: 1,\n// origin:\n// originX: \n// originY:\n\n// Style override in active state\n'active.font': undefined,\n'active.fontSize': undefined,\n'active.tint': undefined,\n'active.letterSpacing': undefined,\n'active.lineSpacing': undefined,\n\n// Style override in hover state\n'hover.font': undefined,\n'hover.fontSize': undefined,\n'hover.tint': undefined,\n'hover.letterSpacing': undefined,\n'hover.lineSpacing': undefined,\n\n// Style override in disable state\n'disable.font': undefined,\n'disable.fontSize': undefined,\n'disable.tint': undefined,\n'disable.letterSpacing': undefined,\n'disable.lineSpacing': undefined,\n}\n
"},{"location":"ui-style/#style-of-simplelabel","title":"Style of SimpleLabel","text":"
{\n$type: 'label',\n\n// width: undefined,\n// height: undefined,\n// origin:\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundStyle,\n\nicon: iconStyle,\n\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntext: testStyle,\n// wrapText: false,  // false|'word'|'char',\n// adjustTextFontSize: false,\n// expandTextWidth: false,\n// expandTextHeight: false,\n\naction: actionStyle,\n\n// squareFitAction: false,\n// actionMask: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n\nalign: undefined,  // 'left' | 'top' | 'right' | 'bottom' | 'center\n}    
  • background :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as background element.
    • null : Don't create any game object.
  • text :
    • Style of Text : Create Text, BBCodeText, BitmapText, SimpleLabel, or TextArea as text element.
    • null : Don't create any game object.
  • icon, action :
    • Style of Image : Create Image, Nine-slice, or Round-rectangle as image, action element.
    • null : Don't create any game object.
"},{"location":"ui-style/#style-of-textarea","title":"Style of TextArea","text":"

{\n$type: 'textarea',\n\nspace: { left: 0, right: 0, top: 0, bottom: 0, text: 0, },\n\n// width:\n// height:\n// origin:\n// originX:\n// originY:\n\nbackground: backgroundStyle,\n\ntext: textStyle,\n\n// textWidth: undefined,\n// textHeight: undefined,\n// textMask: false,\n// alwaysScrollable: false,\n\nslider: {\ntrack: backgroundStyle,\n\nthumb: backgroundStyle,\n\n// input: 'drag',\n// position: 'right',\n\n// hideUnscrollableSlider: false,\n// adaptThumbSize: false,\n// minThumbSize: undefined,\n},\n// slider: null,\n\n// scroller: {\n//     threshold: 10,\n//     slidingDeceleration: 5000,\n//     backDeceleration: 2000,\n//     pointerOutRelease: true,\n//     dragRate: 1,\n// },\n\nmouseWheelScroller: false,\n// mouseWheelScroller: {\n//     focus: true,\n//     speed: 0.1\n// },\n\nclampChildOY: false,\n}\n
- background : - Style of Background : Create round-rectangle, nine-slice, or image as background element. - null : Don't create any game object. - text : - Style of Text : Create text, BBCodeText, BitmapText, or SimpleLabel as text element. - null : Don't create any game object. - slider : - slider.track : - Style of Background : Create round-rectangle, nine-slice, or image as track element. - null : Don't create any game object. - slider.thumb : - Style of Background : Create round-rectangle, nine-slice, or image as thumb element. - null : Don't create any game object. - null, or false : Don't create any game object for slider.

"},{"location":"ui-style/#style-of-canvasinput","title":"Style of CanvasInput","text":"

CanvasInput

{\nwidth: undefined, height: undefined,\n\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null,\n\n// Style when focus\n// 'focus.color': ...\n// 'focus.color2': ...\n// 'focus.stroke': ...\n},\nfocusStyle: undefined,\n\ninnerBounds: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBY: undefined,\noffsetX: 0,\noffsetY: 0,\n\n// Style when cursor move on\n// 'cursor.color': ...\n// 'cursor.backgroundColor': ...\n// 'cursor.xxx': ...\n},\ncursorStyle: undefined,\n}\n
"},{"location":"ui-style/#style-of-triangle","title":"Style of triangle","text":"
{\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n
"},{"location":"ui-tabpages/","title":"Tab pages","text":""},{"location":"ui-tabpages/#introduction","title":"Introduction","text":"

A container with tabs and pages, only current page is visible.

  • Author: Rex
  • Game object
"},{"location":"ui-tabpages/#live-demos","title":"Live demos","text":"
  • Tabpage
"},{"location":"ui-tabpages/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-tabpages/#install-plugin","title":"Install plugin","text":""},{"location":"ui-tabpages/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add tab-pages object
    var tabPages = scene.rexUI.add.tabPages(config);\n
"},{"location":"ui-tabpages/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add tab-pages object
    var tabPages = scene.rexUI.add.tabPages(config);\n
"},{"location":"ui-tabpages/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { TabPages } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add tab-pages object
    var tabPages = new TabPages(scene, config);\nscene.add.existing(tabPages);\n
"},{"location":"ui-tabpages/#add-tab-pages-object","title":"Add tab-pages object","text":"
var tabPages = scene.rexUI.add.tabPages({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// background: backgroundGameObject,\n\ntabsPosition: 'top',\n// tabPosition: 'top',\n\nwrapTabs: false,\n\ntabs: {\n// width:\n// height:\n// rtl:\n\n// background: backgroundGameObject,        \nalign:\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n},\nspace: { left: 0, right:0, top:0, bottom:0, item:0 }\n},\n\npages: {\nspace: { left: 0, right:0, top:0, bottom:0 },\nfadeIn: 0,\n},\n\nexpand: {\ntabs: false,\n},\n\nalign: {\ntabs: 'left',\n},\n\n// space: { left:0, right:0, top:0, bottom:0, item:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • tabsPosition (or tabPosition) : Put tabs at top, bottom, left, right of pages.
    • 'top', 'bottom', 'left', 'right' : Default value is 'top'.
  • wrapTabs :
    • false : Uses Buttons as Tabs, default behavior.
    • true :
      • Using FixWidthButtons as Tabs, if tabPosition is 'top' or 'bottom'.
      • Using Buttons as Tabs, if tabPosition is 'left' or 'right'
  • tabs : Configuration of tabs, which is a buttons game object.
    • tabs.width, tabs.height : Minimum width, minimum height of tabs, to preserve space if tabs is empty, optional.
    • tabs.rtl :
      • true : Layout buttons from right to left.
      • false : Layout buttons from left to right. Default behavior.
    • tabs.background : Game object of background, optional. This background game object will be resized to fit the size of grid table.
    • tabs.space :
      • tabs.space.top, tabs.space.bottom, tabs.space.left, tabs.space.right : Padding around bottons.
      • tabs.space.item : Space between 2 button game objects.
    • tabs.click: Configuration of button clicking.
      • tabs.click.mode :
        • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
        • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
      • tabs.click.clickInterval : Interval between 2 'click' events, in ms.
  • pages : Configuration of pages
    • pages.space : Pads spaces.
      • pages.space.left, pages.space.right, pages.space.top, pages.space.bottom : Space of bounds.
    • pages.fadeIn : Fade-in duration of current page.
      • 0 : No fade-in effect. Default behavior.
  • expand :
    • expand.tabs : Set true to expand width/height of tabs. Default value is false.
  • align :
    • align.tabs :
      • 'left'. 'right', 'center' : Align tabs to left/right/center side when tabPosition is 'top' or 'bottom'.
      • 'top'. 'bottom', 'center' : Align tabs to top/bottom/center side when tabPosition is 'left' or 'right'.
  • space :
    • An object: Padding of button game objects.
      • space.top, space.bottom, space.left, space.right : Padding around bottons.
      • space.item : Space between tabs and pages.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-tabpages/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTabPages extends RexPlugins.UI.TabPages {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var tabPages = new MyTabPages(scene, config);\n
"},{"location":"ui-tabpages/#add-page","title":"Add page","text":"

Add a tab/page to last of tabs/pages.

tabPages.addPage(key, tabGameObject, pageGameObject).layout();\n

or

tabPages.addPage({\n// key: undefined,\ntab: tabGameObject,\npage: pageGameObject\n}).layout();\n
  • key : Unique string name of this page.
    • undefined : Create an UUID for key.
  • tab : A game object, will put it into tabs.
  • page : A game object, will put it into pages.

Note

Invoke tabPages.layout() after adding pages.

"},{"location":"ui-tabpages/#swap-to-page","title":"Swap to page","text":"
  • Swap to related page when clicking tab.
  • Swap to page by key/index
    tabPages.swapPage(key);\n
    tabPages.swapPage(index);\n
    • key : Unique string name of the page.
    • index : Index number in tabs.
  • Swap to first page
    tabPages.swapFirstPage();\n
  • Swap to last page
    tabPages.swapLastPage();\n
  • Swap page without fade-in transition
    tabPages.swapPage(key, 0);\n
    tabPages.swapPage(index, 0);\n
    tabPages.swapFirstPage(0);\n
    tabPages.swapLastPage(0);\n
"},{"location":"ui-tabpages/#remove-page","title":"Remove page","text":"
  • Remove page
    tabPages.removePage(key);\n
    tabPages.removePage(index);\n
  • Remove and destroy page
    tabPages.removePage(key, true);\n
    tabPages.removePage(index, true);\n
  • Remove all pages
    tabPages.removeAllPages();\n
  • Remove and destroy all pages
    tabPages.removeAllPages(true);\n
"},{"location":"ui-tabpages/#change-tabs-position","title":"Change tabs position","text":"
tabPages.setTabPosition(position);\n
  • position : 'top', 'bottom', 'left', 'right'
"},{"location":"ui-tabpages/#padding-of-tabs","title":"Padding of tabs","text":"
  • Change padding
    tabPages.setTabsPadding(key, value).layout();\n
    or
    tabPages.setTabsPadding({\nleft: leftPadding, right: rightPadding,\ntop: topPadding,\nbottom: bottomPadding\n}).layout();\n
    • key : 'left', 'right', 'top', 'bottom', 'item'
  • Get padding
    var value = tabPages.getTabsPadding(key);\n
    • key : 'left', 'right', 'top', 'bottom', 'item'
"},{"location":"ui-tabpages/#get-element","title":"Get element","text":"
  • Get element
    • Pages
      var gameObject = tabPages.getElement('pages');\n
    • Tabs, a buttons
      var gameObject = tabPages.getElement('tabs');\n
    • Page by key/index
      var gameObject = tabPages.getPage(key);\n
      var gameObject = tabPages.getPage(index);\n
      • key : Unique string name of the page.
      • index : Index number in tabs.
    • Tab by key/index
      var gameObjects = tabPages.getTab(key);\n
      var gameObjects = tabPages.getTab(index);\n
      • key : Unique string name of the page.
      • index : Index number in tabs.
  • Get by name
    var gameObject = tabPages.getElement('#' + name);\n// var gameObject = pages.getElement('#' + name, recursive);\n
    or
    var gameObject = tabPages.getByName(name);\n// var gameObject = tabPages.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-tabpages/#other-properties","title":"Other properties","text":"

See sizer, base sizer object, container-lite, Pages, Buttons

"},{"location":"ui-tabpages/#events","title":"Events","text":"
  • When swapping to a page by clicking tab, or tabPages.swapPage(key)
    pages.on('tab.focus', function(tab, key) {\n// ...\n}, scope);\npages.on('page.focus', function(page, key) {\n// ...\n}, scope);\n
    pages.on('tab.blur', function(tab, key) {\n// ...\n}, scope);\npages.on('page.blur', function(page, key) {\n// ...\n}, scope);    
    • tab : Game object of tab.
    • page : Game object of page.
    • key : Unique string name of the page.
"},{"location":"ui-tabs/","title":"Tabs","text":""},{"location":"ui-tabs/#introduction","title":"Introduction","text":"

A container with 4 groups of buttons around a center panel.

  • Author: Rex
  • Game object
"},{"location":"ui-tabs/#live-demos","title":"Live demos","text":"
  • Tabs
  • Expand buttons
  • Tabs-table
"},{"location":"ui-tabs/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-tabs/#install-plugin","title":"Install plugin","text":""},{"location":"ui-tabs/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add tabs object
    var tabs = scene.rexUI.add.tabs(config);\n
"},{"location":"ui-tabs/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add tabs object
    var tabs = scene.rexUI.add.tabs(config);\n
"},{"location":"ui-tabs/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Tabs } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add tabs object
    var tabs = new Tabs(scene, config);\nscene.add.existing(tabs);\n
"},{"location":"ui-tabs/#add-tabs-object","title":"Add Tabs object","text":"
var tabs = scene.rexUI.add.tabs({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\nbackground: backgroundGameObject,\npanel: panelGameObject,\n\nleftButtons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\nrightButtons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\ntopButtons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\nbottomButtons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\nleftButtonsBackground: leftButtonsBackgroundGameObject,\nrightButtonsBackground: rightButtonsBackgroundGameObject,\ntopButtonsBackground: topButtonsBackgroundGameObject,\nbottomButtonsBackground: bottomButtonsBackgroundGameObject,\n\nexpand: {\npanel: false,\nleftButtons: false,\nrightButtons: false,\ntopButtons: false,\nbottomButtons: false,\n},\n\nalign: {\nleftButtons: 'top',\nrightButtons: 'top',\ntopButtons: 'left',\nbottomButtons: 'left',\n},\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nleftButtonsOffset: 0,\nrightButtonsOffset: 0,\ntopButtonsOffset: 0,\nbottomButtonsOffset: 0,\n\nleftButton: 0,\nrightButton: 0,\ntopButton: 0,\nbottomButton: 0\n},\n\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n}\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of grid table.
  • panel : Game object of center panel.
  • leftButtons, rightButtons, topButtons, bottomButtons : Array of button game object.
    • [] : Assign an empty array if user will add button later.
  • leftButtonsBackground, rightButtonsBackground, topButtonsBackground, bottomButtonsBackground : Game object of leftButtons' background, rightButtons' background, topButtons' background, bottomButtons' background, optional.
  • expand : Expand size of panel or buttons
    • expand.panel : Expand size of panel. Default value is false.
    • expand.leftButtons, expand.rightButtons : Expand height of leftButtons, rightButtons. Default value is false.
    • expand.topButtons, expand.bottomButtons : Expand width of topButtons, bottomButtons. Default value is false.
  • align : Alignment of buttons
    • align.leftButtons, align.rightButtons : 'top', 'bottom', or 'center'. Default value is 'top'.
    • align.topButtons, align.bottomButtons : 'left', 'right', or 'center'. Default value is 'left'.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds
    • space.leftButtonsOffset, space.rightButtonsOffset : Top offset of buttons group.
    • space.topButtonsOffset, space.bottomButtonsOffset : Left offset of buttons group.
    • space.leftButton, space.rightButton, space.topButton, space.bottomButton : Space between 2 button game objects.
  • click: Configuration of button clicking.
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-tabs/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTabs extends RexPlugins.UI.Tabs {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var tabs = new MyTabs(scene, config);\n
"},{"location":"ui-tabs/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

tabs.layout();\n

See also - dirty

"},{"location":"ui-tabs/#other-properties","title":"Other properties","text":"

See grid sizer object, base-sizer object.

"},{"location":"ui-tabs/#events","title":"Events","text":"
  • Click button
    tabs.on('button.click', function(button, groupName, index, pointer) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
  • Pointer-over button
    tabs.on('button.over', function(button, groupName, index, pointer) {\n// ...\n}, scope);\n
    • button : Triggered button game object
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
  • Pointer-out button
    tabs.on('button.out', function(button, groupName, index, pointer) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
  • Enable button's input
    tabs.on('button.enable', function(button, groupName, index) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : Index of triggered button game object.
  • Disable button's input
    tabs.on('button.disalbe', function(button, groupName, index) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : Index of triggered button game object.
"},{"location":"ui-tabs/#emit-button-click-event","title":"Emit button click event","text":"
  • Emit button click event in a given group
    tabs.emitButtonClick(groupName, index);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, or a button game object.
  • Emit left/right/top/bottom button click event
    tabs.emitLeftButtonClick(index);\ntabs.emitRightButtonClick(index);\ntabs.emitTopButtonClick(index);\ntabs.emitBottomButtonClick(index);\n
    • index : A number index, or a button game object.
"},{"location":"ui-tabs/#enabledisable-input-of-button","title":"Enable/disable input of button","text":"
  • Enable button input in a given group
    tabs.setButtonEnable(groupName, index);\n// tabs.setButtonEnable(groupName, index, true);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, or a button game object.
  • Enable left/right/top/bottom button
    tabs.setLeftButtonEnable(index);\ntabs.setRightButtonEnable(index);\ntabs.setTopButtonEnable(index);\ntabs.setBottomButtonEnable(index);\n
    • index : A number index, or a button game object.
  • Disable button input in a given group
    tabs.setButtonEnable(groupName, index, false);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, or a button game object.
  • Disable choice/action/toolbar/left-toolbar button's input
    tabs.setLeftButtonEnable(index, false);\ntabs.setRightButtonEnable(index, false);\ntabs.setTopButtonEnable(index, false);\ntabs.setBottomButtonEnable(index, false);\n
    • index : A number index, or a button game object.
  • Toggle button input in a given group
    tabs.toggleButtonEnable(groupName, index);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, or a button game object.
  • Toggle choice/action/toolbar/left-toolbar button's input
    tabs.toggleLeftButtonEnable(index);\ntabs.toggleRightButtonEnable(index);\ntabs.toggleTopButtonEnable(index);\ntabs.toggleBottomButtonEnable(index);\n
    • index : A number index, or a button game object.
  • Get button input enable in a given group
    var enabled = tabs.getButtonEnable(groupName, index);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, or a button game object.
  • Get choice/action/toolbar/left-toolbar button's input enable
    var enabled = tabs.getLeftButtonEnable(index);\nvar enabled = tabs.getRightButtonEnable(index);\nvar enabled = tabs.getTopButtonEnable(index);\nvar enabled = tabs.getBottomButtonEnable(index);\n
    • index : A number index, or a button game object.
"},{"location":"ui-tabs/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = tabs.getElement('background');\n
    • Panel game object
      var panel = tabs.getElement('panel');\n
    • Buttons
      • Button game object in a group
        var buttons = tabs.getButton(groupName, index)\n
        • groupName : 'left', 'right', 'top', or 'bottom'.
        • index : A number index.
      • Left button game object
        var buttons = tabs.getElement('leftButtons');\n
        or
        var button = tabs.getLeftButton(index);\n
        or
        var buttons = tabs.getElement('leftButtons[0]');\n
        • First button of left buttons.
      • Right button game object
        var buttons = tabs.getElement('rightButtons');\n
        or
        var button = tabs.getRightButton(index);\n
        or
        var buttons = tabs.getElement('rightButtons[0]');\n
        • First button of right buttons.
      • Top button game object
        var buttons = tabs.getElement('topButtons');\n
        or
        var button = tabs.getTopButton(index);\n
        or
        var buttons = tabs.getElement('topButtons[0]');\n
        • First button of top buttons.
      • Bottom button game object
        var buttons = tabs.getElement('bottomButtons');\n
        or
        var button = tabs.getBottomButton(index);\n
        or
        var buttons = tabs.getElement('bottomButtons[0]');\n
        • First button of bottom buttons.
  • Get by name
    var gameObject = tabs.getElement('#' + name);\n// var gameObject = tabs.getElement('#' + name, recursive);\n
    or
    var gameObject = tabs.getByName(name);\n// var gameObject = tabs.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-tabs/#add-button","title":"Add button","text":"
  • Add button in a group
    tabs.addButton(groupName, gameObject);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • gameObject : A game object, or an array of game objects.
  • Add left/right/top/bottom button
    tabs.addLeftButton(gameObject);\ntabs.addRightButton(gameObject);\ntabs.addTopButton(gameObject);\ntabs.addBottomButton(gameObject);\n
    • gameObject : A game object, or an array of game objects.
"},{"location":"ui-tabs/#remove-button","title":"Remove button","text":"
  • Remove a button from a group
    tabls.removeButton(groupName, index, destroyChild);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, a string name, or a button game object.
    • destroyChild : Set true to destroy button game object.
  • Remove left/right/top/bottom button
    tabs.removeLeftButton(index, destroyChild);\ntabs.removeRightButton(index, destroyChild);\ntabs.removeTopButton(index, destroyChild);\ntabs.removeBottomButton(index, destroyChild);\n
    • index : A number index, a string name, or a button game object.
    • destroyChild : Set true to destroy button game object.
  • Remove all buttons of a group
    tabls.clearButtons(groupName, destroyChild);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • destroyChild : Set true to destroy button game objects.
  • Remove all left/right/top/bottom buttons
    tabs.clearLeftButtons(destroyChild);\ntabs.clearRightButtons(destroyChild);\ntabs.clearTopButtons(destroyChild);\ntabs.clearBottomButtosn(destroyChild);\n
    • destroyChild : Set true to destroy button game objects.
"},{"location":"ui-tabs/#showhide-button","title":"Show/hide button","text":"

Hidden elements won't be counted when layouting. Call tabs.layout(), or topSizer.layout() after show/hide any button.

  • Show button in a group
    tabs.showButton(groupName, index);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, a string name, or a button game object.
  • Show left/right/top/bottom button
    tabs.showLeftButton(index);\ntabs.showRightButton(index);\ntabs.showTopButton(index);\ntabs.showBottomButton(index);\n
    • index : A number index, a string name, or a button game object.
  • Hide button in a group
    tabs.hideButton(groupName, index);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, a string name, or a button game object.
  • Hide left/right/top/bottom button.
    tabs.hideLeftButton(index);\ntabs.hideRightButton(index);\ntabs.hideTopButton(index);\ntabs.hideBottomButton(index);\n
    • index : A number index, a string name, or a button game object.
"},{"location":"ui-tabs/#for-each-button","title":"For each button","text":"
  • For each button in a group
    var enabled = tabs.forEachButton(groupName, index);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, or a button game object.
  • For each button in left/right/top/bottom group
    tabs.forEachLeftButton(callback, scope);\ntabs.forEachRightButton(callback, scope);\ntabs.forEachTopButton(callback, scope);\ntabs.forEachBottomButton(callback, scope);\n
    • callback :
      function(button, index, buttons) {\n// ...\n}\n
"},{"location":"ui-text-helper/","title":"Ui text helper","text":""},{"location":"ui-text-helper/#introduction","title":"Introduction","text":"

Some helper methods for Text object, bbcode text object, tag text object, Bitmap text object game objects

  • Author: Rex
  • Methods
"},{"location":"ui-text-helper/#live-demos","title":"Live demos","text":"
  • Wrap-expand-text
  • Wrap-expand-bitmaptext
  • Fontsize-expand-text
  • Resize Fontsize-expand-text
"},{"location":"ui-text-helper/#usage","title":"Usage","text":"
  • Wrap-expand-text
  • Fontsize-expand-text
"},{"location":"ui-text-helper/#wrap-expand-text","title":"Wrap expand text","text":"
sizer\n.add(\nthis.rexUI.wrapExpandText(this.add.text(0, 0, content)),\n{\n// proportion: 1,\n// expand: true\n}\n)\n
  • proportion: 1 or/and expand: true : Expand width of text
"},{"location":"ui-text-helper/#fontsize-expand-text","title":"Fontsize expand text","text":"
sizer\n.add(\nthis.rexUI.fontSizeExpandText(this.add.text(0, 0, content)),\n{\n// proportion: 1,\n// expand: true\n}\n)\n
  • proportion: 1 or/and expand: true : Expand width of text
"},{"location":"ui-textarea/","title":"Text area","text":""},{"location":"ui-textarea/#introduction","title":"Introduction","text":"

A container with a text, slider, and scroller.

  • Author: Rex
  • Game object
"},{"location":"ui-textarea/#live-demos","title":"Live demos","text":"
  • Text-area
  • Bitmap text
  • Hide unscrollable slider
  • Append text
  • Scroll to line
  • Modal dialog
  • Min height
"},{"location":"ui-textarea/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-textarea/#install-plugin","title":"Install plugin","text":""},{"location":"ui-textarea/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add text-area object
    var textArea = scene.rexUI.add.textArea(config);\n
"},{"location":"ui-textarea/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text-area object
    var textArea = scene.rexUI.add.textArea(config);\n
"},{"location":"ui-textarea/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { TextArea } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add text-area object
    var textArea = new TextArea(scene, config);\nscene.add.existing(textArea);\n
"},{"location":"ui-textarea/#add-text-area-object","title":"Add text-area object","text":"
var textArea = scene.rexUI.add.textArea({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\nbackground: backgroundGameObject,\n\ntext: textGameObject,\n// textWidth: undefined,\n// textHeight: undefined,\n// textMask: false,\n// alwaysScrollable: false,\n\nslider: {\n// background: sliderBackgroundGameObject,\ntrack: trackGameObject,\n/* \n        track: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\n\n// indicator: indicatorGameObject,\nthumb: thumbGameObject,\n/* \n        thumb: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\n// input: 'drag',\n// position: 'right',\n\n// hideUnscrollableSlider: false,\n// adaptThumbSize: false,\n// minThumbSize: undefined,\n\n// buttons: {\n//     top: topButtonGameObject, bottom: bottomButtonGameObject,\n//     left: leftButtonGameObject, right: rightButtonGameObject,\n//     step: 0.01,\n// }\n},\n\n// scroller: {\n//     threshold: 10,\n//     slidingDeceleration: 5000,\n//     backDeceleration: 2000,\n//     pointerOutRelease: true,\n//     rectBoundsInteractive: true,\n//     dragRate: 1,\n// },\n\nmouseWheelScroller: false,\n// mouseWheelScroller: {\n//     focus: true,\n//     speed: 0.1\n// },\n\nclampChildOY: false,\n\nheader: headerGameObject,\nfooter: footerGameObject,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\ntext: 0,\n// text: {\n//    top: 0,\n//    bottom: 0,\n//    left: 0,\n//    right: 0,\n//},\n\nslider: 0,\n// slider: {\n//     top: 0,\n//     bottom: 0,\n//     left: 0,\n//     right: 0,\n// },\n\nheader: 0,\nfooter: 0,\n},\n\nexpand: {\nheader: true,\nfooter: true,\n},\n\nalign: {\nheader: 'center',\nfooter: 'center',\n},\n\ncontent: '',\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of text area.
  • text : Text object, bbcode text object, tag text object, or bitmap text object
  • textWidth : Fixed width of text game object. Set undefined to ignore this feature.
  • textHeight : Fixed height of text game object. Set undefined to ignore this feature.
  • textMask :
    • false : Crop text game object. Default behavior if text game object has setCrop method.
    • true : Apply mask on text to crop text game object. Default behavior if text game object does not have setCrop method (ex. bitmaptext game object).
  • slider : Componments of slider, optional.
    • slider.background : Game object of slider background, optional.
    • slider.track : Game object of track.
    • slider.thumb : Game object of thumb.
    • slider.input :
      • 'pan', 'drag', or 0 : Control slider by panning/dragging thumb game object. Default setting.
      • 'click', or 1 : Control slider by touching track game object.
      • 'none', or -1 : Disable sider controlling.
    • slider.position : Position of this slider.
      • 0, 'right', 'bottom' : Slider at right/bottom side. Default value.
      • 1, 'left', 'top' : Slider at left/top side.
    • slider.hideUnscrollableSlider :
      • false : Slider is always visible no matter it is scrollable or not. Default behavior.
      • true : Set slider to invisible if it is unscrollable.
    • slider.adaptThumbSize :
      • false : Don't adjust height/width of thumb. Default behavior.
      • true : Adjust height/width of thumb according to ratio of visible child.
        • Minimum height/width of thumb = slider.minThumbSize. If content is larger then a page.
        • Maximum height/width of thumb = height/width of slider.track. If content is less then a page.
    • slider.minThumbSize : Minimum height/width of thumb used in slider.adaptThumbSize mode.
    • slider.buttons : Press button to scroll content in each tick.
      • slider.buttons.top, slider.buttons.bottom : Top and bottom buttons.
      • slider.buttons.left, slider.buttons.right : Left and right buttons
      • slider.buttons.step : Scrolling step in each tick. Default value is 0.01.
    • Set to false to skip creating slider.
  • scroller : Configuration of scroller behavior.
    • scroller.threshold : Minimal movement to scroll. Set 0 to scroll immediately.
    • scroller.slidingDeceleration : Deceleration of slow down when dragging released.
      • Set false to disable it.
    • scroller.backDeceleration : Deceleration of pull back when out of bounds.
      • Set false to disable it.
    • scroller.pointerOutRelease : Set to true to release input control when pointer out of gameObject.
    • scroller.rectBoundsInteractive :
      • false : Detect scrolling by game object's touch input.
      • true : Detect scrolling by rectangle bounds of game object. Default behavior.
    • scroller.dragRate : Rate of dragging distance/dragging speed. Default value is 1.
    • Set to false to skip creating scroller.
  • mouseWheelScroller : Configuration of mouse-wheel-scroller behavior.
    • mouseWheelScroller.focus :
      • false, or 0 : Without checking if cursor is over game object or not.
      • true, or 1 : Cursor is inside the rectangle bounds of game object. Default behavior.
      • 2 : Cursor is over game object.
    • mouseWheelScroller.speed : Scrolling speed, default value is 0.1.
    • Set to false to skip creating mouse-wheel-scroller. Default behavior.
  • clampChildOY : Set true to clamp scrolling.
  • alwaysScrollable :
    • false : Can't scroll if content is less then 1 page. Default behavior.
    • true : Can scroll in all cases
  • header : Game object of header, optional.
  • footer : Game object of footer, optional.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.text :
      • A number: Space between text object and slider object.
      • An object: Padding of text object.
        • space.text.top, space.text.bottom : Top, bottom padding space of text object.
        • space.text.right : Space between text object and slider object.
    • space.slider :
      • 0 : No space around slider.
      • space.slider.left, space.slider.right, space.slider.top, space.slider.bottom : Space around slider.
    • space.header : Space between header and text object.
    • space.footer : Space between footer and text object.
  • expand : Expand width or height of element
    • expand.header : Set true to expand width or height of header game object.
    • expand.footer : Set true to expand width or height of footer game object.
  • align : Align element
    • align.header
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • align.footer
  • content : Content of this text area.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-textarea/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTextArea extends RexPlugins.UI.TextArea {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var textArea = new MyTextArea(scene, config);\n
"},{"location":"ui-textarea/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

textArea.layout();\n

See also - dirty

"},{"location":"ui-textarea/#content","title":"Content","text":"
  • Set
    textArea.setText(text);\n
  • Append
    textArea.appendText(text);\n
  • Get
    var text = textArea.text;\n
"},{"location":"ui-textarea/#scroll-content","title":"Scroll content","text":"
  • Scroll down lines
    textArea.scrollLine(lineCount);\n
  • Set
    textArea.childOY = oy;\n// textArea.setChildOY(oy);\n
  • Set and clamp
    textArea.setChildOY(oy, true);\n
  • Add
    textArea.addChildOY(oy);\n
  • Add and clamp
    textArea.addChildOY(oy, true);\n
  • Get
    var childOY = textArea.childOY;\n
  • Top OY
    var topOY = textArea.topChildOY;\n
  • Bottom OY
    var bottomOY = textArea.bottomChildOY;\n
  • Is overflow (height of content is larger than display height)
    var isOverflow = textArea.isOverflow;\n
"},{"location":"ui-textarea/#scroll-by-percentage","title":"Scroll by percentage","text":"
  • Set
    textArea.t = t;  // t: 0~1\n// textArea.setT(t);  \n
  • Set and clamp
    textArea.setT(t, true);\n
  • Get
    var t = textArea.t;\n
"},{"location":"ui-textarea/#scroll-to-topbottom","title":"Scroll to top/bottom","text":"
  • Scroll to top
    textArea.scrollToTop();\n
    • Equal to textArea.t = 0;
  • Scroll to bottom
    textArea.scrollToBottom();\n
    • Equal to textArea.t = 1;
"},{"location":"ui-textarea/#scroll-to-line","title":"Scroll to line","text":"
  • Scroll to next line
    textArea.scrollToNextLine();\n
  • Scroll to next n line
    textArea.scrollToNextLine(n);\n
  • Scroll to line
    textArea.scrollToLine(lineIndex);\n
  • Get current line index
    var lineIndex = textArea.lineIndex;\n
"},{"location":"ui-textarea/#enabledisable-scrolling","title":"Enable/disable scrolling","text":"
  • Slider
    • Set enable state
      textArea.setSliderEnable(enabled);\n
      or
      textArea.sliderEnable = enabled;\n
    • Get enable state
      var enable = textArea.sliderEnable;\n
  • Scroller
    • Set enable state
      textArea.setScrollerEnable(enabled);\n
      or
      textArea.scrollerEnable = enabled;\n
    • Get enable state
      var enable = textArea.scrollerEnable;\n
  • Mouse-Wheel-Scroller
    • Set enable state
      textArea.setMouseWheelScrollerEnable(enabled);\n
      or
      textArea.mouseWheelScrollerEnable = enabled;\n
    • Get enable state
      var enable = textArea.mouseWheelScrollerEnable;\n
"},{"location":"ui-textarea/#event","title":"Event","text":"
  • Scroll
    textArea.on('scroll', function(textArea) {\n// ...\n})\n
  • Slider
    • Slider drag start
      textArea.getElement('slider').on('inputstart', function(panel) {\n// ...\n})\n
    • Slider drag end
      textArea.getElement('slider').on('inputend', function(panel) {\n// ...\n})\n
  • Scroller
    • Scroller drag start
      textArea.getElement('scroller').on('dragstart', function(panel) {\n// ...\n})\n
    • Scroller drag end
      textArea.getElement('scroller').on('dragend', function(panel) {\n// ...\n})\n
"},{"location":"ui-textarea/#lines-count","title":"Lines count","text":"
var linesCount = textArea.linesCount;\n
"},{"location":"ui-textarea/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-textarea/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = textArea.getElement('background');\n
    • Text game object
      var text = textArea.getElement('text');\n
    • Slider
      • Track
        var track = textArea.getElement('slider.track');\n
      • Thumb
        var thumb = textArea.getElement('slider.thumb');\n
    • Scroller
      var scroller = textArea.getElement('scroller');\n
  • Get by name
    var gameObject = textArea.getElement('#' + name);\n// var gameObject = textArea.getElement('#' + name, recursive);\n
    or
    var gameObject = textArea.getByName(name);\n// var gameObject = textArea.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-textareainput/","title":"Text area input","text":""},{"location":"ui-textareainput/#introduction","title":"Introduction","text":"

A container with a canvasInput, and slider.

  • Author: Rex
  • Game object
"},{"location":"ui-textareainput/#live-demos","title":"Live demos","text":"
  • Text-area
"},{"location":"ui-textareainput/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-textareainput/#install-plugin","title":"Install plugin","text":""},{"location":"ui-textareainput/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add text-area-input object
    var textAreaInput = scene.rexUI.add.textAreaInput(config);\n
"},{"location":"ui-textareainput/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text-area-input object
    var textAreaInput = scene.rexUI.add.textAreaInput(config);\n
"},{"location":"ui-textareainput/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { TextAreaInput } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add text-area-input object
    var textAreaInput = new TextAreaInput(scene, config);\nscene.add.existing(textAreaInput);\n
"},{"location":"ui-textareainput/#add-text-area-input-object","title":"Add text-area-input object","text":"
var textAreaInput = scene.rexUI.add.textAreaInput({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\nbackground: backgroundGameObject,\n\ntext: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null,\n\n// Style when focus\n// 'focus.color': ...\n// 'focus.color2': ...\n// 'focus.stroke': ...\n},\nfocusStyle: undefined,\n\ninnerBounds: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBY: undefined,\noffsetX: 0,\noffsetY: 0,\n\n// Style when cursor move on\n// 'cursor.color': ...\n// 'cursor.backgroundColor': ...\n// 'cursor.xxx': ...\n},\ncursorStyle: undefined,\n\nchildrenInteractive: false,\n\ntext: '',\n\nwrap: {\nlineHeight: undefined,\nuseDefaultLineHeight: true,\nmaxLines: 1,\nwrapWidth: undefined,\nletterSpacing: 0,\nhAlign: 0,\nvAlign: 'center',  // For single line text input\nwrapMode: 'char',  // For single line text input\n},\n\ntextArea: true,\n\n// Parameters of hidden-text-editor   \n// inputType: 'text',  // 'text'|'password'|'textarea'|...                \n\n// readOnly: false,\n// maxLength: undefined,\n// minLength: undefined,\n// selectAll: false,\n\n// enterClose: true,\n\n// Callbacks\n// onOpen: function (textObject, hiddenInputText) {\n// },\n\n// onClose: function (textObject, hiddenInputText) {\n// },\n\n// onUpdate: function (text, textObject, hiddenInputText) {\n//     return text;\n// },\n\n// onAddChar: function(child, index, canvasInput) {\n//    child.modifyStyle({...})\n// },\n\n// onCursorOut: function(child, cursorIndex, canvasInput) {\n//     child.modifyStyle({\n//         \n//     });\n// },\n\n// onCursorIn: function(child, cursorIndex, canvasInput) {\n//     child.modifyStyle({\n//         \n//     });\n// },\n\n// parseTextCallback: function(text) {\n//     return text;\n// }.        \n},\n// alwaysScrollable: false,\n\nslider: {\n// background: sliderBackgroundGameObject,\ntrack: trackGameObject,\n/* \n        track: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\n\n// indicator: indicatorGameObject,\nthumb: thumbGameObject,\n/* \n        thumb: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\n// input: 'drag',\n// position: 'right',\n\n// hideUnscrollableSlider: false,\n// adaptThumbSize: false,\n// minThumbSize: undefined,\n\n// buttons: {\n//     top: topButtonGameObject, bottom: bottomButtonGameObject,\n//     left: leftButtonGameObject, right: rightButtonGameObject,\n//     step: 0.01,\n// }\n},\n\n// scroller: false,  // No scrollor support\n\nmouseWheelScroller: false,\n// mouseWheelScroller: {\n//     focus: true,\n//     speed: 0.1\n// },\n\nclampChildOY: false,\n\nheader: headerGameObject,\nfooter: footerGameObject,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\ntext: 0,\n// text: {\n//    top: 0,\n//    bottom: 0,\n//    left: 0,\n//    right: 0,\n//},\n\nslider: 0,\n// slider: {\n//     top: 0,\n//     bottom: 0,\n//     left: 0,\n//     right: 0,\n// },\n\nheader: 0,\nfooter: 0,\n},\n\nexpand: {\nheader: true,\nfooter: true,\n},\n\nalign: {\nheader: 'center',\nfooter: 'center',\n},\n\ncontent: '',\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of text area.
  • text : Configuration of CanvasInput, or a CanvasInput game object.
  • slider : Componments of slider, optional.
    • slider.background : Game object of slider background, optional.
    • slider.track : Game object of track.
    • slider.thumb : Game object of thumb.
    • slider.input :
      • 'pan', 'drag', or 0 : Control slider by panning/dragging thumb game object. Default setting.
      • 'click', or 1 : Control slider by touching track game object.
      • 'none', or -1 : Disable sider controlling.
    • slider.position : Position of this slider.
      • 0, 'right', 'bottom' : Slider at right/bottom side. Default value.
      • 1, 'left', 'top' : Slider at left/top side.
    • slider.hideUnscrollableSlider :
      • false : Slider is always visible no matter it is scrollable or not. Default behavior.
      • true : Set slider to invisible if it is unscrollable.
    • slider.adaptThumbSize :
      • false : Don't adjust height/width of thumb. Default behavior.
      • true : Adjust height/width of thumb according to ratio of visible child.
        • Minimum height/width of thumb = slider.minThumbSize. If content is larger then a page.
        • Maximum height/width of thumb = height/width of slider.track. If content is less then a page.
    • slider.minThumbSize : Minimum height/width of thumb used in slider.adaptThumbSize mode.
    • slider.buttons : Press button to scroll content in each tick.
      • slider.buttons.top, slider.buttons.bottom : Top and bottom buttons.
      • slider.buttons.left, slider.buttons.right : Left and right buttons
      • slider.buttons.step : Scrolling step in each tick. Default value is 0.01.
    • Set to false to skip creating slider.
  • scroller : No scroller supported (false).
  • mouseWheelScroller : Configuration of mouse-wheel-scroller behavior.
    • mouseWheelScroller.focus :
      • true : Only scrolling when cursor is over textAreaInput. Default behavior.
      • false : Scrolling without checking cursor.
    • mouseWheelScroller.speed : Scrolling speed, default value is 0.1.
    • Set to false to skip creating mouse-wheel-scroller. Default behavior.
  • clampChildOY : Set true to clamp scrolling.
  • alwaysScrollable :
    • false : Can't scroll if content is less then 1 page. Default behavior.
    • true : Can scroll in all cases
  • header : Game object of header, optional.
  • footer : Game object of footer, optional.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.text :
      • A number: Space between text object and slider object.
      • An object: Padding of text object.
        • space.text.top, space.text.bottom : Top, bottom padding space of text object.
        • space.text.right : Space between text object and slider object.
    • space.slider :
      • 0 : No space around slider.
      • space.slider.left, space.slider.right, space.slider.top, space.slider.bottom : Space around slider.
    • space.header : Space between header and text object.
    • space.footer : Space between footer and text object.
  • expand : Expand width or height of element
    • expand.header : Set true to expand width or height of header game object.
    • expand.footer : Set true to expand width or height of footer game object.
  • align : Align element
    • align.header
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • align.footer
  • content : Content of this text area.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-textareainput/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTextAreaInput extends RexPlugins.UI.TextAreaInput {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var textAreaInput = new MyTextAreaInput(scene, config);\n
"},{"location":"ui-textareainput/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

textAreaInput.layout();\n

See also - dirty

"},{"location":"ui-textareainput/#content","title":"Content","text":"
  • Set
    textAreaInput.setText(text);\n
  • Append
    textAreaInput.appendText(text);\n
  • Get
    var text = textAreaInput.text;\n
"},{"location":"ui-textareainput/#scroll-content","title":"Scroll content","text":"
  • Scroll down lines
    textAreaInput.scrollLine(lineCount);\n
  • Set
    textAreaInput.childOY = oy;\n// textAreaInput.setChildOY(oy);\n
  • Set and clamp
    textAreaInput.setChildOY(oy, true);\n
  • Add
    textAreaInput.addChildOY(oy);\n
  • Add and clamp
    textAreaInput.addChildOY(oy, true);\n
  • Get
    var childOY = textAreaInput.childOY;\n
  • Top OY
    var topOY = textAreaInput.topChildOY;\n
  • Bottom OY
    var bottomOY = textAreaInput.bottomChildOY;\n
  • Is overflow (height of content is larger than display height)
    var isOverflow = textAreaInput.isOverflow;\n
"},{"location":"ui-textareainput/#scroll-by-percentage","title":"Scroll by percentage","text":"
  • Set
    textAreaInput.t = t;  // t: 0~1\n// textAreaInput.setT(t);  \n
  • Set and clamp
    textAreaInput.setT(t, true);\n
  • Get
    var t = textAreaInput.t;\n
"},{"location":"ui-textareainput/#scroll-to-topbottom","title":"Scroll to top/bottom","text":"
  • Scroll to top
    textAreaInput.scrollToTop();\n
    • Equal to textAreaInput.t = 0;
  • Scroll to bottom
    textAreaInput.scrollToBottom();\n
    • Equal to textAreaInput.t = 1;
"},{"location":"ui-textareainput/#scroll-to-line","title":"Scroll to line","text":"
  • Scroll to next line
    textAreaInput.scrollToNextLine();\n
  • Scroll to next n line
    textAreaInput.scrollToNextLine(n);\n
  • Scroll to line
    textAreaInput.scrollToLine(lineIndex);\n
  • Get current line index
    var lineIndex = textAreaInput.lineIndex;\n
"},{"location":"ui-textareainput/#enabledisable-scrolling","title":"Enable/disable scrolling","text":"
  • Slider
    • Set enable state
      textAreaInput.setSliderEnable(enabled);\n
      or
      textAreaInput.sliderEnable = enabled;\n
    • Get enable state
      var enable = textAreaInput.sliderEnable;\n
  • Scroller
    • Set enable state
      textAreaInput.setScrollerEnable(enabled);\n
      or
      textAreaInput.scrollerEnable = enabled;\n
    • Get enable state
      var enable = textAreaInput.scrollerEnable;\n
"},{"location":"ui-textareainput/#read-only","title":"Read only","text":"
  • Enable read only
    textAreaInput.setReadOnly();\n// textAreaInput.setReadOnly(true);\n
    or
    textAreaInput.readOnly = true;\n
  • Disable read only
    textAreaInput.setReadOnly(false);\n
    or
    textAreaInput.readOnly = false;\n
  • Get read only
    var readOnlyEanble = txt.readOnly;\n
"},{"location":"ui-textareainput/#event","title":"Event","text":"
  • On close text-editor
    textAreaInput.on('close', function(text, textAreaInput) {\n\n})\n
  • Text changed
    textAreaInput.on('textchange', function(text, textAreaInput){\n// ...\n})\n
  • Scroll
    textAreaInput.on('scroll', function(textAreaInput) {\n// ...\n})\n
  • Slider
    • Slider drag start
      textAreaInput.getElement('slider').on('inputstart', function(panel) {\n// ...\n})\n
    • Slider drag end
      textAreaInput.getElement('slider').on('inputend', function(panel) {\n// ...\n})\n
  • Scroller
    • Scroller drag start
      textAreaInput.getElement('scroller').on('dragstart', function(panel) {\n// ...\n})\n
    • Scroller drag end
      textAreaInput.getElement('scroller').on('dragend', function(panel) {\n// ...\n})\n
"},{"location":"ui-textareainput/#lines-count","title":"Lines count","text":"
var linesCount = textAreaInput.linesCount;\n
"},{"location":"ui-textareainput/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-textareainput/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = textAreaInput.getElement('background');\n
    • Text game object
      var text = textAreaInput.getElement('text');\n
    • Slider
      • Track
        var track = textAreaInput.getElement('slider.track');\n
      • Thumb
        var thumb = textAreaInput.getElement('slider.thumb');\n
  • Get by name
    var gameObject = textAreaInput.getElement('#' + name);\n// var gameObject = textAreaInput.getElement('#' + name, recursive);\n
    or
    var gameObject = textAreaInput.getByName(name);\n// var gameObject = textAreaInput.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-textbox/","title":"Text box","text":""},{"location":"ui-textbox/#introduction","title":"Introduction","text":"

A container with an icon, (typing and paging) text, and background.

  • Author: Rex
  • Game object
"},{"location":"ui-textbox/#live-demos","title":"Live demos","text":"
  • Text box
  • Inner sizer
  • Speech bubble background
  • Bitmap text
  • Page break
  • Show last page
"},{"location":"ui-textbox/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-textbox/#install-plugin","title":"Install plugin","text":""},{"location":"ui-textbox/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add text-box object
    var textBox = scene.rexUI.add.textBox(config);\n
"},{"location":"ui-textbox/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text-box object
    var textBox = scene.rexUI.add.textBox(config);\n
"},{"location":"ui-textbox/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { TextBox } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add text-box object
    var textBox = new TextBox(scene, config);\nscene.add.existing(textBox);\n
"},{"location":"ui-textbox/#add-textbox-object","title":"Add textbox object","text":"
var textBox = scene.rexUI.add.textBox({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nlayoutMode: 0,\n\nrtl: false,\n\ntypingMode: 0,\n\nbackground: backgroundGameObject,\n\ninnerBackground: backgroundGameObject,\n\ntitle: titleGameObject,\n\nseparator: separatorGameObject,\n\nicon: iconGameObject,\niconMask: false,\n\ntext: textGameObject,\nexpandTextWidth: false,\nexpandTextHeight: false,\n\naction: actionGameObject,\nactionMask: false,\n\nalign: {\ntitle: 'left',\ntext: 'left',\nicon: 'center',\naction: 'center'\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ninnerLeft: 0, innerRight: 0, innerTop: 0, innerBottom: 0,\n\ntitle: 0, titleLeft: 0, titleRight: 0,\nicon: 0, iconTop: 0, iconBottom: 0,\ntext: 0, textLeft: 0, textRight: 0,\nactionTop: 0, actionBottom: 0,\n},\n\n// page: { \n//    maxLines: undefined,\n//    pageBreak: '\\f\\n',\n// },\n// typing: { \n//    wrap: false,\n//    speed: 333,    \n// },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • layoutMode :
    • 0 : title, separator, and text will be layout vertically, then layout with icon, action horizontally.
    • 1 : icon, text, and action will be layout horizontally, then layout with title, separator vertically. Default behavior.
  • rtl :
    • false : Layout children (icon, text, action) from left to right. Default behavior.
    • true : Layout children (icon, text, action) from right to left.
  • typingMode :
    • 0, 'page' : Typing content page by page. Default behavior.
    • 1, 'line' : Typing content line by line until finished.
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • innerBackground : Game object of background inside innerSizer, optional.
    • In mode 0, innerSizer contains title, separator, and text.
    • In mode 1, innerSizer contains icon, text, and action.
  • title : Game object of title, optional.
  • separator : Game object of separator, optional.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
  • text : Text object, bbcode text object, tag text object, or bitmap text object, required.
    • Max lines and wrapped width
      • Built-in text object : maxLines and wrap width (wordWrap.width).
      • BBcode text object : maxLines and wrap width (wrap.width).
      • Tag text object : maxLines and wrap width (wrap.width).
      • Bitmap text object : Set maxLines at page.maxLines in configuration of page behavior, and wrap width at text.setMaxWidth(width).
    • Fixed width and fixed height
      • Built-in text object : fixedWidth and fixedHeight, set to 0 to disable this feature.
      • BBcode text object : fixedWidth and fixedHeight, set to 0 to disable this feature.
      • Tag text object : fixedWidth and fixedHeight, set to 0 to disable this feature.
  • expandTextWidth :
    • true : Expand fixedWidth and wrapWidth when layout, to change width of text game object to fit this textbox.
  • expandTextHeight :
    • true : Expand fixedHeight when layout, to change height of text game object to fit this textbox.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
  • align : Alignment of title, text, icon, action game objects.
    • align.title, align.text : 'left', 'center', or 'right'. Default vale is 'left'.
    • align.icon, align.action : 'top', 'center', or 'bottom'. Default vale is 'center'.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.innerLeft, space.innerRight, space.innerTop, space.innerBottom : Space parameter of inner sizer.
    • space.title : Space between title game object and separator game object.
    • space.titleLeft, space.titleRight : Space at left or right side of title game object.
    • space.icon : Space between icon game object and text game object.
    • space.iconTop, space.iconBottom : Space around icon game object.
    • space.text : Space between text game object and action icon game object.
    • space.textLeft, space.textRight : Space at left or right side of text game object.
    • space.actionTop, space.actionBottom : Space around action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • page : Configuration of page behavior
    • page.maxLines : Max lines of a page. If not given in text game object.
    • page.pageBreak : Symbol of page-break. Default value is '\\f\\n'.
  • typing : Configuration of type behavior
    • typing.wrap :
      • false : Don't insert \\n, default behavior.
      • true : Insert \\n to wrap content according to style of text, to prevent typing jittering.
    • typing.speed : Typing speed in ms, default value is 333.
"},{"location":"ui-textbox/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTextBox extends RexPlugins.UI.TextBox {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var textBox = new MyTextBox(scene, config);\n
"},{"location":"ui-textbox/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

textBox.layout();\n

See also - dirty

"},{"location":"ui-textbox/#typing","title":"Typing","text":"
  • Start typing
    textBox.start(content, typingSpeed);\n
    • content : Content string.
    • speed : Typing speed in ms.
      • undefined : Use previous typing speed.
  • Append and continue typing
    textBox.more(content, typingSpeed);\n
    • content : Content string.
    • speed : Typing speed in ms.
      • undefined : Use previous typing speed.
  • Stop typing
    textBox.stop();\n
    • Will fire 'stop' event.
  • Stop typing and show all text
    textBox.stop(true);\n
    • Will fire 'stop', 'type', 'pageend' event.
  • Stop typing and show all text at last page
    textBox.showLastPage();\n
    • Will fire 'type', 'pageend', 'complete' events.
  • Pause typing
    textBox.pause();\n
    • Will fire 'pause' event.
  • Resume typing
    textBox.resume();\n
    • Will fire 'resume' event.
  • Is typing
    var isTyping = textBox.isTyping;\n
"},{"location":"ui-textbox/#typing-speed","title":"Typing speed","text":"
  • Change typing speed
    textBox.setTypingSpeed(speed);\n
    • speed : Typing speed in ms.
  • Get typing speed
    var speed = textBox.typingSpeed;\n
"},{"location":"ui-textbox/#page","title":"Page","text":"
  • Type next page
    textBox.typeNextPage();\n
  • Is page end, after typing complete
    var isPageEnd = textBox.isPageEnd;\n
  • Is last page
    var isLastPage = textBox.isLastPage;\n
  • Is first page
    var isFirstPage = textBox.isFirstPage;\n
  • Current page index
    var pageIndex = textBox.pageIndex;\n
  • Number of pages
    var pageIndex = textBox.pageCount;\n
"},{"location":"ui-textbox/#icon-texture","title":"Icon texture","text":"
  • Set texture
    textBox.setTexture(key);\n// label.setTexture(key, frame);\n
  • Get texture key, frame name
    var textureKey = textBox.texture.key;\nvar frameName = textBox.frame.name;\n
"},{"location":"ui-textbox/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = textBox.getElement('background');\n
    • InnerSizer
      var innerSizer = textBox.getElement('innerSizer');\n
      • In mode 0, innerSizer contains title, separator, and text.
      • In mode 1, innerSizer contains icon, text, and action.
    • Background game object inside innerSizer
      var innerBackground = textBox.getElement('innerBackground');\n
    • Title game object
      var textObject = textBox.getElement('title');\n
    • Separator game object
      var textObject = textBox.getElement('separator');\n
    • Icon game object
      var icon = textBox.getElement('icon');\n
    • Text game object
      var textObject = textBox.getElement('text');\n
    • Action icon game object
      var action = textBox.getElement('action');\n
  • Get by name
    var gameObject = textBox.getElement('#' + name);\n// var gameObject = textBox.getElement('#' + name, recursive);\n
    or
    var gameObject = textBox.getByName(name);\n// var gameObject = textBox.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-textbox/#events","title":"Events","text":"
  • On typing start.
    textBox.on('start', function() {\n// ...\n}, scope);\n
  • On changing content of text game object, will also re-layout textbox :
    textBox.on('type', function() {\n// ...\n}, scope);\n
  • On typing a character :
    textBox.on('typechar', function(char) {\n// ...\n}, scope);\n
  • On Typing the last character of current page.
    textBox.on('pageend', function() {\nif (textBox.isLastPage) {\n// ...            \n}\n}, scope);\n
  • On typing all pages complete, equal to 'pageend' event with textBox.isLastPage.
    textBox.on('complete', function() {\n// ...\n}, scope);\n
  • On typing paused by textBox.pause().
    textBox.on('pause', function() {\n// ...\n}, scope);\n
  • On typing resume by textBox.resume().
    textBox.on('resume', function() {\n// ...\n}, scope);\n
  • On typing stop by textBox.stop().
    textBox.on('stop', function() {\n// ...\n}, scope);\n
"},{"location":"ui-textbox/#other-properties","title":"Other properties","text":"

See title label, sizer object, base sizer object, container-lite.

"},{"location":"ui-titlelabel/","title":"Title label","text":""},{"location":"ui-titlelabel/#introduction","title":"Introduction","text":"

A container with title, text in two rows, and an icon, background.

  • Author: Rex
  • Game object
"},{"location":"ui-titlelabel/#live-demos","title":"Live demos","text":"
  • Title-label
  • Layout modes
"},{"location":"ui-titlelabel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-titlelabel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-titlelabel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add label object
    var label = scene.rexUI.add.titleLabel(config);\n
"},{"location":"ui-titlelabel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add label object
    var label = scene.rexUI.add.titleLabel(config);\n
"},{"location":"ui-titlelabel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { TitleLabel } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add label object
    var label = new TitleLabel(scene, config);\nscene.add.existing(label);\n
"},{"location":"ui-titlelabel/#add-label-object","title":"Add label object","text":"
var label = scene.rexUI.add.titleLabel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nlayoutMode: 0,\n\n// rtl: false,\n\nbackground: backgroundGameObject,\n\ninnerBackground: backgroundGameObject,\n\ntitle: titleGameObject,\n// wrapTitle: false,\n// adjustTitleFontSize: false,\n// expandTitleWidth: false,\n// expandTitleHeight: false,\n\nseparator: separatorGameObject,\n\nicon: iconGameObject,\niconMask: false,\n\ntext: textGameObject,\n// wrapText: false,\n// adjustTextFontSize: false,\n// expandTextWidth: false,\n// expandTextHeight: false,\n\naction: actionGameObject,\nactionMask: false,\n\nalign: {\ntitle: 'left',\ntext: 'left',\nicon: 'center',\naction: 'center'\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ninnerLeft: 0, innerRight: 0, innerTop: 0, innerBottom: 0,\n\ntitle: 0, titleLeft: 0, titleRight: 0,\nicon: 0, iconTop: 0, iconBottom: 0,\ntext: 0, textLeft: 0, textRight: 0,\nseparator: 0, separatorLeft: 0, separatorRight: 0,\nactionTop: 0, actionBottom: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • layoutMode :
    • 0 : title, separator, and text will be layout vertically, then layout with icon, action horizontally.
    • 1 : icon, text, and action will be layout horizontally, then layout with title, separator vertically.
  • rtl :
    • false : Layout children (icon, text, action) from left to right. Default behavior.
    • true : Layout children (icon, text, action) from right to left.
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • innerBackground : Game object of background inside innerSizer, optional.
    • In mode 0, innerSizer contains title, separator, and text.
    • In mode 1, innerSizer contains icon, text, and action.
  • title : Game object of title, optional.
  • wrapTitle : Enable WrapExpandText feature.
    • false, 0 : No WrapExpandText feature. Default behavior.
    • true, 1, 'word' : Word WrapExpandText.
    • 2, 'char' : Character WrapExpandText.
  • adjustTitleFontSize : Enable FontSizeExpandText feature.
    • false : No FontSizeExpandText feature. Default behavior.
    • true : Enable FontSizeExpandText feature. Can't work with wrapTitle: true.
      • Text-width and text-height will be expanding.
      • Use BBCodeText (scene.rexUI.add.BBCodeText) with {valign: 'center'} style.
  • expandTitleWidth :
    • false : Keep width of title to original size. Default behavior.
    • true : Expand width of title object. Will set display width by default.
      • Must set to true if using scene.rexUI.wrapExpandText method with any text game object.
      • Can't work with squareFitIcon: true.
  • expandTitleHeight : Set true to expand height of title object.
  • separator : Game object of separator, optional.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • text : Game object of text.
  • wrapText : Enable WrapExpandText feature.
    • false, 0 : No WrapExpandText feature. Default behavior.
    • true, 1, 'word' : Word WrapExpandText.
    • 2, 'char' : Character WrapExpandText.
  • adjustTextFontSize : Enable FontSizeExpandText feature.
    • false : No FontSizeExpandText feature. Default behavior.
    • true : Enable FontSizeExpandText feature. Can't work with wrapText: true.
      • Text-width and text-height will be expanding.
      • Use BBCodeText (scene.rexUI.add.BBCodeText) with {valign: 'center'} style.- expandTextWidth :
    • false : Keep width of text to original size. Default behavior.
    • true : Expand width of text object. Will set display width by default.
      • Must set to true if using scene.rexUI.wrapExpandText method with any text game object.
      • Can't work with squareFitIcon: true.
  • expandTextHeight : Set true to expand height of text object.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • align : Alignment of title, text, icon, action game objects.
    • align.title, align.text : 'left', 'center', or 'right'. Default vale is 'left'.
    • align.icon, align.action : 'top', 'center', or 'bottom'. Default vale is 'center'.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.innerLeft, space.innerRight, space.innerTop, space.innerBottom : Space parameter of inner sizer.
    • space.title : Space between title game object and separator game object.
    • space.titleLeft, space.titleRight : Space at left or right side of title game object.
    • space.icon : Space between icon game object and text game object.
    • space.iconTop, space.iconBottom : Space around icon game object.
    • space.text : Space between text game object and action icon game object.
    • space.textLeft, space.textRight : Space at left or right side of text game object.
    • space.actionTop, space.actionBottom : Space around action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-titlelabel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTitleLabel extends RexPlugins.UI.TitleLabel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var label = new MyTitleLabel(scene, config);\n
"},{"location":"ui-titlelabel/#layout-modes","title":"Layout modes","text":""},{"location":"ui-titlelabel/#mode-0","title":"Mode 0","text":"

title, separator, and text will be layout vertically inside innerSizer, then layout with icon, action horizontally.

Icon Title Action Separator Text"},{"location":"ui-titlelabel/#mode-1","title":"Mode 1","text":"

icon, text, and action will be layout horizontally inside innerSizer, then layout with title, separator vertically.

Title Separator Icon Text Action"},{"location":"ui-titlelabel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

label.layout();\n

See also - dirty

"},{"location":"ui-titlelabel/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = label.getElement('background');\n
    • InnerSizer
      var innerSizer = label.getElement('innerSizer');\n
      • In mode 0, innerSizer contains title, separator, and text.
      • In mode 1, innerSizer contains icon, text, and action.
    • Background game object inside innerSizer
      var innerBackground = label.getElement('innerBackground');\n
    • Title game object
      var textObject = label.getElement('title');\n
    • Separator game object
      var textObject = label.getElement('separator');\n
    • Icon game object
      var icon = label.getElement('icon');\n
    • Text game object
      var textObject = label.getElement('text');\n
    • Action icon game object
      var action = label.getElement('action');\n
  • Get by name
    var gameObject = label.getElement('#' + name);\n// var gameObject = label.getElement('#' + name, recursive);\n
    or
    var gameObject = label.getByName(name);\n// var gameObject = label.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-titlelabel/#title","title":"Title","text":"
  • Get title string
    var s = label.title;\n
  • Set title string
    label.setTitle(s);\n
    or
    label.title = s;\n
"},{"location":"ui-titlelabel/#text","title":"Text","text":"
  • Get text string
    var s = label.text;\n
  • Set text string
    label.setText(s);\n
    or
    label.text = s;\n
"},{"location":"ui-titlelabel/#icon-texture","title":"Icon texture","text":"
  • Set texture
    label.setTexture(key);\n// label.setTexture(key, frame);\n
  • Set texture via texture object
    label.setTexture(texture);\n// label.setTexture(texture, frame);\n
  • Get texture, frame.
    var texture = label.texture;\nvar frame = label.frame;\n
  • Get texture key, frame name.
    var textureKey = label.texture.key;\nvar frameName = label.frame.name;\n
"},{"location":"ui-titlelabel/#reset-display-content","title":"Reset display content","text":"
label.resetDisplayContent({\ntitle: '',\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n})\n

or

label.resetDisplayContent(text);\n
  • title : Set title's text string.
  • text : Set text string.
  • icon, iconFrame
    • A string : Set texture of icon game object.
    • undefined, or null : Hide icon game object.
    • true : Show icon game object without change its texture.
  • iconSize : Set display size of icon game object.
  • action, actionFrame
    • A string : Set texture of icon game object.
    • undefined, or null : Hide action game object.
    • true : Show action game object without change its texture.
  • actionSize : Set display size of action game object.

Run label.layout() after this method, to layout children again.

"},{"location":"ui-titlelabel/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-toast/","title":"Toast","text":""},{"location":"ui-toast/#introduction","title":"Introduction","text":"

Show text message for a short while.

  • Author: Rex
  • Game object
"},{"location":"ui-toast/#live-demos","title":"Live demos","text":"
  • Toast
  • Depth
    • Set depth
    • Bring to top
    • Add to layer
"},{"location":"ui-toast/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-toast/#install-plugin","title":"Install plugin","text":""},{"location":"ui-toast/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add toast object
    var toast = scene.rexUI.add.toast(config);\n
"},{"location":"ui-toast/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add toast object
    var toast = scene.rexUI.add.toast(config);\n
"},{"location":"ui-toast/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Toast } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add toast object
    var toast = new Toast(scene, config);\nscene.add.existing(toast);\n
"},{"location":"ui-toast/#add-toast-object","title":"Add toast object","text":"
var toast = scene.rexUI.add.toast({\nx: 0,\ny: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n\nbackground: backgroundGameObject,\nicon: iconGameObject,\niconMask: false,\ntext: textGameObject,\naction: actionGameObject,\nactionMask: false,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0,\ntext: 0,\n},\n\nduration: {\nin: 200,\nhold: 1200,\nout: 200,\n},\n\n// transitIn: 0,\n// transitOut: 0,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • background : Game object of background, optional. This background game object will be resized to fit the size of toast.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
  • text : Game object of text.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds
    • space.icon : Space between icon game object and text game object.
    • space.text : Space between text game object and action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • duration : Duration of displaying message
    • duration.in : Duration of transit-in stage.
    • duration.hold : Duration of hold stage.
    • duration.out : Duration of transit-out stage.
  • transitIn : Transit-in action.
    • 0, or 'popUp' : Pop-up.
    • 1, or 'fadeIn' : Fade-in.
    • A callback : Custom transit-in function
      function(toast, duration) {\n// ...\n}\n
    • false, null : No transitIn.
  • transitOut : Transit-out action.
    • 0, or 'scaleDown' : Scale-down.
    • 1, or 'fadeOut' : Fade-out.
    • A callback : Custom transit-out function
      function(toast, duration) {\n// ...\n}\n
    • false, null : No transitOut.

Toast object will be invisible at beginning.

"},{"location":"ui-toast/#custom-class","title":"Custom class","text":"
  • Define class
    class MyToast extends RexPlugins.UI.Toast {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var toast = new MyToast(scene, config);\n
"},{"location":"ui-toast/#show-message","title":"Show message","text":"
toast.showMessage(message);\n
  • message : A string, or a callback.
    • A string. Apply this content to text game object.
    • Callback. Invoke this callback to configurate toast object.
      function(toast) {\n// var icon = toast.getElement('icon');\n// var text = toast.getElement('text');\n// var action = toast.getElement('action');\n}\n

Toast displays message follows these steps : transit-in, hold, transit-out. New message will be pending until toast is back to idle.

"},{"location":"ui-toast/#clear-messages","title":"Clear messages","text":"
toast.removeAllMessages();\n
"},{"location":"ui-toast/#is-showing-message","title":"Is showing message","text":"
var isShowing = toast.isShowingMessage;\n
"},{"location":"ui-toast/#display-time","title":"Display time","text":"
  • Transit-in time (duration.in)
    • Get
      var time = toast.transitInTime;\n
    • Set
      toast.setTransitInTime(time);\n
  • Display time (duration.hold)
    • Get
      var time = toast.displayTime;\n
    • Set
      toast.setDisplayTime(time);\n
  • Transit-out time (duration.out)
    • Get
      var time = toast.transitOutTime;\n
    • Set
      toast.setTransitOutTime(time);\n
"},{"location":"ui-toast/#transit-action","title":"Transit action","text":"
  • Set transit-in action
    toast.setTransitInCallback(callback);\n
    • callback : Transit-in action
      • 0, or 'popUp' : Pop-up.
      • 1, or 'fadeIn' : Fade-in.
      • A callback : Custom transit-in function
        function(toast, duration) {\n// ...\n}\n
  • Set transit-out action
    toast.setTransitOutCallback(callback);\n
    • callback : Transit-out action
      • 0, or 'scaleDown' : Scale-down.
      • 1, or 'fadeOut' : Fade-out.
      • A callback : Custom transit-out function
        function(toast, duration) {\n// ...\n}\n
"},{"location":"ui-toast/#event","title":"Event","text":"
  • Transit-in
    toast.on('transitin', function(toast, transitInTime) {\n// ...\n})\n
  • Transit-out
    toast.on('transitout', function(toast, transitOutTime) {\n// ...\n})\n
"},{"location":"ui-toast/#other-properties","title":"Other properties","text":"

See label object, sizer object, base sizer object, container-lite.

"},{"location":"ui-toastqueue/","title":"Toast queue","text":""},{"location":"ui-toastqueue/#introduction","title":"Introduction","text":"

Queue messages for a short while.

  • Author: Rex
  • Game object
"},{"location":"ui-toastqueue/#live-demos","title":"Live demos","text":"
  • Toast queue
"},{"location":"ui-toastqueue/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-toastqueue/#install-plugin","title":"Install plugin","text":""},{"location":"ui-toastqueue/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add toast-queue object
    var toastQueue = scene.rexUI.add.toastQueue(config);\n
"},{"location":"ui-toastqueue/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add toast-queue object
    var toastQueue = scene.rexUI.add.toastQueue(config);\n
"},{"location":"ui-toastqueue/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ToastQueue } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add toast-queue object
    var toastQueue = new ToastQueue(scene, config);\nscene.add.existing(toastQueue);\n
"},{"location":"ui-toastqueue/#add-toast-queue-object","title":"Add toast-queue object","text":"
var toastQueue = scene.rexUI.add.toastQueue({\nx: 0,\ny: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 1,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nitem: 0,\n},\n\ncreateMessageLabelCallback(scene, message, toastQueue) {\n// return gameObject;\n},\n\nqueueDirection: 1, // 'bottom-to-top', or 'top-to-bottom'\n\nduration: {\nin: 200,\nhold: 2000,\nout: 200,\n},\n\n// transitIn: undefined,\n// transitOut: undefined,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between 2 children game objects.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • createMessageLabelCallback : Callback for creating message label game object
    function(scene, message, toastQueue) {\n// \nreturn gameObject;\n}\n
    • message : message parameter passing from showMessage method.
    • toastQueue : This toast-queue game object.
  • queueDirection : Direction of message queue
    • 1, or 'bottom-to-top' : Message queue from bottom to top. Default value.
    • 0, or 'top-to-bottom' : Message queue from top to bottom.
  • duration : Duration of displaying message
    • duration.in : Duration of transit-in stage.
    • duration.hold : Duration of hold stage.
    • duration.out : Duration of transit-out stage.
  • transitIn : Transit-in action.
    • undefined (not gived) : Pop up message label.
    • A callback : Custom transit-in function
      function(messageLabel, duration, toastQueue) {\n// ...\n}\n
    • false, null : No transitOut.
  • transitOut : Transit-out action.
    • undefined (not gived) : Fade out message label.
    • A callback : Custom transit-out function
      function(messageLabel, duration, toastQueue) {\n// ...\n}\n
    • false, null : No transitOut.

Message Label will be destroyed when

  • Clicking, or
  • Timeout
"},{"location":"ui-toastqueue/#custom-class","title":"Custom class","text":"
  • Define class
    class MyToastQueue extends RexPlugins.UI.ToastQueue {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var toastQueue = new MyToastQueue(scene, config);\n
"},{"location":"ui-toastqueue/#show-message","title":"Show message","text":"
toastQueue.showMessage(message);\n
  • message : A string, or an object. Will pass to createMessageLabelCallback callback.
"},{"location":"ui-toastqueue/#clear-messages","title":"Clear messages","text":"
toastQueuetoast.removeAllMessages();\n

Invoke transition-out of all message labels.

"},{"location":"ui-toastqueue/#display-time","title":"Display time","text":"
  • Transit-in time (duration.in)
    • Get
      var time = toastQueue.transitInTime;\n
    • Set
      toastQueue.setTransitInTime(time);\n
  • Display time (duration.hold)
    • Get
      var time = toastQueue.displayTime;\n
    • Set
      toastQueue.setDisplayTime(time);\n
  • Transit-out time (duration.out)
    • Get
      var time = toastQueue.transitOutTime;\n
    • Set
      toastQueue.setTransitOutTime(time);\n
"},{"location":"ui-toastqueue/#transit-action","title":"Transit action","text":"
  • Set transit-in action
    toastQueue.setTransitInCallback(callback);\n
    • callback : Transit-in action
      function(messageLabel, duration, toastQueue) {\n// ...\n}\n
  • Set transit-out action
    toastQueue.setTransitOutCallback(callback);\n
    • callback : Transit-out action
      function(messageLabel, duration, toastQueue) {\n// ...\n}\n
"},{"location":"ui-toastqueue/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-trees/","title":"Trees","text":""},{"location":"ui-trees/#introduction","title":"Introduction","text":"

A container with trees and leaf-nodes

  • Author: Rex
  • Game object
"},{"location":"ui-trees/#live-demos","title":"Live demos","text":"
  • Tree
  • Display json
"},{"location":"ui-trees/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-trees/#install-plugin","title":"Install plugin","text":""},{"location":"ui-trees/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add trees object
    var trees = scene.rexUI.add.trees(config);\n
"},{"location":"ui-trees/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add trees object
    var trees = scene.rexUI.add.trees(config);\n
"},{"location":"ui-trees/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Trees } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add trees object
    var trees = new Trees(scene, config);\nscene.add.existing(trees);\n
"},{"location":"ui-trees/#add-instance","title":"Add instance","text":"

Trees contains tree-node instance, each tree contains tree instance and node instance.

"},{"location":"ui-trees/#add-trees-object","title":"Add trees object","text":"
var trees = scene.rexUI.add.trees({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\n// space: { left: 0, right:0, top:0, bottom:0, item:0 },\n\ntree: {\n// background: function(scene {isLeaf}) { return gameObject; },\n// background: backgroundStyle,\n\n// toggleButton: function(scene, {isLeaf}) {\n//     gameObject\n//         .on('expand.start', function (gameObject) {\n//          })\n//          .on('collapse.start', function (gameObject) {\n//          })\n//     return gameObject;\n// }\n// toggleButton : triangleStyle,\n\n// nodeBackground: function(scene {isLeaf}) { return gameObject; },\n// nodeBackground: backgroundStyle,\n\n// nodeBody: function(scene {isLeaf}) { return gameObject; },\n// nodeBody: simpleLabelStyle,\n\n// transition: {\n//     duration: 200,\n//     expandCallback: undefined,\n//     collapseCallback: undefined,\n// },\n\n// orientation: 'y',\n\n//space: {\n//    indent: 0,\n//    indentLeft: 0, indentRight: 0, indentTop: 0, indentBottom: 0,\n//\n//    nodeLeft: 0, nodeRight: 0, nodeTop: 0, nodeBottom: 0,\n//    toggleButton: 0,\n//},\n\n// align: {\n//     title: 'left',\n//     child: 'left',\n// },\n\n// expand: {\n//     title: true,\n//     child: true,\n// },\n\n// expanded: true,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this trees. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between 2 children game objects.
  • tree : Default configuration of node, optional.
    • tree.background :
      • Callback
        function(scene, {isLeaf}) {\nreturn gameObject;\n}\n
        • isLeaf :
          • false : This node is a tree-node.
          • true : This node is a leaf-node.
      • Style of Background : Create Round-rectangle, Bar-rectangle, Nine-slice, or Image as background element.
      • undefined : Don't create any game object.
    • tree.toggleButton
      • Callback
        function(scene, {isLeaf}) {\ngameObject\n.on('expand.start', function (gameObject) {\n})\n.on('collapse.start', function (gameObject) {\n})\nreturn gameObject;\n}\n
        • isLeaf :
          • false : This node is a tree-node.
          • true : This node is a leaf-node.
        • Events 'expand.start' and 'collapse.start' will be fired when expanding or collapsing child nodes of this tree.
      • Style of triangle, default behavior.
        {\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n
    • tree.nodeBackground
      • Callback
        function(scene, {isLeaf}) {\nreturn gameObject;\n}\n
        • isLeaf :
          • false : This node is a tree-node.
          • true : This node is a leaf-node.
      • Style of Background : Create Round-rectangle, Bar-rectangle, Nine-slice, or Image as background element.
      • undefined : Don't create any game object.
    • tree.nodeBody
      • Callback
        function(scene, {isLeaf}) {\nreturn gameObject;\n}\n
        • isLeaf :
          • false : This node is a tree-node.
          • true : This node is a leaf-node.
      • Style of simple label : Create Simple-label as node body element. Default behavior.
    • tree.transition : Configuration of expanding/collapsing transition.
      • tree.transition.duration : Duration of expanding/collapsing transition.
      • tree.transition.expandCallback : Callback invoked when expading child. Default behavior is scale-up.
      • tree.transition.collapseCallback : Callback invoked when collapsing child. Default behavior is scale-down.
    • tree.space : Pads spaces of tree.
      • tree.space.indent, tree.space.indentLeft, tree.space.indentRight, tree.space.indentTop, tree.space.indentBottom : Space of node's bounds.
      • tree.space.nodeLeft, tree.space.nodeRight, tree.space.nodeTop, tree.space.nodeBottom : Space of node child's bounds.
      • tree.space.toggleButton : Space between toggle button and next child.
    • tree.align.title, tree.align.child : Alignment of title, child game objects.
      • undefined, or 'left', or 'top' : Align game objects at left, or top. Default behavior.
      • 'center' : Align game objects at center.
      • 'right', or 'bottom' : Align game objects at right, or bottom.
    • tree.expand.title, tree.expand.child : Expand width/height of title, child game objects.
      • true : Expand width/heigh. Default behavior.
      • false : Use origin width/height.
    • tree.expanded :
      • true : Expand this tree node. Default behavior.
      • false : Collapse this tree node.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire trees events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-trees/#add-tree-object","title":"Add tree object","text":"

var tree = trees.addTree();\n// var tree = trees.addTree(nodeKey);\n
var subTree = tree.addTree();\n// var subTree = tree.addTree(nodeKey);\n

or

var tree = trees.addTree({\n// nodeKey: UUID()\n\n// background: backgroundGameObject,\n// background: function(scene {isLeaf}) { return gameObject; },\n// background: backgroundStyle,\n\ntoggleButton: toggleButtonGameObject,\n// toggleButton: function(scene {isLeaf}) { \n//      gameObject\n//          .on('expand.start', function (gameObject) {\n//           })\n//           .on('collapse.start', function (gameObject) {\n//           })\n//     return gameObject; \n// },\n// toggleButton : triangleStyle,\n\n// nodeBackground: nodeBackgroundGameObject,\n// nodeBackground: function(scene {isLeaf}) { return gameObject; },\n// nodeBackground: backgroundStyle,\n\nnodeBody: nodeBodyGameObject,\n// nodeBody: function(scene {isLeaf}) { return gameObject; },\n// nodeBody: simpleLabelStyle,\n\n// transition: {\n//     duration: 200,\n//     expandCallback: undefined,\n//     collapseCallback: undefined,\n// },\n\n// orientation: 'y',\n\n// space: {\n//     indent: 0,\n//     indentLeft: 0, indentRight: 0, indentTop: 0, indentBottom: 0,\n// \n//     nodeLeft: 0, nodeRight: 0, nodeTop: 0, nodeBottom: 0,\n//     toggleButton: 0,\n// },\n\n// align: {\n//     title: 'left',\n//     child: 'left',\n// },\n\n// expand: {\n//     title: true,\n//     child: true,\n// },\n\n// expanded: true,\n})\n
var subTree = tree.addTree(config);\n

  • nodeKey : Store reference of this tree instance by this unique string. Get tree back by trees.getTree(nodeKey)
    • An unique string, does not contain .
    • undefined : Create unique string by UUID
  • background :
    • A game object
    • Callback
      function(scene, {isLeaf}) {\nreturn gameObject;\n}\n
      • isLeaf :
        • false : This node is a tree-node.
        • true : This node is a leaf-node.
    • Style of Background : Create Round-rectangle, Bar-rectangle, Nine-slice, or Image as background element.
    • undefined : Don't create any game object.
  • toggleButton
    • A game object
    • Callback
      function(scene, {isLeaf}) {\ngameObject\n.on('expand.start', function (gameObject) {\n})\n.on('collapse.start', function (gameObject) {\n})\nreturn gameObject;\n}\n
      • isLeaf :
        • false : This node is a tree-node.
        • true : This node is a leaf-node.
      • Events 'expand.start' and 'collapse.start' will be fired when expanding or collapsing child nodes of this tree.
    • Style of triangle, default behavior.
      {\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n
  • nodeBackground
    • A game object
    • Callback
      function(scene, {isLeaf}) {\nreturn gameObject;\n}\n
      • isLeaf :
        • false : This node is a tree-node.
        • true : This node is a leaf-node.
    • Style of Background : Create Round-rectangle, Bar-rectangle, Nine-slice, or Image as background element.
    • undefined : Don't create any game object.
  • nodeBody
    • A game object
    • Callback
      function(scene, {isLeaf}) {\nreturn gameObject;\n}\n
      • isLeaf :
        • false : This node is a tree-node.
        • true : This node is a leaf-node.
    • Style of simple label : Create Simple-label as node body element. Default behavior.
"},{"location":"ui-trees/#add-node-object","title":"Add node object","text":"
  • Add default node game object
    var node = tree.addNode();\n// var node = tree.addNode(nodeKey);\n
    • nodeKey : Store reference of this tree instance by this unique string. Get tree back by trees.getTree(nodeKey)
      • An unique string, does not contain .
      • undefined : Create unique string by UUID
  • Add custom node game object
    var node = tree.addNode(gameObject);\n// var node = tree.addNode(gameObject, nodeKey);\n
"},{"location":"ui-trees/#insert-tree-object","title":"Insert tree object","text":"

var tree = trees.insertTree(index);\n// var tree = trees.insertTree(index, nodeKey);\n// var tree = trees.insertTree(index, config);\n
var subTree = tree.insertTree(index);\n// var subTree = tree.insertTree(index, nodeKey);\n// var subTree = tree.insertTree(index, config);\n

"},{"location":"ui-trees/#insert-node-object","title":"Insert node object","text":"
  • Insert default node game object
    var node = tree.insertTree(index);\n// var node = tree.insertTree(index, nodeKey);\n
  • Insert custom node game object
    var node = tree.insertTree(index, gameObject);\n// var node = tree.insertTree(index, gameObject, nodeKey);\n
"},{"location":"ui-trees/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTrees extends RexPlugins.UI.Trees {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var trees = new MyTrees(scene, config);\n
"},{"location":"ui-trees/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

trees.layout();\n

See also - dirty

Note

Layout topmost trees when expanding/collapsing start.

"},{"location":"ui-trees/#expandcollapse-tree","title":"Expand/collapse tree","text":"
  • Expand, will re-layout from topmost trees
    tree.expand();\n// tree.expand(duration);\n
    tree.expand(0);  // Immediately, won't invoke expandCallback\n
  • Collapse, will re-layout from topmost trees
    tree.collapse();\n// tree.collapse(duration);\n
    tree.collapse(0);  // Immediately, won't invoke collapseCallback\n
  • Toggle, will re-layout from topmost trees
    tree.toggle();\n// tree.toggle(duration);\n
    tree.toggle(0);  // Immediately, won't invoke expandCallback/collapseCallback\n
  • Set expanded state without re-layouting
    tree.setExpandedState(expanded);  // true, or false\n
  • Get expanded state
    var expanded = tree.expanded;\n
    • expanded : Initial value is undefined
"},{"location":"ui-trees/#remove-tree-or-node","title":"Remove tree or node","text":""},{"location":"ui-trees/#remove-tree","title":"Remove tree","text":"
  • Remove tree without destroying
    trees.removeTree(tree);\n
    tree.removeTree(subTree);\n
    tree.removeTree(nodeKey);\n
  • Remove tree and destroying
    trees.removeTree(tree, true);\n
    tree.removeTree(subTree, true);\n
    tree.removeTree(nodeKey, true);\n
  • Remove all trees without destroying
    trees.removeAllNodes();\n
    tree.removeAllNodes();\n
  • Remove all trees and destroying
    trees.removeAllNodes(tree);\n
    tree.removeAllNodes(tree);\n
"},{"location":"ui-trees/#remove-subtree-or-node","title":"Remove subTree or node","text":"
  • Remove subTree or node without destroying
    tree.removeNode(subTree);\n
    tree.removeNode(node);\n
    tree.removeNode(nodeKey);\n
  • Remove subTree or node and destroying
    trees.removeNode(subTree, true);\n
    tree.removeNode(node, true);\n
    tree.removeNode(nodeKey, true);\n
  • Remove all sub-trees and nodes without destroying
    tree.removeAllNodes();\n
  • Remove all sub-trees and nodes and destroying
    tree.removeAllNodes(tree);\n
"},{"location":"ui-trees/#get-sub-tree-or-node","title":"Get sub-tree or node","text":"
  • Get sub-tree
    var tree = trees.getTree(nodeKey);\n
    var tree = subTree.getTree(nodeKey);\n
  • Get sub-tree/node
    var tree = trees.getNode(nodeKeys);\n
    var tree = subTree.getNode(nodeKeys);\n
    • nodeKeys : nodeKeys connected by ., e.x. key0.key1.key2...
  • Get all child nodes in this tree
    var nodes = tree.getNodes();\n// var nodes = tree.getNodes(out);\n
  • Get all child nodes including all descendant nodes
    var nodes = tree.getAllNodes();\n// var nodes = tree.getAllNodes(out);\n
"},{"location":"ui-trees/#get-parent-or-root-tree","title":"Get parent or root tree","text":"
  • Get parent (tree)
    var patent = tree.getTreePatent();\n
    var patent = node.getTreePatent();\n
  • Get root (tree)
    var root = tree.getTreeRoot();\n
    var root = node.getTreeRoot();\n
"},{"location":"ui-trees/#get-element","title":"Get element","text":"
  • Get element in a tree
    • Background game object
      var background = tree.getElement('background');\n
    • Toggle button game object
      var toggleButton = trees.getElement('toggleButton');\n
    • Node-body game object
      var nodeBody = trees.getElement('nodeBody');\n
    • Children-node list game objects
      var childrenNodes = trees.getElement('childrenNodes');\n
  • Get by name
    var gameObject = trees.getElement('#' + name);\n// var gameObject = trees.getElement('#' + name, recursive);\n
    or
    var gameObject = trees.getByName(name);\n// var gameObject = trees.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-trees/#other-properties","title":"Other properties","text":"

Trees is extended from trees object, base trees object, container-lite. Tree is extended from folder.

"},{"location":"ui-trees/#set-children-interactive","title":"Set children interactive","text":"

Applies click, tap, press, swipe behaviors on this trees, to detect input events of children.

tree.setChildrenInteractive({\n// dropZone: false,\n\n// click: {mode: 'release', clickInterval: 100},\n\n// over: undefined,\n\n// press: {time: 251, threshold: 9},\n\n// tap: {time: 250, tapInterval: 200, threshold: 9, tapOffset: 10, \n//       taps: undefined, minTaps: undefined, maxTaps: undefined,},\n\n// swipe: {threshold: 10, velocityThreshold: 1000, dir: '8dir'},\n\n// inputEventPrefix: 'child.',\n})\n
  • dropZone :
    • true : Enable drop Zone on scrollable area.
    • false : Do nothing.
"},{"location":"ui-trees/#events","title":"Events","text":"
  • Pointer-down
    trees.on('child.down', function(child, pointer, event) {        }, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
  • Pointer-up
    trees.on('child.up', function(child, pointer, event) {\n// ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
  • Pointer-over
    trees.on('child.over', function(child, pointer, event) {\n// ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
  • Pointer-out
    trees.on('child.out', function(child, pointer, event) {\n// ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
  • Click
    trees.on('child.click', function(child, pointer, event) {\n// ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
    • pointer : Pointer object.
  • Press
    trees.on('child.pressstart', function(child, pointer) { // ...\n}, scope);\n
    trees.on('child.pressend', function(child, pointer) { // ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
  • Tap
    trees.on(tapEventName, function(child, pointer) { // ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
    • tapEventName : 'child.1tap', 'child.2tap', 'child.3tap', etc ...
  • Swipe
    trees.on(swipeEventName, function(child, pointer) { // ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
    • swipeEventName : 'child.swipeleft', 'child.swiperight', 'child.swipeup', 'child.swipedown'.
"},{"location":"ui-trees/#events_1","title":"Events","text":"
  • On tree expand-start
    trees.on('tree.expand.start', function(tree){\n\n})\n
  • On tree expand-complete
    trees.on('tree.expand.complete', function(tree){\n\n})\n
  • On tree collapse-start
    trees.on('tree.collapse.start', function(tree){\n\n})\n
  • On tree collapse-complete
    trees.on('tree.collapse.complete', function(tree){\n\n})\n
"},{"location":"ui-tweaker/","title":"Tweaker","text":""},{"location":"ui-tweaker/#introduction","title":"Introduction","text":"

Fine-tuning properties of target object. Reference

  • Author: Rex
  • Game object
"},{"location":"ui-tweaker/#live-demos","title":"Live demos","text":"
  • Tweaker
  • Bind target
  • Horizontal tweaker
  • Columns
  • Wrap
  • Buttons
  • Add rows
  • Edit item
"},{"location":"ui-tweaker/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-tweaker/#install-plugin","title":"Install plugin","text":""},{"location":"ui-tweaker/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add tweaker object
    var tweaker = scene.rexUI.add.tweaker(config);\n
"},{"location":"ui-tweaker/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add tweaker object
    var tweaker = scene.rexUI.add.tweaker(config);\n
"},{"location":"ui-tweaker/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Tweaker } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add tweaker object
    var tweaker = new Tweaker(scene, config);\nscene.add.existing(tweaker);\n
"},{"location":"ui-tweaker/#add-tweaker-object","title":"Add tweaker object","text":"
var tweaker = scene.rexUI.add.tweaker({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// orientation: 0,\n\n// style: { ... }\nstyles : {\nitemWidth : 0,\nitemHeight: 0,\n\ninputRow: {\nbackground: {\n\n},\n\ntitle: {\n\n},\n\ninputText: {\n\n},\n\ninputTextArea: {\nheight:\n},\n\nlist: {\nlabel: {\n\n},\n\nbutton: {\n\n}\n},\n\nbutton: {\n\n},\n\nslider: {\ntrack: {\n\n},\n\nindicator: {\n\n},\n\nthumb: {\n\n}\n},\n\ncolorInput: {\ncolorPicker: {\n\n},\n\ncolorComponents: {\ninputText: {\n\n}\n}\n},\n\ncheckbox: {\n\n},\n\ntoggleSwitch: {\n\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n}\n},\n\nseparator: {\n\n},\n\nfolder: {\n},\n\ntab: {\n},\n\nscrollable: {\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0, item: 0\n},\n},\n\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation : Main orientation of the tweaker.
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Arrange game objects from left ot right.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Arrange game objects from top to bottom. Default value is 1.
  • styles, or style : Styles settings of input rows, separator, folder, tab, and scrollable. See Styles chapter for more detail.
    • style.itemWidth : Width of input row, used if orientation is set to 'y'(1).
    • styles.space : Pads spaces.
      • styles.space.left, styles.space.right, styles.space.top, styles.space.bottom : Space of bounds.
      • styles.space.item : Space between 2 input rows.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-tweaker/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTweaker extends RexPlugins.UI.Tweaker {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var tweaker = new MyTweaker(scene, config);\n
"},{"location":"ui-tweaker/#add-input-row","title":"Add input row","text":"

An input row can fine-tuning properties of target object.

"},{"location":"ui-tweaker/#text-input-row","title":"Text input row","text":"

object[key] is a text value.

tweaker.addInput(object, key, {    // view: 'string',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n\n// autoUpdate: true,\n// onValidate: undefined,\n// onValueChange: undefined,    \n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'string',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n\n// autoUpdate: true,\n// onValidate: undefined,\n// onValueChange: undefined,    \n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'string', if bindingTarget is not given.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.
  • autoUpdate :
    • true : Update binding key when user input. Default behavior.
    • false : Use onValueChange to set value of binding key when user input.
  • onValidate :
    • Callback invoked when new value input.
      function(newValue, oldValue, bindingTarget, bindingKey) { return true;\n}\n
      • true : Accept this new value.
      • false : Reject this new value.
    • undefined : Always accept new value changing. Default behavior.
  • onValueChange :
    • Callback invoked when binding value changing.
      function(newValue, oldValue, bindingTarget, bindingKey) { }\n
    • undefined : Ignore this feature. Default value.

See Style of text input

"},{"location":"ui-tweaker/#text-area-input-row","title":"Text-Area input row","text":"

object[key] is a text value.

tweaker.addInput(object, key, {    view: 'textarea',\n\n// height: undefined,\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n\n// autoUpdate: true,\n// onValidate: undefined,\n// onValueChange: undefined,    \n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\nview: 'textarea',\n\n// height: undefined,\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n\n// autoUpdate: true,\n// onValidate: undefined,\n// onValueChange: undefined,    \n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : 'textarea'.
  • height : Height of this input row.
    • undefined : Use children height.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.
  • autoUpdate :
    • true : Update binding key when user input. Default behavior.
    • false : Use onValueChange to set value of binding key when user input.
  • onValidate :
    • Callback invoked when new value input.
      function(newValue, oldValue, bindingTarget, bindingKey) { return true;\n}\n
      • true : Accept this new value.
      • false : Reject this new value.
    • undefined : Always accept new value changing. Default behavior.
  • onValueChange :
    • Callback invoked when binding value changing.
      function(newValue, oldValue, bindingTarget, bindingKey) { }\n
    • undefined : Ignore this feature. Default value.

See Style of text-area input

"},{"location":"ui-tweaker/#text-input-from-list","title":"Text input from list","text":"

object[key] is a text value.

tweaker.addInput(object, key, {\n// view: 'list',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0, /* icon: , iconFrame, .. */ },\n{text: text1, value: value1, /* icon: , iconFrame, .. */ },\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'list',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0, /* icon: , iconFrame, .. */ },\n{text: text1, value: value1, /* icon: , iconFrame, .. */ },\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'list', if bindingTarget is not given.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • options : Option list, each item contains
    • text : Display text.
    • value : Set key to this value.
    • icon, iconFrame, ... : See Reset display content of Label
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of list input

"},{"location":"ui-tweaker/#text-input-from-buttons","title":"Text input from buttons","text":"

object[key] is a text value.

tweaker.addInput(object, key, {\nview: 'buttons',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0},\n{text: text1, value: value1},\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\nview: 'buttons',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0},\n{text: text1, value: value1},\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'buttons'.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • options : Option list, each item contains
    • text : Display text.
    • value : Set key to this value.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of buttons input

"},{"location":"ui-tweaker/#number-input-row","title":"Number input row","text":"

object[key] is a number value.

tweaker.addInput(object, key, {\n// view: 'number',\n// int: undefined,\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'number',\n// int: undefined,\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'number', if bindingTarget is not given.
  • int : Set to true to truncate float number to integer number.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of text input

"},{"location":"ui-tweaker/#number-input-in-a-range","title":"Number input in a range","text":"

object[key] is a number value.

tweaker.addInput(object, key, {\n// view: 'range',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\nmin: minValue, max: maxValue,\n// step: undefined,\n\n// format: function(value) { return s; },\n// inputTextReadOnly: false,\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'range',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\nmin: minValue, max: maxValue,\n// step: undefined,\n\n// format: function(value) { return s; },\n// inputTextReadOnly: false,\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'range', if bindingTarget is not given.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • min, max : Minimum, maximun value of range.
  • step : Step/gap of slider, optional.
  • format : Callback to return formatted string for input text field.
    function(value) {\nreturn s;\n}\n
  • inputTextReadOnly :
    • false : Input text field is editable. Default behavior.
    • true : Input text field is read-only.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of range input

"},{"location":"ui-tweaker/#number-input-in-inc-dec-buttons","title":"Number input in inc-dec buttons","text":"

object[key] is a number value.

tweaker.addInput(object, key, {\nview: 'incdec',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// min: undefined, \n// max: undefined,\n// step: 1,\n\n// format: function(value) { return s; },\n// inputTextReadOnly: false,\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'incdec',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// min: undefined, \n// max: undefined,\n// step: 1,\n\n// format: function(value) { return s; },\n// inputTextReadOnly: false,\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'incdec', if bindingTarget is not given.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • step : Incremental or decremental value when clicking inc-button, or dec-button
  • min, max : Minimum, maximun value of range, optional.
  • format : Callback to return formatted string for input text field.
    function(value) {\nreturn s;\n}\n
  • inputTextReadOnly :
    • false : Input text field is editable. Default behavior.
    • true : Input text field is read-only.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of incdec input

"},{"location":"ui-tweaker/#number-input-from-list","title":"Number input from list","text":"

object[key] is a number value.

tweaker.addInput(object, key, {\n// view: 'list',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0},\n{text: text1, value: value1},\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'list',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0},\n{text: text1, value: value1},\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'list', if bindingTarget is not given.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • options : Option list, each item contains
    • text : Display text.
    • value : Set key to this value.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of list input

"},{"location":"ui-tweaker/#number-input-from-buttons","title":"Number input from buttons","text":"

object[key] is a number value.

tweaker.addInput(object, key, {\nview: 'buttons',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0},\n{text: text1, value: value1},\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\nview: 'buttons',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0},\n{text: text1, value: value1},\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'buttons'.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • options : Option list, each item contains
    • text : Display text.
    • value : Set key to this value.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of buttons input

"},{"location":"ui-tweaker/#color-input","title":"Color input","text":"

object[key] is a number value.

tweaker.addInput(object, key, {\nview: 'color',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\nview: 'color',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'color'.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of color input

"},{"location":"ui-tweaker/#boolean-input-row","title":"Boolean input row","text":"

object[key] is a boolean value.

tweaker.addInput(object, key, {\n// view: 'boolean',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'boolean',\n// view: 'toggleSwitch',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'boolean', or 'toggleSwitch', if bindingTarget is not given.
    • 'boolean' : Checkbox input. Default behavior.
    • 'toggleSwitch' : Toggle switch input.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of boolean input

"},{"location":"ui-tweaker/#value-callbacks-row","title":"Value callbacks row","text":"
tweaker.addInput({\nbindingTarget: object,\n\nonGetValue(bindingTarget) {\n\n},\n\nonSetValue(bindingTarget, value) {\n\n},\n\nview: ,\n\n// Other properties..\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • onGetValue : Callback to get dispaly value
    function(bindingTarget) {\nreturn value;\n}\n
  • onSetValue : Callback to set value to bindingTarget
    function(bindingTarget, value) {        }\n
  • view : Any kind of view listed before.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

Note

No bindingKey parameter in this case.

"},{"location":"ui-tweaker/#add-button","title":"Add button","text":"
tweaker.addButton({\n// bindingTarget: object,\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\ntitle: undefined,\n\nlabel: undefined,\n\ncallback: function(target) {},\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target will pass to callback. Optional.
    • Can bind target later via tweaker.setBindingTarget(object).
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label.
  • label : Display text of button, a string or a plain object.
    {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n}\n
  • callback : Callback when clicking button
    function(target) { }\n
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of botton

"},{"location":"ui-tweaker/#add-buttons","title":"Add buttons","text":"
tweaker.addButtons({\n// bindingTarget: object,\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\ntitle: undefined,\n\nbuttons:[\n{\nlabel: undefined,\ncallback: function(target) {},\n},\n{\nlabel: undefined,\ncallback: function(target) {},\n},\n// ...\n],\n\nwrap: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target will pass to callback. Optional.
    • Can bind target later via tweaker.setBindingTarget(object).
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label.
  • buttons : Array of button label and button callback
    {\nlabel: undefined,\ncallback: function(target) {},\n}\n
    • label : Display text of button, a string or a plain object. ```javascript { text: '',

      icon: undefined, \niconFrame: undefined,\niconSize: undefined,\n\naction: undefined, \nactionFrame: undefined,\nactionSize: undefined,\n

      } `` -callback: Callback when clicking button

      function(target) { }\n
      -wrap: Layout mode of buttons. -true: [fixwidth-sizer](ui-fixwidthsizer.md) layout. -false: [sizer](ui-sizer.md) layout. Default behavior. -key: Add this child into childMap, which could be read back bytweaker.getElement(key). -undefined` : Don't add this child. Default value.

See Style of botton

"},{"location":"ui-tweaker/#add-separator","title":"Add separator","text":"
tweaker.addSeparator();\n

See Style of separator

"},{"location":"ui-tweaker/#add-folder","title":"Add folder","text":"

Folder contains collapsible child tweaker game object.

var childTweaker = tweaker.addFolder({\ntitle: titleA,\n\n// expanded: true,\n});\n\n// childTweaker.addInput(...)\n
  • childTweaker : Child tweaker game object. Add input rows by addInput method.
  • title Title of folder. Click title can collapse or expand child tweaker game object.
  • expanded :
    • true : Expand child tweaker game object at beginning. Default behavior.
    • false : Collapse child tweaker game object at beginning.

See Style of folder

"},{"location":"ui-tweaker/#add-tab","title":"Add tab","text":"

Tab containes pages. Each page is a tweaker game object.

var childrenTweakers = tweaker.addTab({\npages: [\n{\ntitle: titleA, // show: false\n},\n{\ntitle: titleB\n// show: false\n},\n// ...\n]\n});\n\n// childrenTweakers[0].addInput(...)\n// childrenTweakers[1].addInput(...)\n
  • childrenTweakers : Array of children tweaker game object. Add input rows by addInput method.
  • pages : Array of page setting.
    {\ntitle: titleA,\nshow: false,\n}\n
    • title : Display text of page title
    • show : Set to true to show this page at beginning

See Style of tab

"},{"location":"ui-tweaker/#add-columns","title":"Add columns","text":"

Multiple columns in a row. Each column is a tweaker game object.

var childrenTweakers = tweaker.addColumns(amount);\n\n// childrenTweakers[0].addInput(...)\n// childrenTweakers[1].addInput(...)\n

or

var childrenTweakers = tweaker.addColumns({\n// title: title,\n\ncolumns: [\n{\n// width: 0,\n// expand: true\n},\n{\n// width: 0,\n// expand: true\n},\n]\n});\n\n// childrenTweakers[0].addInput(...)\n// childrenTweakers[1].addInput(...)\n
  • childrenTweakers : Array of children tweaker game object. Add input rows by addInput method.
  • amount : A number, amount of columns. Will use default column config.
  • columns : Array of column config, each column config contains
    • width : Minimum width of this column, default value is 0, will set proportion to 1.
    • expand : Expand height of this column, default value is true.

See Style of columns

"},{"location":"ui-tweaker/#add-wrap","title":"Add wrap","text":"

A tweaker panel which Wrap input rows into multiple lines.

var childTweaker = tweaker.addWrap({\n// title: titleA,\n\nitemWidth: 0,\nitemHeight: 0,\n});\n\n// childTweaker.addInput(...)\n
  • childTweaker : Child tweaker game object. Add input rows by addInput method.
  • title Title of folder. Click title can collapse or expand child tweaker game object.
  • itemWidth, itemHeight : Size of input row.

See Style of wrap

"},{"location":"ui-tweaker/#add-scrollable","title":"Add scrollable","text":"

Scrollable(Panel) contains child tweaker game object and slider.

var childTweaker = tweaker.addScrollable({\n// title: title,\n\n// height: 0\n});\n\n// childTweaker.addInput(...)\n
  • childTweaker : Child tweaker game object. Add input rows by addInput method.
  • title Title of scrolable.
    • A string : Title string.
    • undefined : Hide this title game object.
  • height :
    • A number : Height of this Scrollable(Panel).
    • undefined, or 0 : Expand this scrollable(Panel).

See Style of scrollable

"},{"location":"ui-tweaker/#add-rows","title":"Add rows","text":"

Add mutiple rows (input row, button, buttons, separator, folder, tab) in a single method

tweaker.addRows(properties, target);\n// tweaker.addRows(properties, target, monitor);\n
  • properties : A list of properties, each property could be one of
    • Input row
      {\n$key: '',\n// $target:\n// More properties...\n}\n
      • $key : Assign this value to bindingKey
      • $target : Assign this value to bindingTarget
        • undefined : Use target parameter from addRows method. Default behavior
      • More properties. See
        • Text input row,
        • Text area input row,
        • Text input from list
        • Text input from buttons
        • Number input row
        • Number input in a range
        • Number input from list
        • Number input from buttons
        • Color input row
        • Boolean input row
        • Value callback row
    • Button
      {\n$type: 'button', title: '', label: '',\ncallback(target) {\n}\n}\n
    • Buttons
    • Separator
      { $type: 'separator' }\n
    • Folder
      {\n$type: 'folder', title: '',\n// $target: \n$properties: [\n// ...\n]\n}\n
      • $target : Override target value pass to remainder $properties.
        • undefined : Use previous target value. Default behavior.
    • Tab
      {\n$type: 'tab',\n// $target:\npages: [\n{\ntitle: '',\n$properties: [\n// ...\n]\n},\n{\ntitle: '',\n$properties: [\n// ...\n]\n},\n// ... More pages\n]\n}\n
      • $target : Override target value pass to remainder $properties.
        • undefined : Use previous target value. Default behavior.
    • Columns
      {\n$type: 'columns',\n// $target:\ncolumns: [\n{\n// width: 0,\n// expand: true,\n$properties: [\n// ...\n]\n},\n{\n// width: 0,\n// expand: true,\n$properties: [\n// ...\n]\n},\n// ... More columns\n]\n}\n
      • $target : Override target value pass to remainder $properties.
        • undefined : Use previous target value. Default behavior.
    • Wrap
      {\n$type: 'wrap', title: '',\n// $target: \n$properties: [\n// ...\n]\n}\n
      • $target : Override target value pass to remainder $properties.
        • undefined : Use previous target value. Default behavior.
    • Scrollable
      {\n$type: 'scrollable', title: undefined,\n// $target: \n$properties: [\n// ...\n]\n}\n
      • $target : Override target value pass to remainder $properties.
        • undefined : Use previous target value. Default behavior.
  • monitor :
    • false : Don't update input text every tick from target.
    • true : Update input text from current object, in postupdate event of scene. Default behavior.
"},{"location":"ui-tweaker/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

tweaker.layout();\n

See also - dirty

"},{"location":"ui-tweaker/#styles","title":"Styles","text":""},{"location":"ui-tweaker/#style-of-text-input","title":"Style of text input","text":"

Style of text-area input is defined in

  • styles.inputRow.title
  • styles.inputRow.inputText
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\ninputText: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\nfocusStyle: {\n// color:\n// color2:\n// horizontalGradient:\n\n// stroke:\n// strokeThickness:\n\n// cornerRadius:\n// cornerIteration:\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\ncursorStyle: {\n// bold:\n// italic:\n// fontSize:\n// fontFamily:\n// color:\n// stroke:\n// strokeThickness:\n// shadowColor:\n// shadowOffsetX:\n// shadowOffsetY:\n// shadowBlur:\n// backgroundColor:\n// backgroundHeight:\n// backgroundBottomY:\n// offsetX:\n// offsetY:\n}\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-text-area-input","title":"Style of text-area input","text":"

Style of text-area input is defined in

  • styles.inputRow.title
  • styles.inputRow.inputTextArea
  • styles.inputRow.inputText
  • styles.inputRow.slider
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\ninputTextArea: {\nheight: undefined,\n\ntext: {\n\n},\n\nslider: {\n// ...\n}\n},\n\ninputText: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\nfocusStyle: {\n// color:\n// color2:\n// horizontalGradient:\n\n// stroke:\n// strokeThickness:\n\n// cornerRadius:\n// cornerIteration:\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\ncursorStyle: {\n// bold:\n// italic:\n// fontSize:\n// fontFamily:\n// color:\n// stroke:\n// strokeThickness:\n// shadowColor:\n// shadowOffsetX:\n// shadowOffsetY:\n// shadowBlur:\n// backgroundColor:\n// backgroundHeight:\n// backgroundBottomY:\n// offsetX:\n// offsetY:\n}\n},\n\nslider: {\ntrack: {\nheight: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nindicator: {\nheight: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nthumb: {\nwidth: 0, height: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n}\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n}\n}\n}\n

Style of text-area is defined at styles.inputRow.inputTextArea :

  • Define style of input text at styles.inputRow.inputTextArea.text, if not given, it will use styles.inputRow.inputText.
  • Define style of slider at styles.inputRow.inputTextArea.slider, if not given, it will use styles.inputRow.slider.
"},{"location":"ui-tweaker/#style-of-list-input","title":"Style of list input","text":"

Style of text/number list input is defined in

  • styles.inputRow.title
  • styles.inputRow.list
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nlist: {\nlabel: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n\n},\n\nbutton: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n\n'hover.color': undefined,\n'hover.alpha': undefined,\n'hover.strokeColor': undefined,\n'hover.strokeAlpha': undefined,\n'hover.strokeWidth': undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nlist: {\nalignParent: 'text',\nalignSide: 'left',\nexpandDirection: 'down',\n}\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-buttons-input","title":"Style of buttons input","text":"

Style of buttons input is defined in

  • styles.inputRow.title
  • styles.inputRow.button
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nbutton: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n},\n\nexpand: true\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-range-input","title":"Style of range input","text":"

Style of range input is defined in

  • styles.inputRow.title
  • styles.inputRow.slider
  • styles.inputRow.inputText
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nslider: {\ntrack: {\nheight: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nindicator: {\nheight: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nthumb: {\nwidth: 0, height: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n}\n},\n\ninputText: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\nfocusStyle: {\n// color:\n// color2:\n// horizontalGradient:\n\n// stroke:\n// strokeThickness:\n\n// cornerRadius:\n// cornerIteration:\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\ncursorStyle: {\n// bold:\n// italic:\n// fontSize:\n// fontFamily:\n// color:\n// stroke:\n// strokeThickness:\n// shadowColor:\n// shadowOffsetX:\n// shadowOffsetY:\n// shadowBlur:\n// backgroundColor:\n// backgroundHeight:\n// backgroundBottomY:\n// offsetX:\n// offsetY:\n}\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\nrange: {\nslider: 0,\ninputText: 0,\n}\n}\n\n}\n}\n}\n
  • Set proportion.range.slider and proportion.range.inputText to layout slider and inputText.
"},{"location":"ui-tweaker/#style-of-inc-dec-input","title":"Style of inc-dec input","text":"

Style of range input is defined in

  • styles.inputRow.title
  • styles.inputRow.incDec
  • styles.inputRow.inputText
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nincDec: {\nincButton: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nicon: {\nkey:,\nframe:,\n},\n\ntext: null,\naction: null,\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\ndecButton: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nicon: {\nkey:,\nframe:,\n},\n\ntext: null,\naction: null,\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\ninputTextIndex: 0, // 0,1,2\n},\n\n\ninputText: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\nfocusStyle: {\n// color:\n// color2:\n// horizontalGradient:\n\n// stroke:\n// strokeThickness:\n\n// cornerRadius:\n// cornerIteration:\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\ncursorStyle: {\n// bold:\n// italic:\n// fontSize:\n// fontFamily:\n// color:\n// stroke:\n// strokeThickness:\n// shadowColor:\n// shadowOffsetX:\n// shadowOffsetY:\n// shadowBlur:\n// backgroundColor:\n// backgroundHeight:\n// backgroundBottomY:\n// offsetX:\n// offsetY:\n}\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\nrange: {\nslider: 0,\ninputText: 0,\n}\n}\n\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-color-input","title":"Style of color input","text":"

Style of color input is defined in

  • styles.inputRow.title
  • styles.inputRow.inputText
  • styles.inputRow.colorInput
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\ncolorInput: {\nswatch: {\nradius: 0,\nsize: undefined,\n},\n\ninputText: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\nfocusStyle: {\n// color:\n// color2:\n// horizontalGradient:\n\n// stroke:\n// strokeThickness:\n\n// cornerRadius:\n// cornerIteration:\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\ncursorStyle: {\n// bold:\n// italic:\n// fontSize:\n// fontFamily:\n// color:\n// stroke:\n// strokeThickness:\n// shadowColor:\n// shadowOffsetX:\n// shadowOffsetY:\n// shadowBlur:\n// backgroundColor:\n// backgroundHeight:\n// backgroundBottomY:\n// offsetX:\n// offsetY:\n}\n},                // inputText: false,\n\ncolorPicker: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n}\n},\n\ncolorComponents: {\ninputText: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\nfocusStyle: {\n// color:\n// color2:\n// horizontalGradient:\n\n// stroke:\n// strokeThickness:\n\n// cornerRadius:\n// cornerIteration:\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\ncursorStyle: {\n// bold:\n// italic:\n// fontSize:\n// fontFamily:\n// color:\n// stroke:\n// strokeThickness:\n// shadowColor:\n// shadowOffsetX:\n// shadowOffsetY:\n// shadowBlur:\n// backgroundColor:\n// backgroundHeight:\n// backgroundBottomY:\n// offsetX:\n// offsetY:\n}\n\n}\n}\n\n// colorComponents: false,\n\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-boolean-input","title":"Style of boolean input","text":"

Style of boolean input is defined in

  • styles.inputRow.title
  • styles.inputRow.checkbox, or styles.inputRow.toggleSwitch
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\n// For checkbox view\ncheckbox: {\n// size: undefined,\n\ncolor: 0x005cb2,\nboxFillAlpha: 1,\nuncheckedColor: null,\nuncheckedBoxFillAlpha: 1,\n\nboxLineWidth: 4,\nboxStrokeColor: 0x005cb2,\nboxStrokeAlpha: 1,\nuncheckedBoxStrokeColor: 0x005cb2,\nuncheckedBoxStrokeAlpha: 1,\n\ncheckerColor: 0xffffff,\ncheckerAlpha: 1,\n\ncircleBox: false\n\nanimationDuration: 150,\n\nreadOnly: false,\n},\n\n// For toggle switch view\ntoggleSwitch: {\n// size: undefined,\n\ncolor: 0x005cb2,\ntrackFillAlpha: 1,\nfalseValueTrackColor: undefined,\nfalseValueTrackFillAlpha: 1,\n\nthumbColor: 0xffffff,\nthumbAlpha: 1,\n\ntrackWidth: 0.9,\ntrackHeight: 0.5,\ntrackCornerRadius: (trackHeight * 0.5),\n\nthumbHeight: (trackHeight * 0.9),\nthumbWidth: (thumbHeight),\nthumbCornerRadius: (thumbHeight * 0.5),\n\nthumbLeft: 0.3,\nthumbRight: (1 - thumbLeft),\nrtl: false,\n\nanimationDuration: 150,\n\nreadOnly: false,\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-botton","title":"Style of botton","text":"

Style of button is defined in

  • styles.inputRow.title
  • styles.inputRow.button
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nbutton: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-separator","title":"Style of separator","text":"

Style of separator is defined in

  • styles.separator
{\n// style: {...}\nstyles: {\nseparator: {\nheight: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-folder","title":"Style of folder","text":"

Style of folder is defined in

  • styles.folder
{\n// style: {...}\nstyles: {\nfolder: {\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n},\n\nexpandedIcon: {\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n},\n\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, }\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-tab","title":"Style of tab","text":"

Style of tab is defined in

  • styles.tab
{\n// style: {...}\nstyles: {\ntab: {\ntab: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n\n'active.color': undefined,\n'active.alpha': undefined,\n'active.strokeColor': undefined,\n'active.strokeAlpha': undefined,\n'active.strokeWidth': undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nwrapTabs: false,\n\ntabs: {\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, item: 0,\n}\n},\n\npages: {\nfadeIn: 0,\n}\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-columns","title":"Style of columns","text":"

Style of columns is defined in

  • styles.columns
{\n// style: {...}\nstyles: {\ncolumns: {\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n},\n\nexpandedIcon: {\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n},\n\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\n//background: [\n//    {\n//        radius: 0,\n//        // radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n//\n//        color: undefined,\n//        alpha: undefined,\n//        strokeColor: undefined,\n//        strokeAlpha: undefined,\n//        strokeWidth: undefined,\n//    }\n//],\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, column: 0,\n}\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-wrap","title":"Style of wrap","text":"

Style of wrap is defined in

  • styles.wrap
{\n// style: {...}\nstyles: {\nwrap: {\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n},\n\nexpandedIcon: {\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n},\n\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nspace: {\nitem: 0, line: 0\n},\n\nalign: 'justify-cneter'\n}\n}\n}\n
  • align : Align children of a line.
    • 0, 'left' : Align children of a line to left/top side.
    • 1, 'right' : Align children of a line to right/bottom side.
    • 2, 'center' : Align children of a line to ceter.
    • 3, 'justify', 'justify-left' : If remainder space is less or equal than 25%, then justify children. Else align children to left/top side.
    • 4, 'justify-right' : If remainder space is less or equal than 25%, then justify children. Else align children to right/bottom side.
    • 5, 'justify-cneter' : If remainder space is less or equal than 25%, then justify children. Else align children to center.
"},{"location":"ui-tweaker/#style-of-scrollable","title":"Style of scrollable","text":"

Style of scrollable is defined in

  • styles.scrollable
{\n// style: {...}\nstyles: {\nscrollable: {\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n},\n\nexpandedIcon: {\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n},\n\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nslider: {\ntrack: { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n},\n\nthumb: { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n},\n\n// hideUnscrollableSlider: false,\n// adaptThumbSize: false,\n// minThumbSize: undefined,\n},\n\nspace: {\npanel:0, }\n}\n}\n}\n
"},{"location":"ui-tweaker/#bind-target","title":"Bind target","text":"

All input rows will bind to this new target, and update display status.

tweaker.setBindingTarget(object);\n
"},{"location":"ui-tweaker/#events","title":"Events","text":"
  • On value change of any bindingKey
    tweaker.on('valuechange', function(newValue, oldValue, bindingTarget, bindingKey) {\n\n})\n
"},{"location":"ui-tweaker/#get-element","title":"Get element","text":"
  • Get by key
    var gameObject = tweaker.getElement(key);\n
    • key : Add by key parameter in tweaker.addInput(config) method
      tweaker.addInput({\nkey: ...\n})\n
  • Get by name
    var gameObject = tweaker.getElement('#' + name);\n// var gameObject = pages.getElement('#' + name, recursive);\n
    or
    var gameObject = tweaker.getByName(name);\n// var gameObject = tweaker.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-tweaker/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"uniqueitemlist/","title":"Unique item list","text":""},{"location":"uniqueitemlist/#introduction","title":"Introduction","text":"

List of unique items. Support array and set methods.

  • Author: Rex
  • Data structure
"},{"location":"uniqueitemlist/#usage","title":"Usage","text":"

Sample code

"},{"location":"uniqueitemlist/#install-plugin","title":"Install plugin","text":""},{"location":"uniqueitemlist/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexuniqueitemlistplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuniqueitemlistplugin.min.js', true);\n
  • Add list object
    var listA = scene.plugins.get('rexuniqueitemlistplugin').add(config);\n
"},{"location":"uniqueitemlist/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UniqueItemListPlugin from 'phaser3-rex-plugins/plugins/uniqueitemlist-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexUniqueItemList',\nplugin: UniqueItemListPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add list object
    var listA = scene.plugins.get('rexUniqueItemList').add(config);\n
"},{"location":"uniqueitemlist/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import UniqueItemList from 'phaser3-rex-plugins/plugins/uniqueitemlist.js';\n
  • Add list object
    var listA = new UniqueItemList();\n
"},{"location":"uniqueitemlist/#create-instance","title":"Create instance","text":"
var listA = scene.plugins.get('rexUniqueItemList').add({\n// items: undefined,\n// autoCleanup: true\n});\n
  • items : Initial items.
  • autoCleanup : Set true to remove item when item is destroyed (from item's 'destroy' event)

or

var listA = scene.plugins.get('rexUniqueItemList').add(items);\n
"},{"location":"uniqueitemlist/#items","title":"Items","text":"
  • Get first item
    var item = listA.getFirst();\n
  • Get last item
    var item = listA.getLast();\n
  • Get item at index
    var item = listA.get(index);\n
  • Get a random item
    var item = listA.getRandom();\n
  • Get items
    var items = listA.getItems();\n
  • Clone items to a new array
    var items = listA.cloneItems();\n
"},{"location":"uniqueitemlist/#item-count","title":"Item count","text":"
  • Get item count
    var count = listA.length;\n
  • List is empty
    var isEmpty = listA.isEmpty();\n
"},{"location":"uniqueitemlist/#contains","title":"Contains","text":"
  • Has item
    var hasItem = listA.contains(item);\n
  • Has any item
    var hasAny = listA.any(listB);\n
  • Has all items
    var hasAll = listA.all(listB);\n
"},{"location":"uniqueitemlist/#array-operations","title":"Array operations","text":""},{"location":"uniqueitemlist/#add","title":"Add","text":"
  • Add to last
    listA.add(item);\n
    or
    listA.addLast(item);\n
  • Add to first
    listA.addFirst(item);\n
  • Insert to index
    listA.add(item, index);\n
  • Insert, or move to index
    listA.add(item, iindex, true);\n
  • Add items
    listA.addMultiple(items);\n
  • Clone list
    var newList = listA.clone();\n// listA.clone(listB)\n
"},{"location":"uniqueitemlist/#remove","title":"Remove","text":"
  • Remove item
    listA.remove(item);\n
  • Remove first
    listA.removeFirst();\n
  • Remove last
    listA.removeLast();\n
  • Remove item at index
    listA.remove(undefined, index);\n
  • Remove items
    listA.removeMultiple(items);\n
  • Remove all items
    listA.clear();\n
  • Destroy all items
    listA.clear(true);\n
"},{"location":"uniqueitemlist/#pop","title":"Pop","text":"
  • Pop first item
    var item = listA.pop();\n
    or
    var item = listA.popFirst();\n
  • Pop last item
    var item = listA.popLast();\n
  • Pop item at index
    var item = listA.pop(index);\n
  • Pop a random item
    var item = listA.popRandom();\n
"},{"location":"uniqueitemlist/#slice","title":"Slice","text":"
  • Extract items from startIndex to endIndex (item of endIndex is included)
    var newList = listA.slice(startIndex, endIndex);\n// listA.slice(startIndex, endIndex, listB);\n
"},{"location":"uniqueitemlist/#sort","title":"Sort","text":"
  • Sort
    list.sort(function(itemA, itemB) {\nif (itemA > itemB) {\nreturn 1;\n} else if (itemA < itemB) {\nreturn -1;\n} else {\nreturn 0;\n}\n})\n
  • Reverse
    listA.reverse();\n
  • Shuffle
    listA.shuffle();\n
"},{"location":"uniqueitemlist/#set-operations","title":"Set operations","text":"
  • C = A | B
    var listC = listA.union(listB);\n// listA.union(listB, listC);\n
    • listC : Result unique-item-list. Can be listA, or listB.
  • C = A & B
    var listC = listA.intersect(listB);\n// listA.intersect(listB, listC);\n
    • listC : Result unique-item-list. Can be listA, or listB.
  • C = A - B
    var listC = listA.difference(listB);\n// listA.difference(listB, listC);\n
    • listC : Result unique-item-list. Can be listA, or listB.
"},{"location":"uniqueitemlist/#call-method","title":"Call method","text":"

Apply method of each item.

listA.call(fnName, arg0, arg1, arg2, ...);\n
  • fnName : Method name of item.
  • arg0, arg1, arg2 : Arguments of fnName method.

Warning

Don't add or remove any item during this method.

listA.call(function(item, i) {\n// ....\n}, scope);\n
  • callback : A function object.
    function(item, i) {\n\n}\n
"},{"location":"uuid/","title":"UUID","text":""},{"location":"uuid/#introduction","title":"Introduction","text":"

Creates and returns an RFC4122 version 4 compliant UUID, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"uuid/#usage","title":"Usage","text":"
var uuid = Phaser.Utils.String.UUID();\n
"},{"location":"vector2/","title":"Vector2","text":""},{"location":"vector2/#introduction","title":"Introduction","text":"

A representation of a vector in 2D space ({x, y}), built-in object of phaser.

  • Author: Richard Davey
"},{"location":"vector2/#usage","title":"Usage","text":""},{"location":"vector2/#create-object","title":"Create object","text":"
var vector = new Phaser.Math.Vector2();\n// var vector = new Phaser.Math.Vector2(x, y);\n// var vector = new Phaser.Math.Vector2({x, y});\n
"},{"location":"vector2/#clone","title":"Clone","text":"
var newVector = vector.clone();\n
"},{"location":"vector2/#set-components","title":"Set components","text":"
  • Set (x, y)
    vector.set(x, y);\n// vector.setTo(x, y);\n
    or
    vector.copy({x, y});\n// vector.setFromObject({x, y});\n
  • Set angle
    vector.setAngle(angle);\n
    • angle : Angle in radians.
  • Rotate
    vector.rotate(delta);\n
    • delta : The angle to rotate by, in radians.
  • Project
    vector.project(srcVector2);\n
  • Set length
    vector.setLength(length);\n
  • Set from polar coordinate
    vector.setToPolar(azimuth, radius);\n
    • azimuth : The angular coordinate, in radians.
    • radius : The radial coordinate (length). Default is 1.
  • Reset to (0, 0)
    vector.reset();\n
"},{"location":"vector2/#get-componments","title":"Get componments","text":"
  • X, Y
    var x = vector.x;\nvar y = vector.y;\n
  • Angle
    var angle = vector.angle(); // angle in radians\n
  • Length
    var length = vector.length();\n
    or
    var lengthSq = vector.lengthSq(); // squared\n
"},{"location":"vector2/#methods","title":"Methods","text":"
  • Scale
    vector.scale(value);\n
  • Limit the length
    vector.limit(value);\n
  • Normalize
    vector.normalize();\n
  • Negate
    vector.negate();\n
  • Rotate perpendicular
    vector.normalizeRightHand();\nvector.normalizeLeftHand();\n
  • Reflect
    • Reflect this Vector off a line defined by a normal.
      vector.reflect(normal);\n
      • normal : A vector perpendicular to the line.
    • Reflect this Vector across another.
      vector.mirror(axis);\n
      • axis : A vector to reflect across.
"},{"location":"vector2/#vector-methods","title":"Vector methods","text":"
  • Add
    vector.add(src); // src: {x, y}\n
  • Subtract
    vector.subtract(src); // src: {x, y}\n
  • Multiply
    vector.multiply(src); // src: {x, y}\n
  • Divide
    vector.divide(src); // src: {x, y}\n
  • Dot
    var value = vector.dot(src); // src: {x, y}\n
  • Cross
    var value = vector.cross(src); // src: {x, y}\n
  • Fuzzy Equal
    var equal = vector.fuzzyEquals(src); // src: {x, y}\n// var equal = vector.fuzzyEquals(src, epsilon);\n
"},{"location":"vector2/#points-method","title":"Points method","text":"
  • Distance between 2 points.
    var distance = vector.distance(src);\n
    or
    var distanceSq = vector.distanceSq(src); // squared\n
  • Linearly interpolate between 2 points.
    vector.lerp(src, t); // src: {x, y}\n
    • t : The interpolation percentage, between 0 and 1.
"},{"location":"vector2/#constant","title":"Constant","text":"
  • Zero (0,0)
    var vector = Phaser.Math.Vector2.ZERO;\n
  • One (1,1)
    var vector = Phaser.Math.Vector2.ONE;\n
  • Right (1,0)
    var vector = Phaser.Math.Vector2.RIGHT;\n
  • Left (-1,0)
    var vector = Phaser.Math.Vector2.LEFT;\n
  • Up (0,-1)
    var vector = Phaser.Math.Vector2.UP;\n
  • Down (0,1)
    var vector = Phaser.Math.Vector2.DOWN;\n
"},{"location":"video/","title":"Video","text":""},{"location":"video/#introduction","title":"Introduction","text":"

Handling playback of a video file, video stream or media stream.

  • Author: Richard Davey
"},{"location":"video/#usage","title":"Usage","text":""},{"location":"video/#load-video","title":"Load video","text":"
scene.load.video(key, url, noAudio);\n

Reference: load video

Cross-origin

Can't load video cross-origin via scene.load.video(...). Using scene.add.video(x, y).loadURL(urls, noAudio, crossOrigin) to load video cross-origin.

"},{"location":"video/#add-video-object","title":"Add video object","text":""},{"location":"video/#reference-video-from-video-cache","title":"Reference video from Video Cache","text":"
var video = scene.add.video(x, y, key);\n
  • key : Key of the Video this Game Object will play, as stored in the Video Cache.
"},{"location":"video/#load-video-from-url","title":"Load video from URL","text":"
  1. Add video object
    var video = scene.add.video(x, y);\n
  2. Play video from URL
    video.loadURL(url);\n// video.loadURL(urls, noAudio, crossOrigin);\n
    • noAudio : Does the video have an audio track? If not you can enable auto-playing on it.
      • false : Has audio track. Default behavior.
    • crossOrigin : The value to use for the crossOrigin property in the video load request.
      • undefined : crossorigin will not be set in the request. Default behavior.
      • 'anonymous'
      • 'use-credentials'
"},{"location":"video/#load-video-from-mediastream","title":"Load video from MediaStream","text":"
video.loadMediaStream(stream);\n// video.loadMediaStream(stream, noAudio, crossOrigin);\n
  • stream : The MediaStream object.
  • noAudio : Does the video have an audio track? If not you can enable auto-playing on it.
    • false : Has audio track. Default behavior.
  • crossOrigin : The value to use for the crossOrigin property in the video load request.
    • undefined : crossorigin will not be set in the request. Default behavior.
    • 'anonymous'
    • 'use-credentials'
navigator.mediaDevices.getUserMedia({ video: true, audio: false })\n.then(function(stream) {\nvideo.loadMediaStream(stream, true);\nvideo.play();\n})\n.catch(function(err) {\n\n})\n
  • navigator.mediaDevices.getUserMedia
"},{"location":"video/#get-first-frame","title":"Get first frame","text":"
video.getFirstFrame();\n
"},{"location":"video/#size","title":"Size","text":"
  • Initial size : 256x265 (video.setSize(256, 256))
  • Size after playing : Size of video from metadata
"},{"location":"video/#play","title":"Play","text":"
video.play();\n// video.play(loop, markerIn, markerOut);\n
  • loop : Should the video loop automatically when it reaches the end? Please note that not all browsers support seamless video looping for all encoding formats.
  • markerIn, markerOut : Optional in/out marker time, in seconds, for playback of a sequence of the video.

Play video first time

Call video.play() when playing video first time.

Note

If you need audio in your videos, then you'll have to consider the fact that the video cannot start playing until the user has interacted with the browser, into your game flow.

"},{"location":"video/#pause","title":"Pause","text":"
  • Pause
    video.setPaused();\n// video.setPaused(true);\n
  • Resume
    video.setPaused(false);\n

Play video after paused

Call video.setPaused(false) to resume playing.

"},{"location":"video/#stop","title":"Stop","text":"

Stops the video playing and clears all internal event listeners.

video.stop();\n
"},{"location":"video/#is-playing","title":"Is playing","text":"
  • Is playing
    var isPlaying = video.isPlaying();  // (not PAUSE) and (not not ENDED)\n
  • Is paused
    var isPaused = video.isPaused();\n
"},{"location":"video/#playback-time","title":"Playback time","text":"
  • Get
    var playbackTime = video.getCurrentTime();\n
    or
    var t = video.getProgress(); // t: 0~1\n
  • Set
    • Set to
      video.setCurrentTime(playbackTime);  // time in seconds\n
      or
      video.seekTo(t); // t: 0~1\n
      • Is seeking
        var isSeeking = video.isSeeking();\n
    • Forward
      video.setCurrentTime('+' + time);  // time in seconds\n// video.setCurrentTime('+2');\n
    • Backeard
      video.setCurrentTime('-' + time);  // time in seconds\n// video.setCurrentTime('-2');\n
"},{"location":"video/#playback-rate","title":"Playback rate","text":"
  • Get
    var rate = video.getPlaybackRate();\n
  • Set
    video.setPlaybackRate(rate);\n
"},{"location":"video/#duration","title":"Duration","text":"
var duration = video.getDuration();  // time in seconds\n
"},{"location":"video/#volume","title":"Volume","text":"
  • Get
    var volume = video.getVolume();  // volume: 0~1\n
  • Set
    video.setVolume(volume);  // volume: 0~1\n
"},{"location":"video/#mute","title":"Mute","text":"
  • Get
    var muted = video.isMuted();  // muted: true/false\n
  • Set
    video.setMute(muted);  // muted: true/false\n
"},{"location":"video/#loop","title":"Loop","text":"
  • Get
    var loop = video.getLoop();  // loop: true/false\n
  • Set
    video.setLoop(loop);  // loop: true/false\n
"},{"location":"video/#video-key","title":"Video key","text":"
  • Get
    var key = video.getVideoKey();\n
  • Change video key (video source)
    video.changeSource(key);\n// video.changeSource(key, autoplay, loop, markerIn, markerOut);\n
    • autoplay : Should the video start playing immediately, once the swap is complete?
    • loop : Should the video loop automatically when it reaches the end? Not all browsers support seamless video looping for all encoding formats.
    • markerIn, markerOut : Optional in/out marker time, in seconds, for playback of a sequence of the video.
"},{"location":"video/#marks","title":"Marks","text":"
  • Add mark
    video.addMarker(key, markerIn, markerOut);\n
    • key : A unique name to give this marker.
    • markerIn, markerOut : The time, in seconds, representing the start/end of this marker.
  • Play mark
    video.playMarker(key, loop);\n
  • Remove mark
    video.removeMarker(key);\n
"},{"location":"video/#snapshot","title":"Snapshot","text":"
  1. Allocate a canvas texrure
    video.saveSnapshotTexture(key);\n
    • key : Texture key.
  2. Take a snapshot
    var canvasTexture = video.video.snapshot();\n// var canvasTexture = video.snapshot(width, height);\n
    or
    var canvasTexture = video.snapshotArea(x, y, srcWidth, srcHeight);\n// var canvasTexture = video.snapshotArea(x, y, srcWidth, srcHeight, destWidth, destHeight);\n
    • x, y : The horizontal/vertical location of the top-left of the area to grab from.
    • srcWidth, srcHeight : The width/height of area to grab from the video.
    • destWidth, destHeight : The destination width/height of the grab, allowing you to resize it.
    • canvasTexture : Canvas texture object.
      • Get key of texture
        var key = canvasTexture.key;\n
"},{"location":"video/#save-texture","title":"Save texture","text":"

The saved texture is automatically updated as the video plays. If you pause this video, or change its source, then the saved texture updates instantly.

var texture = video.saveTexture(key);\n// var texture = video.saveTexture(key, flipY);\n
  • flipY : Set to true if use it as the input for a Shader.
"},{"location":"video/#events","title":"Events","text":"
  • The media source doesn't represent a supported media format.
    video.on('unsupported', function(video, error){\n\n}, scope);\n
  • A Video is unlocked by a user gesture.
    video.on('unlocked', function(video, error){\n\n}, scope);\n
  • A Video tries to play a source that does not exist, or is the wrong file type.
    video.on('error', function(video, error){\n\n}, scope);\n
  • A Video has access to the metadata.
    video.on('metadata', function(video){\n\n}, scope);\n
  • A Video has exhausted its allocated time while trying to connect to a video source to start playback.
    video.on('timeout', function(video){\n\n}, scope);\n
  • A Video begins playback.
    video.on('play', function(video){\n\n}, scope);\n
  • First started or restarted.
    video.on('playing', function(video){\n\n}, scope);\n
  • The video has finished loading enough data for its first frame.
    video.on('textureready', function(video){\n\n}, scope);\n
  • A Video finishes playback by reaching the end of its duration, or markerOut.
    video.on('complete', function(video){\n\n}, scope);\n
  • A Video that is currently playing has looped.
    video.on('loop', function(video){\n\n}, scope);\n
  • A Video begins seeking to a new point in its timeline.
    video.on('seeking', function(video){\n\n}, scope);\n
  • A Video completes seeking to a new point in its timeline.
    video.on('seeked', function(video){\n\n}, scope);\n
  • Enough of the video source has been loaded, that the browser is able to render a frame from it.
    video.on('created', function(video, width, height){\n\n}, scope);\n
  • Stalled by stalled, suspend, waiting DOM event.
    video.on('stalled', function(video, width, height){\n\n}, scope);\n
  • A Video is stopped from playback via a call to the Video.stop method,
    video.on('stop', function(video){\n\n}, scope);\n
"},{"location":"video/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"video/#create-mask","title":"Create mask","text":"
var mask = video.createBitmapMask();\n

See mask

"},{"location":"video/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"viewport-coordinate/","title":"Viewport-coordinate","text":""},{"location":"viewport-coordinate/#introduction","title":"Introduction","text":"

Attach vpx, vpy properties to a game object, to set position according to proportion (vpx, vpy) of viewport, a rectangle).

  • Author: Rex
  • Method only
"},{"location":"viewport-coordinate/#live-demos","title":"Live demos","text":"
  • Resize
"},{"location":"viewport-coordinate/#usage","title":"Usage","text":"

Sample code

"},{"location":"viewport-coordinate/#install-plugin","title":"Install plugin","text":""},{"location":"viewport-coordinate/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexviewportcoordinateplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexviewportcoordinateplugin.min.js', true);\n
  • Attach vpx, vpy properties.
    scene.plugins.get('rexviewportcoordinateplugin').add(gameObject, viewport, vpx, vpy);\ngameObject.vpx = 0.5;\ngameObject.vpy = 0.5;\n
"},{"location":"viewport-coordinate/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ViewportCoordinatePlugin from 'phaser3-rex-plugins/plugins/viewportcoordinate-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexViewportCoordinate',\nplugin: ViewportCoordinatePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Attach vpx, vpy, vpxOffset, vpyOffset properties.
    scene.plugins.get('rexViewportCoordinate').add(gameObject, viewport, vpx, vpy);\ngameObject.vpx = 0.5;\ngameObject.vpy = 0.5;\ngameObject.vpxOffset = 0;\ngameObject.vpyOffset = 0;\n
"},{"location":"viewport-coordinate/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import AddViewportCoordinateProperties from 'phaser3-rex-plugins/plugins/viewportcoordinate.js';\n
  • Attach vpx, vpy, vpxOffset, vpyOffset properties.
    AddViewportCoordinateProperties(gameObject, viewport, vpx, vpy);\ngameObject.vpx = 0.5;\ngameObject.vpy = 0.5;\ngameObject.vpxOffset = 0;\ngameObject.vpyOffset = 0;\n
"},{"location":"viewport-coordinate/#attach-properties","title":"Attach properties","text":"
scene.plugins.get('rexViewportCoordinate').add(gameObject, viewport, vpx, vpy, transformCallback);\n
  • vpx, vpy : Proportion of viewport.
  • vpxOffset, vpyOffset : Offset of position.
  • viewport : Viewport in rectangle
  • transformCallback : Transform callback.
    • undefined : Use default transform callback.
      function(vpx, vpy, vpxOffset, vpyOffset, viewport, out) {\ngameObject.x = viewport.x + (viewport.width * vpx) + vpxOffset;\ngameObject.y = viewport.y + (viewport.height * vpy) + vpyOffset;\n}\n

Changing

  • gameObject.vpx, gameObject.vpy, gameObject.vpxOffset, gameObject.vpyOffset
  • x, y, width, height of viewport (a rectangle)

Will change position (x , y) of game object.

"},{"location":"virtualjoystick/","title":"Virtual joystick","text":""},{"location":"virtualjoystick/#introduction","title":"Introduction","text":"

Simulate cursor keys according to touch events.

  • Author: Rex
  • Member of scene
"},{"location":"virtualjoystick/#live-demos","title":"Live demos","text":"
  • Virtual joystick
  • Two joySticks
  • Joystick and button
  • Toggle visible
  • Drag vector to cursor keys
"},{"location":"virtualjoystick/#usage","title":"Usage","text":"

Sample code

"},{"location":"virtualjoystick/#install-plugin","title":"Install plugin","text":""},{"location":"virtualjoystick/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexvirtualjoystickplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexvirtualjoystickplugin.min.js', true);\n
  • Create instance
    var joyStick = scene.plugins.get('rexvirtualjoystickplugin').addPlayer(scene, config);\n
"},{"location":"virtualjoystick/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import VirtualJoystickPlugin from 'phaser3-rex-plugins/plugins/virtualjoystick-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexVirtualJoystick',\nplugin: VirtualJoystickPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var joyStick = scene.plugins.get('rexVirtualJoystick').addPlayer(scene, config);\n
"},{"location":"virtualjoystick/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import VirtualJoystick from 'phaser3-rex-plugins/plugins/virtualjoystick.js';\n
  • Create instance
    var joyStick = new VirtualJoystick(scene, config);\n
"},{"location":"virtualjoystick/#create-instance","title":"Create instance","text":"
var joystick = scene.plugins.get('rexVirtualJoystick').add(scene, {\nx: x,\ny: y,\nradius: 100,\nbase: baseGameObject,\nthumb: thumbGameObject,\n// dir: '8dir',\n// forceMin: 16,\n// fixed: true,\n// enable: true\n});\n
  • base : Base game object.
    • Create a circle shape object if no base game object passed.
  • thumb : Thumb game object.
    • Create a circle shape object if no thumb game object passed.
  • x, y : Position of base game object
  • radius : Circle hit-area of base game object
  • dir :
    • 'up&down', or 0 : Simulate up or down cursor keys only.
    • 'left&right', or 1 : Simulate left or right cursor keys only.
    • '4dir', or 2 : Simulate up, down, left or right cursor keys.
    • '8dir', or 3 : Simulate up, up-left, up-right, down, down-left, down-right, left, or right cursor keys.
  • forceMin : Cursor keys will be pressed when force is larger then this value.
    • force : Distance between position of base game object to touch pointer
  • fixed : Set true to fix to camera, i.e set scrollFactor to 0 for base and thumb game object. Default value is true.
  • enable : Set false to disable cursor keys simulation
"},{"location":"virtualjoystick/#state-of-cursor-keys","title":"State of cursor keys","text":"
var cursorKeys = joystick.createCursorKeys();\n\nvar leftKeyDown = cursorKeys.left.isDown;\nvar rightKeyDown = cursorKeys.right.isDown;\nvar upKeyDown = cursorKeys.up.isDown;\nvar downKeyDown = cursorKeys.down.isDown;\n

Or

var leftKeyDown = joystick.left;\nvar rightKeyDown = joystick.right;\nvar upKeyDown = joystick.up;\nvar downKeyDown = joystick.down;\nvar noKeyDown = joystick.noKey;\n
"},{"location":"virtualjoystick/#force-angle","title":"Force & Angle","text":"

Force : Distance between position of base game object to touch pointer.

var force = joystick.force;\nvar forceX = joystick.forceX;\nvar forceY = joystick.forceY;\n\nvar angle = joystick.angle;  // degree between -180 to 180\nvar rotation = joystick.rotation; // radians\n
"},{"location":"virtualjoystick/#visible","title":"Visible","text":"

Visible of base game object.

  • Get : Return visible of base game object
    var visible = joystick.visible;\n
  • Set : Set visible to base game object and thumb game object
    joystick.visible = visible;\njoystick.setVisible(visible);\njoystick.toggleVisible();\n
    Joystick will be disabled when invisible.
"},{"location":"virtualjoystick/#enable","title":"Enable","text":"
  • Get
    var enable = joystick.enable;\n
  • Set
    joystick.setEnable(enable);  // enable: true, or false\n//joystick.enable = enable;\n
  • Toggle
    joystick.toggleEnable();\n
"},{"location":"virtualjoystick/#position","title":"Position","text":"

Position of base game object.

  • Get
    var x = joystick.x;\nvar y = joystick.y;\n
  • Set
    joystick.setPosition(x ,y);\n// joystick.x = x;\n// joystick.y = y;\n
"},{"location":"virtualjoystick/#scroll-factor","title":"Scroll factor","text":"
  • Fix to camera
    joystick.setScrollFactor(0);\n
"},{"location":"virtualjoystick/#touch-pointer","title":"Touch pointer","text":"
  • Position
    var x = joystick.pointerX;\nvar y = joystick.pointerY;\n
  • Pointer
    var pointer = joystick.pointer;\n
"},{"location":"virtualjoystick/#destroy","title":"Destroy","text":"

Destroy base & thumb game object.

joystick.destroy();\n
"},{"location":"virtualjoystick/#events","title":"Events","text":"
  • On joystick updated :
    joystick.on('update', function(){});\n
  • On pointer-down
    joystick.on('pointerdown', function(pointer){});\n
  • On pointer-up
    joystick.on('pointerup', function(pointer){});\n
"},{"location":"virtualjoystick/#elements","title":"Elements","text":"
  • Base Game object:
    var baseGO = joystick.base;\n
  • Thumb Game object:
    var thumb = joystick.thumb;\n
"},{"location":"virtualjoystick/#vector-to-cursor-keys","title":"Vector to cursor keys","text":"

A controller to represent cursor keys by (drag) vector

"},{"location":"virtualjoystick/#create-controller","title":"Create controller","text":"
var controller = scene.plugins.get('rexVirtualJoyStick').addVectorToCursorKeys({\n// dir: '8dir',\n// forceMin: 16,\n// enable: true\n})\n

or

// import VirtualJoystick from 'phaser3-rex-plugins/plugins/vectortocursorkeys.js';\nvar controller = new VirtualJoystick(undefined, config);\n
  • dir :
    • 'up&down', or 0 : Simulate up or down cursor keys only.
    • 'left&right', or 1 : Simulate left or right cursor keys only.
    • '4dir', or 2 : Simulate up, down, left or right cursor keys.
    • '8dir', or 3 : Simulate up, up-left, up-right, down, down-left, down-right, left, or right cursor keys.
  • forceMin : Cursor keys will be pressed when force is larger then this value.
    • force : Distance between position of base game object to touch pointer
  • enable : Set false to disable cursor keys simulation.
"},{"location":"virtualjoystick/#set-vector","title":"Set vector","text":"
  • Set vector
    controller.setVector(x0, y0, x1, y1);\n
  • Clear vector
    controller.clearVector();\n
"},{"location":"virtualjoystick/#state-of-cursor-keys_1","title":"State of cursor keys","text":"
var cursorKeys = controller.createCursorKeys();\n\nvar leftKeyDown = cursorKeys.left.isDown;\nvar rightKeyDown = cursorKeys.right.isDown;\nvar upKeyDown = cursorKeys.up.isDown;\nvar downKeyDown = cursorKeys.down.isDown;\n
"},{"location":"virtualjoystick/#force-angle_1","title":"Force & Angle","text":"
var force = controller.force;\nvar forceX = controller.forceX;\nvar forceY = controller.forceY;\n\nvar angle = controller.angle;  // degree between -180 to 180\nvar rotation = controller.rotation; // radians\n
"},{"location":"waitevents/","title":"Wait events","text":""},{"location":"waitevents/#introduction","title":"Introduction","text":"

Wait fired events or callbacks.

  • Author: Rex
"},{"location":"waitevents/#usage","title":"Usage","text":"

Sample code

"},{"location":"waitevents/#install-plugin","title":"Install plugin","text":""},{"location":"waitevents/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexwaiteventsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexwaiteventsplugin.min.js', true);\n
  • Create instance
    var waitEvents = scene.plugins.get('rexwaiteventsplugin').add(completeCallback, completeCallbackScope);\n
"},{"location":"waitevents/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import WaitEventsPlugin from 'phaser3-rex-plugins/plugins/waitevents-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexWaitEvents',\nplugin: WaitEventsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var waitEvents = scene.plugins.get('rexWaitEvents').add(completeCallback, completeCallbackScope);\n
"},{"location":"waitevents/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import WaitEvents from 'phaser3-rex-plugins/plugins/waitevents.js';\n
  • Create instance
    var waitEvents = new WaitEvents(completeCallback, completeCallbackScope);\n
"},{"location":"waitevents/#create-instance","title":"Create instance","text":"
var waitEvents = scene.plugins.get('rexWaitEvents').add(completeCallback, completeCallbackScope);\n
  • completeCallback, completeCallbackScope : Callback when all waitting events are fired.
"},{"location":"waitevents/#set-complete-callback","title":"Set complete callback","text":"
waitEvents.setCompleteCallback(completeCallback, completeCallbackScope);\n
  • completeCallback, completeCallbackScope : Callback when all waitting events are fired.
"},{"location":"waitevents/#add-waiting-event","title":"Add waiting event","text":""},{"location":"waitevents/#callback","title":"Callback","text":"
var callback = waitEvents.waitCallback();\n
  • callback : A function object which invoked when waitting event finished.

For example, invokes completeCallback when all timers are time-out.

scene.time.delayedCall(500, waitEvents.waitCallback());\nscene.time.delayedCall(1000, waitEvents.waitCallback());\nscene.time.delayedCall(1500, waitEvents.waitCallback());\n
"},{"location":"waitevents/#callback-from-event-emitter","title":"Callback from event emitter","text":"
waitEvents.waitEvent(eventEmitter, eventName);\n
"},{"location":"waitevents/#remove-waiting-event","title":"Remove waiting event","text":"
callback();\n

or

waitEvents.remove(callback);\n
  • callback : A function object created via waitEvents.waitCallback()
"},{"location":"waitevents/#clear-all-waiting-events","title":"Clear all waiting events","text":"
waitEvents.clear();\n
"},{"location":"waitevents/#no-wait-event","title":"No wait event","text":"
var noWaitEvent = waitEvents.noWaitEvent;\n
"},{"location":"webfontloader/","title":"Webfont loader","text":""},{"location":"webfontloader/#introduction","title":"Introduction","text":"

Load web font by google webfont loader in payload or preload stage.

  • Author: Rex
  • Custom File of loader
"},{"location":"webfontloader/#live-demos","title":"Live demos","text":"
  • Webfont loader
"},{"location":"webfontloader/#usage","title":"Usage","text":"

Sample code

"},{"location":"webfontloader/#install-plugin","title":"Install plugin","text":""},{"location":"webfontloader/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    var sceneConfig = {\n// ....\npack: {\nfiles: [{\ntype: 'plugin',\nkey: 'rexwebfontloaderplugin',\nurl: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/    rexwebfontloaderplugin.min.js',\nstart: true\n}]\n}\n};\nclass MyScene extends Phaser.Scene {\nconstructor() {\nsuper(sceneConfig)\n}\n// ....\n\npreload() {\n// rexwebfontloaderplugin will be installed before preload(), but not added to loader yet\n// Call addToScene(scene) to add this await loader to loader of this scene\nthis.plugins.get('rexwebfontloaderplugin').addToScene(this);\n\nthis.load.rexWebFont(config);\n}\n}\n
"},{"location":"webfontloader/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import WebFontLoaderPlugin from 'phaser3-rex-plugins/plugins/webfontloader-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexWebFontLoader',\nplugin: WebFontLoaderPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • In preload stage
    scene.load.rexWebFont(config);\n
"},{"location":"webfontloader/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import WebFontLoader from 'phaser3-rex-plugins/plugins/webfontloader.js';\n
  • Start loading task
    WebFontLoader.call(scene.load, config);\n
"},{"location":"webfontloader/#load-webfont","title":"Load webfont","text":"

In preload stage:

this.load.rexWebFont({\ngoogle: {\nfamilies: ['Bangers']\n},\n// testString: undefined,\n// testInterval: 20,\n});\n
  • testString : To test if the font is loaded completed or not.
    • undefined : No testing. Default value.
    • A string : A test string for all fonts
    • An object, {fontFamily: testString} : Test string for a specific font family.
  • testInterval : Retry interval.

or load font in pack

var sceneConfig = {\nkey: '...',\npack: {\nfiles: [{\ntype: 'rexWebFont',\nkey: 'webfont',\nconfig: {\ngoogle: {\nfamilies: ['Bangers']\n},\n// testString: undefined,\n// testInterval: 20,\n}\n}\n]\n}\n};\n

Configuration of loading fonts

  • Google webfont
    WebFontConfig = {\ngoogle: {\nfamilies: ['Droid Sans', 'Droid Serif:bold']\n}\n};\n
  • Custom font
    WebFontConfig = {\ncustom: {\nfamilies: ['My Font', 'My Other Font:n4,i4,n7'],\nurls: ['/fonts.css']\n}\n};\n
    and fonts.css
    @font-face {\nfont-family: 'My Font';\nsrc: ...;\n}\n@font-face {\nfont-family: 'My Other Font';\nfont-style: normal;\nfont-weight: normal; /* or 400 */\nsrc: ...;\n}\n@font-face {\nfont-family: 'My Other Font';\nfont-style: italic;\nfont-weight: normal; /* or 400 */\nsrc: ...;\n}\n@font-face {\nfont-family: 'My Other Font';\nfont-style: normal;\nfont-weight: bold; /* or 700 */\nsrc: ...;\n}\n
"},{"location":"webfontloader/#events","title":"Events","text":"
  • fontactive event

    this.load.on('webfontactive', function(fileObj, familyName){});\n
  • fontinactive event

    this.load.on('webfontinactive', function(fileObj, familyName){});\n
"},{"location":"webfontloader/#test-string","title":"Test string","text":"

Add string parameter testString into config, to test if the font is loaded completed or not.

  1. Fill 0 within an internal canvas.
  2. Draw testString.
  3. Check if any pixel has non-zero value.
"},{"location":"wrap/","title":"Wrap","text":""},{"location":"wrap/#introduction","title":"Introduction","text":"

Wrap the given value between min and max, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"wrap/#usage","title":"Usage","text":"
var result = Phaser.Math.Wrap(value, min, max);\n
  • value : The value to wrap.
"},{"location":"xor/","title":"XOR","text":""},{"location":"xor/#introduction","title":"Introduction","text":"

Encrypt or decrypt string by XOR algorithm.

  • Author: Rex
  • Methods
"},{"location":"xor/#usage","title":"Usage","text":"

Sample code

"},{"location":"xor/#install-plugin","title":"Install plugin","text":""},{"location":"xor/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexxorplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexxorplugin.min.js', true);\n
  • Encrypt, or decrypt
    var encResult = scene.plugins.get('rexxorplugin').Encrypt(src, pwd);\nvar decResult = scene.plugins.get('rexxorplugin').Decrypt(encResult, pwd);\n
"},{"location":"xor/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import XORPlugin from 'phaser3-rex-plugins/plugins/xor-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexXOR',\nplugin: XORPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Encrypt, or decrypt
    var encResult = scene.plugins.get('rexXOR').Encrypt(src, pwd);\nvar decResult = scene.plugins.get('rexXOR').Decrypt(encResult, pwd);\n
"},{"location":"xor/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import XOR from 'phaser3-rex-plugins/plugins/xor.js';\n
  • Encrypt, or decrypt
    var encResult = XOR.Encrypt(src, pwd);\nvar decResult = XOR.Decrypt(encResult, pwd);\n
"},{"location":"xor/#encrypt","title":"Encrypt","text":"
var encResult = scene.plugins.get('rexXOR').Encrypt(src, pwd);\n
"},{"location":"xor/#decrypt","title":"Decrypt","text":"
var decResult = scene.plugins.get('rexXOR').Decrypt(encResult, pwd);\n
"},{"location":"ymlachievements/","title":"YAML Achievements","text":""},{"location":"ymlachievements/#introduction","title":"Introduction","text":"

Achievements in a YAML table.

  • Author: Rex
  • Member of scene
"},{"location":"ymlachievements/#usage","title":"Usage","text":"

Sample code

"},{"location":"ymlachievements/#install-plugin","title":"Install plugin","text":""},{"location":"ymlachievements/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexymlachievementsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexymlachievementsplugin.min.js', true);\n
  • Add conditions-table object
    var achievements = scene.plugins.get('rexymlachievementsplugin').add();\n
"},{"location":"ymlachievements/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import AchievementsPlugin from 'phaser3-rex-plugins/plugins/ymlachievements-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAchievements',\nplugin: AchievementsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add conditions-table object
    var achievements = scene.plugins.get('rexAchievements').add();\n
"},{"location":"ymlachievements/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Achievements from 'phaser3-rex-plugins/plugins/ymlachievements.js';\n
  • Add conditions-table object
    var achievements = new Achievements();\n
"},{"location":"ymlachievements/#create-instance","title":"Create instance","text":"
var achievements = scene.plugins.get('rexAchievements').add();\n
"},{"location":"ymlachievements/#load-table-from-yaml-string","title":"Load table from YAML string","text":"
achievements.loadYML(ymlString);\n

For exameple

Lv1 :\nAch1 : (A >= 10) && (A < 20)\nAch2 : (A >= 20) && (A < 50)\nAch3 : A >= 50\n

Equations will be parsed by expression-parser.

"},{"location":"ymlachievements/#test","title":"Test","text":"
  1. Run test
    var achievements.runTest(levelName, values);\n
    • levelName : Level name, in 1st column of achievements table.
    • values : Inputs in Key-value pairs
  2. Get obtained states
    var states = achievements.getObtainedState(levelName);\n
    • states : Obtained states of levelName
      {\nachievementName: {\nwasObtained: boolean,\njustObtained: boolean\n}\n}\n
      • wasObtained : Obtained this achievement achievementName before last testing.
      • justObtained : Obtained this achievement achievementName at last testing.

or

var states = achievements.getTestResults(levelName, values);\n
"},{"location":"ymlachievements/#get-obtained-states","title":"Get obtained states","text":"
  • Get obtained states of an achievement in a level
    var state = achievements.getObtainedState(levelName, achievementName);\n
    • state : Obtained states of achievementName, in level levelName
      {\nwasObtained: boolean,\njustObtained: boolean\n}\n
      • wasObtained : Obtained this achievement achievementName before last testing.
      • justObtained : Obtained this achievement achievementName at last testing.
  • Get obtained states of a level
    var state = achievements.getObtainedState(levelName);\n
    • states : Obtained states of levelName
      {\nachievementName: {\nwasObtained: boolean,\njustObtained: boolean\n}\n}\n
  • Get obtained states of all levels
    var state = achievements.getObtainedState();\n// var state = achievements.getObtainedStates();\n
    • states : Obtained states of all levels
      {\nlevelName: {\nachievementName: {\nwasObtained: boolean,\njustObtained: boolean\n}\n}\n}\n
  • For each obtained state in a level
    achievements.forEachObtainedState(levelName, function(levelName, achievementName, state) {\n\n}, scope)\n
    • state : Obtained states of achievementName, in level levelName
      {\nwasObtained: boolean,\njustObtained: boolean\n}\n
"},{"location":"ymlachievements/#get-name","title":"Get name","text":"
  • Name of levels
    var names = achievements.getLevelNames();\n// var names = achievements.getLevelNames(out);\n
  • Name of achievements in a level
    var names = achievements.getAchievementNames(levelName);\n// var names = achievements.getAchievementNames(levelName, out);\n
"},{"location":"ymlachievements/#save-load-obtained-states","title":"Save & load obtained states","text":"
  • Get obtained states
    var states = achievements.getObtainedStates();\n
  • Load obtained states
    achievements.loadObtainedStates(states);\n
"},{"location":"ymlachievements/#set-obtained-state","title":"Set obtained state","text":"
  • Set wasObtained, justObtained properties to true.
    achievements.setObtainedState(levelName, achievementName);\n
  • Set wasObtained, justObtained properties to false.
    achievements.clearObtainedState(levelName, achievementName);\n// achievements.setObtainedState(levelName, achievementName, false);\n
"},{"location":"ymlconditionstable/","title":"YAML Conditions table","text":""},{"location":"ymlconditionstable/#introduction","title":"Introduction","text":"

Check conditions to find passed tests listed in a YAML table.

  • Author: Rex
  • Member of scene
"},{"location":"ymlconditionstable/#usage","title":"Usage","text":"

Sample code

"},{"location":"ymlconditionstable/#install-plugin","title":"Install plugin","text":""},{"location":"ymlconditionstable/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexymlconditionstableplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexymlconditionstableplugin.min.js', true);\n
  • Add conditions-table object
    var conditionstable = scene.plugins.get('rexymlconditionstableplugin').add();\n
"},{"location":"ymlconditionstable/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ConditionsTablePlugin from 'phaser3-rex-plugins/plugins/ymlconditionstable-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexConditionsTable',\nplugin: ConditionsTablePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add conditions-table object
    var conditionstable = scene.plugins.get('rexConditionsTable').add();\n
"},{"location":"ymlconditionstable/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ConditionsTable from 'phaser3-rex-plugins/plugins/ymlconditionstable.js';\n
  • Add conditions-table object
    var conditionstable = new ConditionsTable();\n
"},{"location":"ymlconditionstable/#create-instance","title":"Create instance","text":"
var table = scene.plugins.get('rexConditionsTable').add();\n
"},{"location":"ymlconditionstable/#load-table-from-yaml-string","title":"Load table from YAML string","text":"
table.loadYML(ymlString);\n

For exameple

Test1 : (A >= 10) && (A <= 20)\nTest2 : B == 3\n

Equations will be parsed by expression-parser.

"},{"location":"ymlconditionstable/#test","title":"Test","text":""},{"location":"ymlconditionstable/#get-test-results","title":"Get test results","text":"
var results = table.getTestResults(context);\n
  • context : Inputs in Key-value pairs
  • results : {name: boolean}, use OR operation to combine result of tests with the same name.
"},{"location":"ymlconditionstable/#get-first-pass-test-name","title":"Get first pass test name","text":"
var testName = table.anyPassTest(context);\n
  • context : Inputs in Key-value pairs
"},{"location":"youtubeplayer/","title":"Youtube player","text":""},{"location":"youtubeplayer/#introduction","title":"Introduction","text":"

Play youtube video on iframe.

  • Author: Rex
  • DOM Game object
"},{"location":"youtubeplayer/#live-demos","title":"Live demos","text":"
  • Youtube player
"},{"location":"youtubeplayer/#usage","title":"Usage","text":"

Sample code

"},{"location":"youtubeplayer/#install-plugin","title":"Install plugin","text":""},{"location":"youtubeplayer/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexyoutubeplayerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexyoutubeplayerplugin.min.js', true);\n
  • Add youtube player object
    var youtubePlayer = scene.add.rexYoutubePlayer(x, y, width, height, config);\n
"},{"location":"youtubeplayer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import YoutubePlayerPlugin from 'phaser3-rex-plugins/plugins/youtubeplayer-plugin.js';\nvar config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexYoutubePlayer',\nplugin: YoutubePlayerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Add youtube player object
    var youtubePlayer = scene.add.rexYoutubePlayer(x, y, width, height, config);\n
"},{"location":"youtubeplayer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import YoutubePlayer from 'phaser3-rex-plugins/plugins/youtubeplayer.js';\n
  • Add youtube player object
    var youtubePlayer = new YoutubePlayer(scene, x, y, width, height, config);\nscene.add.existing(youtubePlayer);\n
"},{"location":"youtubeplayer/#add-youtube-player-object","title":"Add youtube player object","text":"
  • Youtube player on DOM
    var player = scene.add.rexYoutubePlayer(x, y, width, height, config);\n// var player = scene.add.rexYoutubePlayer(x, y, config);\n// var player = scene.add.rexYoutubePlayer(config);\n

Default configuration

{\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\n\nvideoId: '',\nautoPlay: true,\ncontrols: false,\nkeyboardControl: true,\nmodestBranding: false,\nloop: false,\n}\n
  • x, y : Position
  • width, height : Size of element
  • videoId : The YouTube video ID that identifies the video that the player will load.
  • autoPlay : Automatically start to play when the player loads.
  • controls : Whether the video player controls are displayed.
  • keyboardControl : Set false to disable keyboard controls.
  • modestBranding : Set false to prevent the YouTube logo from displaying in the control bar.
  • loop : Play video when ended.
"},{"location":"youtubeplayer/#custom-class","title":"Custom class","text":"
  • Define class
    class MyYoutubePlayer extends YoutubePlayer {  // or YoutubePlayerCanvas\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config) {\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta)\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var player = new MyYoutubePlayer(scene, x, y, width, height, config);\n
"},{"location":"youtubeplayer/#load","title":"Load","text":"
player.load(videoId);\n// player.load(videoId, autoPlay);\n
"},{"location":"youtubeplayer/#play","title":"Play","text":"
player.play();\n
"},{"location":"youtubeplayer/#pause","title":"Pause","text":"
player.pause();\n
"},{"location":"youtubeplayer/#playback-time","title":"Playback time","text":"
  • Get
    var playbackTime = player.playbackTime; // time in seconds\n
    var t = player.t; // t: 0~1\n
  • Set
    player.setPlaybackTime(time); // time in seconds\n// player.playbackTime = time;\n
    player.setT(t); // t: 0~1\n// player.t = t;\n
"},{"location":"youtubeplayer/#duration","title":"Duration","text":"
var duration = player.duration;  // time in seconds\n
"},{"location":"youtubeplayer/#volume","title":"Volume","text":"
  • Get
    var volume = player.volume;  // volume: 0~1\n
  • Set
    player.setVolume(volume);  // volume: 0~1\n// player.volume = volume;\n
"},{"location":"youtubeplayer/#mute","title":"Mute","text":"
  • Get
    var muted = player.muted;  // muted: true/false\n
  • Set
    player.setMute(muted);  // muted: true/false\n// player.muted = muted;\n
"},{"location":"youtubeplayer/#loop","title":"Loop","text":"
  • Get
    var loop = player.loop;  // loop: true/false\n
  • Set
    player.setLoop(loop);  // loop: true/false\n// player.loop = loop;\n
"},{"location":"youtubeplayer/#resize","title":"Resize","text":"
player.resize(width, height);\n
"},{"location":"youtubeplayer/#status","title":"Status","text":"
  • Is playing
    var isPlaying = player.isPlaying;\n
  • Is paused
    var isPaused = player.isPaused;\n
  • Has end
    var hasEnded = player.hasEnded;\n
  • Video state
    var videoState = player.videoState;\n
    or
    var videoStateString = player.videoStateString;\n
    • -1 : unstarted
    • 0 : ended
    • 1 : playing
    • 2 : paused
    • 3 : buffering
    • 5 : cued
"},{"location":"youtubeplayer/#events","title":"Events","text":"
  • Youtube player api ready
    player.on('ready', function(player){ }, scope);\n
  • State change
    player.on('statechange', function(player){ }, scope);\n
    • State : player.videoState
  • Unstarted
    player.on('unstarted', function(player){ }, scope);\n
  • Playing
    player.on('playing', function(player){ }, scope);\n
  • Pause
    player.on('pause', function(player){ }, scope);\n
  • Ended
    player.on('ended', function(player){ }, scope);\n
  • Buffering
    player.on('buffering', function(player){ }, scope);\n
  • Video cued
    player.on('cued', function(player){ }, scope);\n
  • Error
    player.on('error', function(player, errorMessage){ }, scope);\n

No Playback time changed event

Get playback time every tick might cause playing video lagging.

"},{"location":"youtubeplayer/#other-properties","title":"Other properties","text":"

See dom game object, game object

"},{"location":"youtubeplayer/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"

See dom-element's Interactive with other game objects

"},{"location":"zone/","title":"Zone","text":""},{"location":"zone/#introduction","title":"Introduction","text":"

Non-rendering rectangular game object for creating drop zones and input hit areas, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"zone/#usage","title":"Usage","text":""},{"location":"zone/#add-zone-object","title":"Add zone object","text":"
var zone = scene.add.zone(x, y, width, height);\n

Add zone from JSON

var zone = scene.make.zone({\nx: 0,\ny: 0,\n//width: 1,\n//height: 1,\n// origin: {x: 0.5, y: 0.5},\n});\n
"},{"location":"zone/#custom-class","title":"Custom class","text":"
  • Define class
    class MyZone extends Phaser.GameObjects.Zone {\nconstructor(scene, x, y, width, height) {\nsuper(scene, x, y, width, height);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var zone = new MyZone(x, y, width, height);\n
"},{"location":"zone/#input-hit-zone","title":"Input hit zone","text":"
zone.setInteractive();\n

See touch events

"},{"location":"zone/#drop-zones","title":"Drop zones","text":"
  • Default drop zone
    zone.setDropZone();\n
  • Rectangle drop zone
    zone.setRectangleDropZone(width, height);\n
  • Circular drop zone
    zone.setCircleDropZone(radius);\n
  • Custom drop zone
    zone.setDropZone(shape, callback);\n
    • callback
      function(shape, x, y, gameObject) {\nreturn hit;  // true/false\n}\n

See drop zone

"},{"location":"zone/#other-properties","title":"Other properties","text":"

See game object

"}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Home","text":""},{"location":"#phaser","title":"Phaser","text":"

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

"},{"location":"#links","title":"Links","text":""},{"location":"#phaser3","title":"Phaser3","text":"
  • FAQ
  • Official discord channel
  • API document
  • Examples
  • Bug report
"},{"location":"#rex-plugins","title":"Rex plugins","text":"
  • Plugin list
    • Demos
  • Discord channel
  • Bug report
  • Feature suggestion & discussion
"},{"location":"achievements/","title":"CSV Achievements","text":""},{"location":"achievements/#introduction","title":"Introduction","text":"

Achievements in a csv table.

  • Author: Rex
  • Member of scene
"},{"location":"achievements/#usage","title":"Usage","text":"

Sample code

"},{"location":"achievements/#install-plugin","title":"Install plugin","text":""},{"location":"achievements/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexachievementsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexachievementsplugin.min.js', true);\n
  • Add conditions-table object
    var achievements = scene.plugins.get('rexachievementsplugin').add();\n
"},{"location":"achievements/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import AchievementsPlugin from 'phaser3-rex-plugins/plugins/achievements-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAchievements',\nplugin: AchievementsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add conditions-table object
    var achievements = scene.plugins.get('rexAchievements').add();\n
"},{"location":"achievements/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Achievements from 'phaser3-rex-plugins/plugins/achievements.js';\n
  • Add conditions-table object
    var achievements = new Achievements();\n
"},{"location":"achievements/#create-instance","title":"Create instance","text":"
var achievements = scene.plugins.get('rexAchievements').add();\n
"},{"location":"achievements/#load-table-from-csv-string","title":"Load table from csv string","text":"
achievements.loadCSV(csvString, {\n// delimiter: ','\n});\n

For exameple, csv string

A A Lv1 Ach1 >= 10 < 20 Lv1 Ach2 >= 20 < 50 Lv1 Ach3 >= 50
,A,A\nLv1,Ach1,>= 10,<= 20,\nLv1,Ach2,>= 20,< 50,\nLv1,Ach3,>= 50,,\n
  • 1st column : Level names
  • 2nd column : Achievement names
  • Other columns : Condtions
  • 1st row : Variable names of conditions.

means that:

Lv1, Ach1: (A>=10) && (A<20)\nLv1, Ach2: (A>=20) && (A<50)\nLv1, Ach3: (A>=50)\n
"},{"location":"achievements/#test","title":"Test","text":"
  1. Run test
    var achievements.runTest(levelName, values);\n
    • levelName : Level name, in 1st column of achievements table.
    • values : Inputs in Key-value pairs
  2. Get obtained states
    var states = achievements.getObtainedState(levelName);\n
    • states : Obtained states of levelName
      {\nachievementName: {\nwasObtained: boolean,\njustObtained: boolean\n}\n}\n
      • wasObtained : Obtained this achievement achievementName before last testing.
      • justObtained : Obtained this achievement achievementName at last testing.

or

var states = achievements.getTestResults(levelName, values);\n
"},{"location":"achievements/#get-obtained-states","title":"Get obtained states","text":"
  • Get obtained states of an achievement in a level
    var state = achievements.getObtainedState(levelName, achievementName);\n
    • state : Obtained states of achievementName, in level levelName
      {\nwasObtained: boolean,\njustObtained: boolean\n}\n
      • wasObtained : Obtained this achievement achievementName before last testing.
      • justObtained : Obtained this achievement achievementName at last testing.
  • Get obtained states of a level
    var state = achievements.getObtainedState(levelName);\n
    • states : Obtained states of levelName
      {\nachievementName: {\nwasObtained: boolean,\njustObtained: boolean\n}\n}\n
  • Get obtained states of all levels
    var state = achievements.getObtainedState();\n// var state = achievements.getObtainedStates();\n
    • states : Obtained states of all levels
      {\nlevelName: {\nachievementName: {\nwasObtained: boolean,\njustObtained: boolean\n}\n}\n}\n
  • For each obtained state in a level
    achievements.forEachObtainedState(levelName, function(levelName, achievementName, state) {\n\n}, scope)\n
    • state : Obtained states of achievementName, in level levelName
      {\nwasObtained: boolean,\njustObtained: boolean\n}\n
"},{"location":"achievements/#get-name","title":"Get name","text":"
  • Name of levels
    var names = achievements.getLevelNames();\n// var names = achievements.getLevelNames(out);\n
  • Name of achievements in a level
    var names = achievements.getAchievementNames(levelName);\n// var names = achievements.getAchievementNames(levelName, out);\n
"},{"location":"achievements/#save-load-obtained-states","title":"Save & load obtained states","text":"
  • Get obtained states
    var states = achievements.getObtainedStates();\n
  • Load obtained states
    achievements.loadObtainedStates(states);\n
"},{"location":"achievements/#set-obtained-state","title":"Set obtained state","text":"
  • Set wasObtained, justObtained properties to true.
    achievements.setObtainedState(levelName, achievementName);\n
  • Set wasObtained, justObtained properties to false.
    achievements.clearObtainedState(levelName, achievementName);\n// achievements.setObtainedState(levelName, achievementName, false);\n
"},{"location":"alphamaskimage/","title":"Alpha mask image","text":""},{"location":"alphamaskimage/#introduction","title":"Introduction","text":"

Load a texture, then apply an alpha mask from another texture. Extended from canvas plugin.

  • Author: Rex
  • Game object
"},{"location":"alphamaskimage/#live-demos","title":"Live demos","text":"
  • Alpha-mask-image
"},{"location":"alphamaskimage/#usage","title":"Usage","text":"

Sample code

"},{"location":"alphamaskimage/#install-plugin","title":"Install plugin","text":""},{"location":"alphamaskimage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexalphamaskimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexalphamaskimageplugin.min.js', true);\n
  • Add alpha-mask-image object
    var image = scene.add.rexAlphaMaskImage(x, y, key, frame, config);\n
"},{"location":"alphamaskimage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import AlphaMaskImagePlugin from 'phaser3-rex-plugins/plugins/alphamaskimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAlphaMaskImagePlugin',\nplugin: AlphaMaskImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add alpha-mask-image object
    var image = scene.add.rexAlphaMaskImage(x, y, key, frame, config);\n
"},{"location":"alphamaskimage/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import AlphaMaskImage from 'phaser3-rex-plugins/plugins/alphamaskimage.js';\n
  • Add alpha-mask-image object
    var image = new AlphaMaskImage(scene, x, y, key, frame, config);\nscene.add.existing(image);\n
"},{"location":"alphamaskimage/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAlphaMaskImagePlugin',\nplugin: AlphaMaskImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"alphamaskimage/#create-instance","title":"Create instance","text":"
var image = scene.add.rexAlphaMaskImage(x, y, key, frame, {\nmask: {\nkey: textureKey,\n// frame: frameName,\n// invertAlpha: false,\n// scale: undefined,\n}\n\n// backgroundColor: undefined,\n});\n

or

var image = scene.add.rexAlphaMaskImage(x, y, key, {\nmask: {\nkey: textureKey,\n// frame: frameName,\n// invertAlpha: false,\n// scale: undefined,\n}\n\n// backgroundColor: undefined,\n});\n
  • key, frame : Texture key, frame name of target texture.
  • mask.key, mask.frame : Texture key, frame name of the mask texture.
  • mask.invertAlpha :
    • false : Mask non-alpha (alpha === 0) area. Default behavior.
    • true : Mask alpha (alpha > 0) area.
  • mask.scale :
    • undefined : Expand mask texture size to fit target texture.
    • A number : Scale mask texture size.
  • backgroundColor : Background color filled with masked area.
    • undefiined : No background color.

Add image from JSON

var image = scene.make.rexAlphaMaskImage({\nx: 0,\ny: 0,\nkey: key,\nframe: name,\nmask: {\nkey: textureKey,\n// frame: frameName,\n// invertAlpha: false,\n// scale: undefined,\n}\n\n// backgroundColor: undefined,\n\nadd: true\n});\n
"},{"location":"alphamaskimage/#custom-class","title":"Custom class","text":"
  • Define class
    class MyImage extends AlphaMaskImage {\nconstructor(scene, x, y, key, frame, config) {\nsuper(scene, x, y, key, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyImage(scene, key, frame, config);\n
"},{"location":"alphamaskimage/#set-texture","title":"Set texture","text":"
image.setTexture(key, frame);\n// image.setTexture(key, frame, mask);\n

or

image.setTexture(key, frame, {\nmask: {\nkey: textureKey,\n// frame: frameName,\n// invertAlpha: false,\n// scale: undefined,\n}\n\n// backgroundColor: undefined,\n});\n
  • mask.key, mask.frame : Texture key, frame name of the mask texture.
  • mask.invertAlpha :
    • false : Mask non-alpha (alpha === 0) area. Default behavior.
    • true : Mask alpha (alpha > 0) area.
  • mask.scale :
    • undefined : Expand mask texture size to fit target texture.
    • A number : Scale mask texture size.
  • backgroundColor : Background color filled with masked area.
    • undefiined : No background color.
"},{"location":"alphamaskimage/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"alphamaskimage/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"alphamaskimage/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"anchor/","title":"Anchor","text":""},{"location":"anchor/#introduction","title":"Introduction","text":"

Set size and position based on visible window.

Note

Visible window will be changed when scale mode is ENVELOP, WIDTH_CONTROLS_HEIGHT, or HEIGHT_CONTROLS_WIDTH.

  • Author: Rex
  • Behavior of game object
"},{"location":"anchor/#live-demos","title":"Live demos","text":"
  • Anchor
  • Resize
  • Camera zoom/scroll
"},{"location":"anchor/#usage","title":"Usage","text":"

Sample code

"},{"location":"anchor/#install-plugin","title":"Install plugin","text":""},{"location":"anchor/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexanchorplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexanchorplugin.min.js', true);\n
  • Add anchor behavior
    var anchor = scene.plugins.get('rexanchorplugin').add(gameObject, config);\n
"},{"location":"anchor/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import AnchorPlugin from 'phaser3-rex-plugins/plugins/anchor-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAnchor',\nplugin: AnchorPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add anchor behavior
    var anchor = scene.plugins.get('rexAnchor').add(gameObject, config);\n
"},{"location":"anchor/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Anchor from 'phaser3-rex-plugins/plugins/anchor.js';\n
  • Add anchor behavior
    var anchor = new Anchor(gameObject, config);\n
"},{"location":"anchor/#create-instance","title":"Create instance","text":"
var anchor = scene.plugins.get('rexAnchor').add(gameObject, {\n// left: '0%+0',\n// right: '0%+0',\n// centerX: '0%+0',\n// x: '0%+0',\n\n// top: '0%+0',\n// bottom: '0%+0',\n// centerY: '0%+0',\n// y: '0%+0',\n\n// width: '100%+0',\n// height: '100%+0',\n// onResizeCallback: function(width, height, gameObject, anchor) {},\n// onResizeCallbackScope: undefined,\n\n// onUpdateViewportCallback: function(viewport, gameObject, anchor) {},\n// onUpdateViewportCallbackScope: undefined,\n\n// enable: true\n});\n
  • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
    • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • 'left'(=0%), 'center'(=50%), 'right'(=100%)
      • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
    • Offset : '+n', or '-n'.

For example, anchor game object's left bound to viewport's left+10, centerY to viewport's center

{\nleft: 'left+10',\ncenterY: 'center'\n}\n
  • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
    • Percentage of visible width/height : 'p%', p: 0 ~ 100.
    • Padding : '+n', or '-n'.
  • onResizeCallback, onResizeCallbackScope : Callback of resizing game object
    • undefined : Default resize method.
    • Custom method
      function(width, height, gameObject, anchor) {\n// gameObject.setSize(width, height);\n// gameObject.setDisplaySize(width, height);\n// ...\n}\n
    • null or false : No callback
  • onUpdateViewportCallback, onUpdateViewportCallback : Callback invoked when viewport changed (anchor)

    fucntion(viewport, gameObject, anchor) {\n// Can change properties of viewport here\n// var centerX = viewport.centerX,\n//     centerY = viewport.centerY;\n// viewport.width *= 0.8;\n// viewport.height *= 0.9;\n// viewport.centerX = centerX;\n// viewport.centerY = centerY;\n}\n

    • viewport\uff1a A rectangle object
  • enable :

    • undefined, or true : Anchor game object under 'resize' event of scale manager.
    • false : Won't anchor game object automatially.
"},{"location":"anchor/#reset-config","title":"Reset config","text":"
anchor.resetFromJSON({\n// left: '0%+0',\n// right: '0%+0',\n// centerX: '0%+0',\n// x: '0%+0',\n\n// top: '0%+0',\n// bottom: '0%+0',\n// centerY: '0%+0',\n// y: '0%+0',\n\n// width: '100%+0',\n// height: '100%+0',    \n\n// onUpdateViewportCallback: function(viewport, gameObject, anchor) {}\n// onUpdateViewportCallbackScope: undefined,\n})\n
  • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
    • Percentage of visible width/height : 'p%', p: 0~100
      • 'left'(=0%), 'center'(=50%), 'right'(=100%)
      • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
    • Offset : '+n', or '-n'
  • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
    • Percentage of visible width/height : 'p%', p: 0 ~ 100.
    • Padding : '+n', or '-n'.
  • onResizeCallback, onResizeCallbackScope : Callback of resizing game object
    function(width, height, gameObject, anchor) {\n// gameObject.setSize(width, height);\n// gameObject.setDisplaySize(width, height);\n// ...\n}\n
"},{"location":"anchor/#set-onupdateviewport-callback","title":"Set OnUpdateViewport callback","text":"
anchor.setUpdateViewportCallback(callback, scope);\n
  • callback :
    fucntion(viewport, gameObject, anchor) {\n// Can change properties of viewport here\n// var centerX = viewport.centerX,\n//     centerY = viewport.centerY;\n// viewport.width *= 0.8;\n// viewport.height *= 0.9;\n// viewport.centerX = centerX;\n// viewport.centerY = centerY;\n}\n
    • viewport\uff1a A rectangle object
"},{"location":"anchor/#manual-anchor","title":"Manual anchor","text":"
anchor.anchor();\n
"},{"location":"anchor/#auto-anchor","title":"Auto anchor","text":"
  • Anchor game object under 'resize' event of scale manager.
    anchor.autoAnchor();\n// anchor.autoAnchor(true);\n
  • Disable auto-anchor
    anchor.autoAnchor(false);\n
"},{"location":"angle/","title":"Angle","text":""},{"location":"angle/#introduction","title":"Introduction","text":"

Convert angle value, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"angle/#usage","title":"Usage","text":""},{"location":"angle/#degree-radians","title":"Degree <-> Radians","text":"
  • Degree to radians
    var rad = Phaser.Math.DegToRad(deg);\n
  • Radians to degree
    var deg = Phaser.Math.RadToDeg(rad);  // deg : -180 ~ 180\n
"},{"location":"angle/#wrap","title":"Wrap","text":"
  • Wrap angle (radians) in the range of -PI to PI
    var rad = Phaser.Math.Angle.Wrap(angle);\n
  • Wrap angle (radians) in the range of 0 to 2*PI
    var rad = Phaser.Math.Angle.Normalize(angle);\n
  • Wrap angle (degrees) in the range of -180 to 180
    var deg = Phaser.Math.Angle.WrapDegrees(angle);\n
"},{"location":"angle/#angle-between-points","title":"Angle between points","text":"
  • Angle from (0,0) to vector (x2 - x1 , y2 - y1)
    var rad = Phaser.Math.Angle.Between(x1, y1, x2, y2);\n
    var rad = Phaser.Math.Angle.BetweenPoints(point1, point2);\n
"},{"location":"angle/#angle-between-angles","title":"Angle between angles","text":"
  • Shortest angle (degrees) between 2 angles
    var deg = Phaser.Math.Angle.ShortestBetween(angle1, angle2)\n
    • angle1, angle2 : Angle in degrees in the range of -180 to 180
    • deg : Shortest angle in degrees
      • deg > 0 : Counter-ClockWise rotation
      • deg < 0 : ClockWise rotation
"},{"location":"angle/#rotate-around-position","title":"Rotate around position","text":"
  • Rotate a point around x and y by the given angle.
    var out = Phaser.Math.RotateAround(point, x, y, angle);\n
  • Rotate a point around x and y by the given angle and distance.
    var out = Phaser.Math.RotateAroundDistance(point, x, y, angle, distance);\n
"},{"location":"angle/#rotate-to-angle","title":"Rotate to angle","text":"
var rad = Phaser.Math.Angle.RotateTo(currentAngle, targetAngle, lerp)\n
  • currentAngle, : The current angle, in radians.
  • targetAngle : The target angle to rotate to, in radians.
  • lerp : The lerp value to add to the current angle.
"},{"location":"angle/#random-angle","title":"Random angle","text":"
  • Returns a random angle in the range [-pi, pi].
    var angle = Phaser.Math.Angle.Random();\n
  • Returns a random angle in the range [-180, 180].
    var angle = Phaser.Math.Angle.RandomDegrees();\n
"},{"location":"animation/","title":"Animation","text":""},{"location":"animation/#introduction","title":"Introduction","text":"

Animation and animations manager.

  • Author: Richard Davey
"},{"location":"animation/#usage","title":"Usage","text":""},{"location":"animation/#animation-manager","title":"Animation manager","text":""},{"location":"animation/#add-animation","title":"Add animation","text":"
var animationConfig = {\nkey: '',\n\nframes: [],\n\nsortFrames: true,\ndefaultTextureKey: null,\nskipMissedFrames: true,\nrandomFrame: false,\n\n// time\ndelay: 0,\nduration: null,\nframeRate: null,\ntimeScale: 1,\n\n// repeat\nrepeat: 0,              // set to (-1) to repeat forever\nrepeatDelay: 0,\nyoyo: false,\n\n// visible\nshowBeforeDelay: false,\nshowOnStart: false,\nhideOnComplete: false\n};\n\nscene.anims.create(animationConfig);\n
  • key : Unique key of this animation data
  • frames : An array of {key, frame}
    • Properties
      {\nkey: '',\nframe: '', // string, or number\nduration: 0\n}\n
      • duration : The duration, in ms, of this frame of the animation.
    • A string : Texture key.
    • Every frame in the atlas
      scene.anims.generateFrameNames(key);\n
    • Frame sequence indexing from start to end
      var config = ;\nscene.anims.generateFrameNames(key,\n{\nprefix: '',\nstart: 0,\nend: 0,\nsuffix: '',\nzeroPad: 0,\n// outputArray: [], // Append frames into this array\n});\n
      • prefix + Pad(i, zeroPad, '0', 1) + suffix, i: start ~ end
    • Custom frame sequence
      var config = ;\nscene.anims.generateFrameNames(key,\n{\nprefix: '',\nsuffix: '',\nzeroPad: 0,\nframes: [ ... ]\n// outputArray: [], // Append frames into this array\n});\n
      • prefix + Pad(frames[i], zeroPad, '0', 1) + suffix
  • sortFrames : Frame names numerically sorted. Default value is true.
  • defaultTextureKey : The key of the texture all frames of the animation will use. Can be overridden on a per frame basis.
  • skipMissedFrames : Skip frames if the time lags, or always advanced anyway? Default value is true.
  • randomFrame : Start playback of this animation from a randomly selected frame? Default value is false.
  • delay : Delay before starting playback. Value given in milliseconds.
  • duration : How long the animation should play for in milliseconds. If not given its derived from frameRate.
  • frameRate : The frame rate of playback in frames per second. Default value is 24.
  • timeScale : The time scale to be applied to playback of this animation. Default value is 1.
  • repeat : Number of times to repeat the animation. Default value is 0.
    • -1 : Infinity
  • repeatDelay : Delay before the animation repeats. Value given in milliseconds.
  • yoyo : Should the animation yoyo? (reverse back down to the start) before repeating? Default value is false.
  • showBeforeDelay : If this animation has a delay, should it show the first frame immediately (true), or only after the delay (false)
  • showOnStart : Should sprite.visible = true when the animation starts to play? This happens after any delay, if set. Default value is false.
  • hideOnComplete : Should sprite.visible = false when the animation finishes? Default value is false.
"},{"location":"animation/#add-from-aseprite","title":"Add from Aseprite","text":"

Aseprite

scene.anims.createFromAseprite(key);\n// scene.anims.createFromAseprite(key, tags, target);\n
  • key : The key of the loaded Aseprite atlas.
  • tags :
    • undefined : Load all tags.
    • Array of string tag : Load these tags.
  • target : Create the animations on this target Sprite.
    • undefined : Created globally in this Animation Manager. Default behavior.
"},{"location":"animation/#remove-animation","title":"Remove animation","text":"
scene.anims.remove(key);\n
"},{"location":"animation/#delay-between-two-animations","title":"Delay between two animations","text":"
  • Add
    scene.anims.addMix(animA, animB, delay);\n
    • animA, animB : String key of an animation, or an instance of animation.
  • Remove
    scene.anims.removeMix(animA, animB);\n// scene.anims.removeMix(animA);\n
  • Get
    var delay = scene.anims.getMix(animA, animB);\n
"},{"location":"animation/#play-animation","title":"Play animation","text":"
  • Play
    scene.anims.play(key, children);\n
  • Stagger play (delay play)
    scene.anims.staggerPlay(key, children, stagger, staggerFirst);\n
    • children : An array of Game Objects to play the animation on
    • stagger : The amount of time, in milliseconds, to offset each play time by
    • staggerFirst : Set true to apply delay on 1st child
"},{"location":"animation/#pause-all-animations","title":"Pause all animations","text":"
scene.anims.pauseAll();\n
"},{"location":"animation/#resume-all-animations","title":"Resume all animations","text":"
scene.anims.resumeAll();\n
"},{"location":"animation/#global-time-scale","title":"Global time scale","text":"
  • Get
    var timeScale = scene.anims.globalTimeScale;\n
  • Set
    scene.anims.globalTimeScale = timeScale;\n
"},{"location":"animation/#has-animation","title":"Has animation","text":"
var hasAnim = scene.anims.exists(key);\n
"},{"location":"animation/#exportload","title":"Export/load","text":"
  • Export JSON
    var json = scene.anims.toJSON();\n
  • Load from JSON
    scene.anims.fromJSON(json);\n// scene.anims.fromJSON(json, clearCurrentAnimations);\n
    • Load JSON in preload stage javascript scene.load.json(key, url);
    • Load animation in preload stage
      scene.load.animation(key, url);\n
"},{"location":"animation/#events","title":"Events","text":"
  • On add animation
    scene.anims.on('add', function(key, anim) {});\n
  • On remove animation
    scene.anims.on('remove', function(key, anim) {});\n
  • On pause all animations
    scene.anims.on('pauseall', function() {});\n
  • On resume all animations
    scene.anims.on('resumeall', function() {});\n
"},{"location":"animation/#animation-object","title":"Animation object","text":"
var anim = scene.anims.get(key);\n
"},{"location":"animation/#add-frame","title":"Add frame","text":"
  • Append frames
    anim.addFrame(frame);\n
    • frame : scene.anims.generateFrameNames(key, config)
  • Insert frames at index
    anim.addFrameAt(index, frame);\n
    • frame : scene.anims.generateFrameNames(key, config)
"},{"location":"animation/#remove-frame","title":"Remove frame","text":"
  • Remove frame at
    anim.removeFrameAt(index);\n
  • Remove frame
    anim.removeFrame(frame);\n
"},{"location":"animation/#get-frame","title":"Get frame","text":"
  • Has frame index
    var HasFrameAt = anim.checkFrame(index);\n
  • Get frame at index
    var frame = anim.getFrameAt(index);\n
  • Get last frame
    var frame = anim.getLastFrame();\n
"},{"location":"animation/#export","title":"Export","text":"
  • Export JSON
    var json = anim.toJSON();\n
    or
    var jsonString = JSON.stringify(anim);\n
"},{"location":"arcade-body/","title":"Body","text":""},{"location":"arcade-body/#introduction","title":"Introduction","text":"

Arcade physics body.

  • Author: Richard Davey
"},{"location":"arcade-body/#usage","title":"Usage","text":""},{"location":"arcade-body/#get-physics-body","title":"Get physics body","text":"
  1. Enable physics world
  2. Add existing game object(s) to physics world
    • Add a game object
      var gameObject = scene.physics.add.existing(gameObject, bodyType);\n
      • bodyType :
        • 0 : Dynamic body
        • 1 : Static body
    • Add game objects
      scene.physics.world.enable(gameObjects, bodyType);\n
      • gameObjects : An array of game objects, or a group object
      • bodyType :
        • 0 : Dynamic body
        • 1 : Static body
  3. Get physics body
    var body = gameObject.body;\n
"},{"location":"arcade-body/#enable","title":"Enable","text":"

Whether this Body is updated by the physics simulation.

  • Enable (default)
    body.setEnable();\n
    or
    body.enable = true;\n
  • Disable
    body.setEnable(false);\n
    or
    body.enable = false;\n
"},{"location":"arcade-body/#direct-control","title":"Direct control","text":"

Enable directControl when game object is controlled by tween or dragging. Default behavior is disable.

  • Enable
    body.setDirectControl();\n// body.setDirectControl(true);\n
    or
    body.directControl = true;\n
  • Disable
    body.setDirectControl(false);\n
    or
    body.directControl = false;\n
"},{"location":"arcade-body/#immovable","title":"Immovable","text":"

Whether this Body can be moved by collisions with another Body.

  • Enable
    body.setImmovable();\n// body.immovable = true;\n
  • Disable (defalut)
    body.setImmovable(false);\n// body.immovable = false;\n
  • Get
    var immovable = body.immovable;\n
"},{"location":"arcade-body/#pushable","title":"Pushable","text":"

Sets if this Body can be pushed by another Body.

  • Enable (default value of dynamic body)
    body.pushable = true;\n
  • Disable, reflect back all of the velocity it is given to the colliding body.
    body.pushable = false;\n
  • Get
    var pushable = body.pushable;\n
"},{"location":"arcade-body/#moveable","title":"Moveable","text":"

Whether the Body's position and rotation are affected by its velocity, acceleration, drag, and gravity.

  • Enable (default)
    body.moves = true;\n
  • Disable
    body.moves = false;\n
  • Get
    var moves = body.moves;\n
"},{"location":"arcade-body/#destroy","title":"Destroy","text":"

Physics body will be destroyed automatically when game object is destroyed.

"},{"location":"arcade-body/#movement","title":"Movement","text":""},{"location":"arcade-body/#velocity","title":"Velocity","text":"
  • Set
    body.setVelocity(x,y);\n
    or
    body.setVelocityX(x);\nbody.setVelocityY(x);\n
  • Get
    var vx = body.velocity.x;\nvar vy = body.velocity.y;\n
"},{"location":"arcade-body/#max-speed","title":"Max speed","text":"
  • Set
    body.setMaxSpeed(speed);\n
  • Get
    var speed = body.maxSpeed;\n
"},{"location":"arcade-body/#max-velocity","title":"Max velocity","text":"
  • Set
    body.setMaxVelocity(x, y);\n
    or
    body.setMaxVelocityX(x);\nbody.setMaxVelocityY(y);\n
  • Get
    var vx = body.maxVelocity.x;\nvar vy = body.maxVelocity.y;\n
"},{"location":"arcade-body/#acceleration","title":"Acceleration","text":"
  • Set
    body.setAcceleration(x, y);\n
    or
    body.setAccelerationX(x);\nbody.setAccelerationY(y);\n
  • Get
    var ax = body.acceleration.x;\nvar ay = body.acceleration.y;\n
"},{"location":"arcade-body/#gravity","title":"Gravity","text":"
  • Set
    body.setGravity(x, y);\n
    or
    body.setGravityX(x);\nbody.setGravityY(y);\n
  • Get
    var gx = body.gravity.x;\nvar gy = body.gravity.y;\n
  • Enables (default)
    body.setAllowGravity();\n
  • Disable
    body.setAllowGravity(false);\n
"},{"location":"arcade-body/#drag","title":"Drag","text":"

Reduces speed per second.

  • Set
    body.setDrag(x, y);\n
    or
    body.setDragX(x);\nbody.setDragY(y);\n
  • Get
    var dx = body.drag.x;\nvar dy = body.drag.y;\n
  • Enables (default)
    body.setAllowDrag();\n
  • Disable
    body.setAllowDrag(false);\n
  • Enable Damping (default: disable)
    body.setDamping(true);\n// body.useDamping = true;\n
"},{"location":"arcade-body/#slide-factor","title":"Slide factor","text":"

The Slide Factor controls how much velocity is preserved when this Body is pushed by another Body.

body.slideFactor.set(x, y);\n
  • x, y :
    • 1 : Take on all velocity given in the push. Default value.
    • 0 : Allow this Body to be pushed but then remain completely still after the push ends, such as you see in a game like Sokoban.
    • Other value between 0 ~ 1 : Keep x/y of the original velocity when the push ends.
      • Combine this with the setDrag() method to create deceleration.
"},{"location":"arcade-body/#reset-position","title":"Reset position","text":"
body.reset(x, y);\n
"},{"location":"arcade-body/#stop","title":"Stop","text":"

Sets acceleration, velocity, and speed to zero.

body.stop();\n
"},{"location":"arcade-body/#friction","title":"Friction","text":"

If this Body is immovable and in motion, this the proportion of this Body's movement received by the riding body on each axis.

  • Set
    body.setFriction(x, y);\n
    or
    body.setFrictionX(x);\nbody.setFrictionY(y);\n
  • Get
    var fx = body.friction.x;\nvar fy = body.friction.y;\n
"},{"location":"arcade-body/#speed","title":"Speed","text":"
  • The absolute (non-negative) change in this Body's horizontal/vertical position from the previous step.
    var dx = body.deltaAbsX();\nvar dy = body.deltaAbsY();\n
"},{"location":"arcade-body/#rotation","title":"Rotation","text":""},{"location":"arcade-body/#allow-rotation","title":"Allow rotation","text":"

Whether this Body's rotation is affected by its angular acceleration and velocity.

  • Enable (default)
    body.setAllowRotation();\n
  • Disable
    body.setAllowRotation(false);\n
  • Get
    var allowRotation = body.allowRotation;\n
"},{"location":"arcade-body/#angular-velocity","title":"Angular velocity","text":"
  • Set
    body.setAngularVelocity(v);\n
  • Get
    var av = body.angularVelocity;\n
"},{"location":"arcade-body/#angular-acceleration","title":"Angular acceleration","text":"
  • Set
    body.setAngularAcceleration(v);\n
  • Get
    var aa = body.angularAcceleration;\n
"},{"location":"arcade-body/#angular-drag","title":"Angular drag","text":"

Reduces angular speed per second.

  • Set
    body.setAngularDrag(v);\n
  • Get
    var ad = body.angularDrag;\n
"},{"location":"arcade-body/#collision","title":"Collision","text":""},{"location":"arcade-body/#collision-category","title":"Collision category","text":"

A body is only below to one collision category. A body can collide with multiple collision categories. The default is that all bodies collide with all others.

  • Collision category
    • Get
      var collisionCategory = body.collisionCategory;\n
    • Set
      body.setCollisionCategory(category);\n
      • category :
        • (1 << 0)
        • (1 << 1)
        • (1 << 2)
        • ...
        • (1 << 31)
    • Reset collision category, to default behavior (all bodies collide with all others)
      body.resetCollisionCategory();\n
      • Set collisionCategory to 1.
      • Set collisionMask to 1
  • Collision mask
    • Get
      var collisionMask = body.collisionMask;\n
    • Set
      body.setCollidesWith(categories);\n
      • categories : A single category value, or an array of them.
    • Add
      body.addCollidesWith(category):\n
      • category : A single category value.
    • Remove
      body.removeCollidesWith(category);\n
      • category : A single category value.
"},{"location":"arcade-body/#collision-bound","title":"Collision bound","text":"
  • Rectangle
    body.setSize(width, height, center);\n
    • center : false to set body's offset to (0, 0).
      • Not work in Graphics object.
  • Circle
    body.setCircle(radius, offsetX, offsetY);\n
"},{"location":"arcade-body/#offset","title":"Offset","text":"
body.setOffset(x, y);\n
"},{"location":"arcade-body/#push-out","title":"Push out","text":"
scene.physics.add.collider(objectsA, objectsB);\n
  • objectsA, objectsB :
    • A game object
    • Game objects in array (Add or remove game objects)
    • Physics group (Add or remove game objects)
    • Group (Add or remove game objects)
"},{"location":"arcade-body/#callbacks","title":"Callbacks","text":"

Add collider

"},{"location":"arcade-body/#point-inside","title":"Point inside","text":"
var hit = body.hitTest(x, y);\n
"},{"location":"arcade-body/#is-colliding","title":"Is colliding","text":"
  • Is colliding this tick
    var isColliding = body.touching;\n
    • isColliding :
      {\nnone: true,\nup: true,\ndown: true,\nleft: true,\nright: true\n}\n
  • Was colliding previous tick
    var wasColliding = body.wasTouching;\n
    • wasColliding :
      {\nnone: true,\nup: true,\ndown: true,\nleft: true,\nright: true\n}\n
"},{"location":"arcade-body/#bounce","title":"Bounce","text":"
  • Set
    body.setBounce(x, y);\n
    or
    body.setBounceX(x);\nbody.setBounceY(y);\n
  • Get
    var bx = body.bounce.x;\nvar by = body.bounce.y;\n
"},{"location":"arcade-body/#world-bounds","title":"World bounds","text":"
  • Default world bounds
  • Custom world bounds :
    body.setBoundsRectangle(bounds);\n
    • bounds : A rectangle object.
  • Enable
    body.setCollideWorldBounds();\n
  • Disable (default)
    body.setCollideWorldBounds(false);\n
  • Get world bounds rectangle
    var top = body.world.bounds.top;\nvar bottom = body.world.bounds.bottom;\nvar left = body.world.bounds.left;\nvar right = body.world.bounds.right;\n
"},{"location":"arcade-body/#blocked","title":"Blocked","text":"

Whether this Body is colliding with a tile or the world boundary.

  • Blocked when moveing down
    var onFloor = body.onFloor(); // blocked.down\n
  • Blocked when moveing up
    var onCeiling = body.onCeiling();  // blocked.up\n
  • Blocked when moveing left or right
    var onWall = body.onWall();  // blocked.left || this.blocked.right\n
  • State
    var blocked = body.blocked;\n
    • blocked :
      {\nnone: true,\nup: false,\ndown: false,\nleft: false,\nright: false\n}\n
"},{"location":"arcade-body/#mass","title":"Mass","text":"
  • Set
    body.setMass(m);\n
  • Get
    var m = body.mass;\n
"},{"location":"arcade-body/#static-body","title":"Static body","text":""},{"location":"arcade-body/#sync","title":"Sync","text":"

Syncs the Bodies position and size with its parent Game Object.

body.updateFromGameObject();\n
"},{"location":"arcade-body/#debug","title":"Debug","text":"
  • Bounds of Body
    • Enable drawing body
      body.debugShowBody = true;\n
    • Color
      body.debugBodyColor = 0xff00ff;\n
  • Direction and magnitude of velocity
    • Enable drawing body
      body.debugShowVelocity = true;\n
"},{"location":"arcade-gameobject/","title":"Game object","text":""},{"location":"arcade-gameobject/#introduction","title":"Introduction","text":"

Arcade physics Image/Sprite/Group object.

  • Author: Richard Davey
"},{"location":"arcade-gameobject/#usage","title":"Usage","text":""},{"location":"arcade-gameobject/#add-physics-object","title":"Add physics object","text":"

Enable physics world

"},{"location":"arcade-gameobject/#image-object","title":"Image object","text":"
  • Static object, extends from Image object
    var image = scene.physics.add.staticImage(x, y, key);\n
  • Dynamic object, extends from Image object
    var image = scene.physics.add.image(x, y, key);\n
"},{"location":"arcade-gameobject/#sprite-object","title":"Sprite object","text":"
  • Static object, extends from Sprite object
    var image = scene.physics.add.staticSprite(x, y, key, frame);\n
  • Dynamic object, extends from Sprite object
    var image = scene.physics.add.sprite(x, y, key, frame);\n
"},{"location":"arcade-gameobject/#group","title":"Group","text":"
  • Static sprite objects, extends from Group object
    var group = scene.physics.add.staticGroup(children, config);\n// var group = scene.physics.add.staticGroup(config);\n
  • Dynamic sprite objects, extends from Group object
    var group = scene.physics.add.group(children, config);\n// var group = scene.physics.add.staticGroup(config);\n
    • config
      var config = {\nclassType: ArcadeSprite,\nenable: true,\ncollideWorldBounds: false,\ncustomBoundsRectangle: null,\naccelerationX: 0,\naccelerationY: 0,\nallowDrag: true,\nallowGravity: true,\nallowRotation: true,\nuseDamping: false,\nbounceX: 0,\nbounceY: 0,\ndragX: 0,\ndragY: 0,\ngravityX: 0,\ngravityY: 0,\nfrictionX: 0,\nfrictionY: 0,\nmaxSpeed: -1,\nvelocityX: 0,\nvelocityY: 0,\nmaxVelocityX: 10000,\nmaxVelocityY: 10000,\nangularVelocity: 0,\nangularAcceleration: 0,\nangularDrag: 0,\nmass: 0,\nimmovable: false,\n\nmaxSize: -1,\nrunChildUpdate: false\n};\n
"},{"location":"arcade-gameobject/#enable","title":"Enable","text":"
  • Enable body
    gameObject.enableBody();\n// gameObject.enableBody(false, 0, 0, enableGameObject, showGameObject);\n
    • Enable and reset position
      gameObject.enableBody(true, x, y);\n// gameObject.enableBody(true, x, y, enableGameObject, showGameObject);\n
    • enableGameObject : Also activate this Game Object.
    • showGameObject : Also show this Game Object.
  • Disable body
    gameObject.disableBody();\n// gameObject.disableBody(disableGameObject, hideGameObject);\n
    • disableGameObject : Also deactivate this Game Object.
    • hideGameObject : Also hide this Game Object.
"},{"location":"arcade-gameobject/#movement","title":"Movement","text":""},{"location":"arcade-gameobject/#velocity","title":"Velocity","text":"
  • Set
    gameObject.setVelocity(x, y);\n
    or
    gameObject.setVelocityX(x);\ngameObject.setVelocityY(y);\n
  • Get
    var vx = gameObject.body.velocity.x;\nvar vy = gameObject.body.velocity.y;\n
"},{"location":"arcade-gameobject/#max-velocity","title":"Max velocity","text":"
  • Set
    gameObject.setMaxVelocity(x, y);\n
  • Get
    var vx = gameObject.body.maxVelocity.x;\nvar vy = gameObject.body.maxVelocity.y;\n
"},{"location":"arcade-gameobject/#acceleration","title":"Acceleration","text":"
  • Set
    gameObject.setAcceleration(x, y);\n
    or
    gameObject.setAccelerationX(x);\ngameObject.setAccelerationY(y);\n
  • Get
    var ax = gameObject.body.acceleration.x;\nvar ay = gameObject.body.acceleration.y;\n
"},{"location":"arcade-gameobject/#gravity","title":"Gravity","text":"
  • Set
    gameObject.setGravity(x, y);\n
    or
    gameObject.setGravityX(x);\ngameObject.setGravityY(y);\n
  • Get
    var gx = gameObject.body.gravity.x;\nvar gy = gameObject.body.gravity.y;\n
"},{"location":"arcade-gameobject/#drag","title":"Drag","text":"
  • Set
    gameObject.setDrag(x, y);\n
    or
    gameObject.setDragX(x);\ngameObject.setDragY(y);\n
  • Get
    var dx = gameObject.body.drag.x;\nvar dy = gameObject.body.drag.y;\n
  • Enable damping
    gameObject.setDamping(value);\n
"},{"location":"arcade-gameobject/#immovable","title":"Immovable","text":"
  • Enable
    gameObject.setImmovable();\n
  • Disable
    gameObject.setImmovable(false);\n
  • Get
    var immovable = gameObject.body.immovable;\n
"},{"location":"arcade-gameobject/#pushable","title":"Pushable","text":"
  • Enable
    gameObject.setPushable();\n
  • Disable
    gameObject.setPushable(false);\n
  • Get
    var pushable = gameObject.body.pushable;\n
"},{"location":"arcade-gameobject/#slide-factor","title":"Slide factor","text":"

The Slide Factor controls how much velocity is preserved when this Body is pushed by another Body.

gameObject.setSlideFactor(x, y);\n
  • x, y :
    • 1 : Take on all velocity given in the push. Default value.
    • 0 : Allow this Body to be pushed but then remain completely still after the push ends, such as you see in a game like Sokoban.
    • Other value between 0 ~ 1 : Keep x/y of the original velocity when the push ends.
      • Combine this with the setDrag() method to create deceleration.
"},{"location":"arcade-gameobject/#friction","title":"Friction","text":"

If this Body is immovable and in motion, this the proportion of this Body's movement received by the riding body on each axis.

  • Set
    gameObject.setFriction(x, y);\n
    or
    gameObject.setFrictionX(x);\ngameObject.setFrictionY(y);\n
  • Get
    var fx = gameObject.body.friction.x;\nvar fy = gameObject.body.friction.y;\n
"},{"location":"arcade-gameobject/#direct-control","title":"Direct control","text":"

Enable directControl when game object is controlled by tween or dragging. Default behavior is disable.

  • Enable
    gameObject.setDirectControl();\n// gameObject.setDirectControl(true);\n
  • Disable
    gameObject.setDirectControl(false);\n

Use case

Enable setDirectControl when game object is controlled by tween or dragging.

"},{"location":"arcade-gameobject/#rotation","title":"Rotation","text":""},{"location":"arcade-gameobject/#allow-rotation","title":"Allow rotation","text":"

Whether this Body's rotation is affected by its angular acceleration and velocity.

  • Enable (default)
    body.setAllowRotation();\n
  • Disable
    body.setAllowRotation(false);\n
  • Get
    var allowRotation = gameObject.body.allowRotation;\n
"},{"location":"arcade-gameobject/#angular-velocity","title":"Angular velocity","text":"
  • Set
    gameObject.setAngularVelocity(v);\n
  • Get
    var av = gameObject.body.angularVelocity;\n
"},{"location":"arcade-gameobject/#angular-acceleration","title":"Angular acceleration","text":"

-Set

gameObject.setAngularAcceleration(v);\n
- Get
var aa = gameObject.body.angularAcceleration;\n

"},{"location":"arcade-gameobject/#angular-drag","title":"Angular drag","text":"
  • Set
    gameObject.setAngularDrag(v);\n
  • Get
    var ad = gameObject.body.angularDrag;\n
"},{"location":"arcade-gameobject/#collision","title":"Collision","text":""},{"location":"arcade-gameobject/#collision-category","title":"Collision category","text":"

A body is only below to one collision category. A body can collide with multiple collision categories. The default is that all bodies collide with all others.

  • Collision category
    • Get
      var collisionCategory = gameObject.body.collisionCategory;\n
    • Set
      gameObject.setCollisionCategory(category);\n
      • category :
        • (1 << 0)
        • (1 << 1)
        • (1 << 2)
        • ...
        • (1 << 31)
    • Reset collision category, to default behavior (all bodies collide with all others)
      gameObject.resetCollisionCategory();\n
      • Set collisionCategory to 1.
      • Set collisionMask to 1
  • Collision mask
    • Get
      var collisionMask = gameObject.body.collisionMask;\n
    • Set
      gameObject.setCollidesWith(categories);\n
      • categories : A single category value, or an array of them.
    • Add
      gameObject.addCollidesWith(category):\n
      • category : A single category value.
    • Remove
      gameObject.removeCollidesWith(category);\n
      • category : A single category value.
"},{"location":"arcade-gameobject/#collision-bound","title":"Collision bound","text":"
  • Rectangle
    gameObject.setBodySize(width, height, center);\n
    • center : false to set body's offset to (0, 0)
  • Circle
    gameObject.setCircle(radius, offsetX, offsetY);\n
"},{"location":"arcade-gameobject/#offset","title":"Offset","text":"
gameObject.setOffset(x, y);\n
"},{"location":"arcade-gameobject/#push-out","title":"Push out","text":"
scene.physics.add.collider(objectsA, objectsB);\n
  • objectsA, objectsB :
    • A game object
    • Game objects in array (Add or remove game objects)
    • Physics group (Add or remove game objects)
    • Group (Add or remove game objects)
"},{"location":"arcade-gameobject/#callbacks","title":"Callbacks","text":"

Add collider

"},{"location":"arcade-gameobject/#point-inside","title":"Point inside","text":"
var hit = gameObject.hitTest(x, y);\n
"},{"location":"arcade-gameobject/#bounce","title":"Bounce","text":"
  • Set
    gameObject.setBounce(x, y);\n
    or
    gameObject.setBounceX(x);\ngameObject.setBounceY(y);\n
  • Get
    var bx = gameObject.body.bounce.x;\nvar by = gameObject.body.bounce.y;\n
  • Enable bounce when colliding with the world boundary
    gameObject.setCollideWorldBounds();\n
  • Disable bounce when colliding with the world boundary
    gameObject.setCollideWorldBounds(false);\n
"},{"location":"arcade-gameobject/#mass","title":"Mass","text":"
  • Set
    gameObject.setMass(m);\n
  • Get
    var m = gameObject.body.mass;\n
"},{"location":"arcade-gameobject/#static-game-object","title":"Static game object","text":""},{"location":"arcade-gameobject/#sync","title":"Sync","text":"

Syncs the Bodies position and size in static game object.

gameObject.refreshBody();\n
"},{"location":"arcade-gameobject/#methods-of-group","title":"Methods of group","text":"
group.setVelocity(x, y, step);\n
group.setVelocityX(value, step);\n
group.setVelocityY(value, step);\n
group.refresh();  // call this method when position of game objects were changed in static object group\n
"},{"location":"arcade-gameobject/#debug","title":"Debug","text":"
gameObject.setDebug(showBody, showVelocity, bodyColor);\n
gameObject.setDebugBodyColor(bodyColor);\n
"},{"location":"arcade-tcrp-player/","title":"Player","text":""},{"location":"arcade-tcrp-player/#introduction","title":"Introduction","text":"

Player of T ime-C ommand-R ecorder-P layer with Arcade physics engine, to run commands on time.

  • Author: Rex
  • Member of scene

Arcade physics engine is fixed-step based, not tick time based.

This Arcade-TCRP has better result of replaying, which store step count via WORLD_STEP(worldstep) event.

"},{"location":"arcade-tcrp-player/#live-demos","title":"Live demos","text":"
  • Player
"},{"location":"arcade-tcrp-player/#usage","title":"Usage","text":"

Sample code

"},{"location":"arcade-tcrp-player/#install-plugin","title":"Install plugin","text":""},{"location":"arcade-tcrp-player/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexarcadetcrpplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexarcadetcrpplugin.min.js', true);\n
  • Create instance
    var player = scene.plugins.get('rexarcadetcrpplugin').addPlayer(scene, config);\n
"},{"location":"arcade-tcrp-player/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TCRPPlugin from 'phaser3-rex-plugins/plugins/arcadetcrp-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTCRP',\nplugin: TCRPPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var player = scene.plugins.get('rexTCRP').addPlayer(scene, config);\n
"},{"location":"arcade-tcrp-player/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TCRP from 'phaser3-rex-plugins/plugins/arcadetcrp.js';\n
  • Create instance
    var player = new TCRP.Player(scene, config);\n
"},{"location":"arcade-tcrp-player/#create-instance","title":"Create instance","text":"
var player = scene.plugins.get('rexTCRP').addPlayer(scene, {\n// commands: [],       // [[time, command], [time, command], ...]\n// timeScale: 1,\n// scope: undefined\n});\n
  • commands : see next section
  • timeScale : An integer equal or larger than 1
"},{"location":"arcade-tcrp-player/#load-commands","title":"Load commands","text":"
player.load(commands, scope);\n
  • Commands : see also Run commands
    [\n[time, command],\n[time, command],\n...\n]\n
    • Format of each row :
      [time, fnName, param0, param1, ...]\n// [time, callback, param0, param1, ...]\n
      [time, [fnName, param0, param1, ...]]\n// [time, [callback, param0, param1, ...]]\n
      [time, [command0, command1, ...]]\n
    • time : Time in step-count
"},{"location":"arcade-tcrp-player/#start-playing","title":"Start playing","text":"
player.start();\n// player.start(startAt);  // Start-at time in step-count\n
"},{"location":"arcade-tcrp-player/#events","title":"Events","text":"
  • Complete
    player.on('complete', function(player){});\n
  • Run command
    player.on('runcommand', function(commands, scope){});\n
"},{"location":"arcade-tcrp-player/#pause-resume-stop-playing","title":"Pause, Resume, stop playing","text":"
player.pause();\nplayer.resume();\nplayer.stop();\n
"},{"location":"arcade-tcrp-player/#seek-elapsed-time","title":"Seek elapsed time","text":"
player.seek(time);   // Elapsed time in step-count\n
"},{"location":"arcade-tcrp-player/#state-of-player","title":"State of player","text":"
var isPlaying = player.isPlaying;\nvar completed = player.completed;\nvar now = player.now;\n
"},{"location":"arcade-tcrp-player/#time-scale","title":"Time-scale","text":"
  • Set
    player.setTimeScale(value);\n// player.timeScale = value;\n
    • timeScale : An integer equal or larger than 1
  • Get
    var timeScale = player.timeScale;\n
"},{"location":"arcade-tcrp-recorder/","title":"Recoder","text":""},{"location":"arcade-tcrp-recorder/#introduction","title":"Introduction","text":"

Recorder of T ime-C ommand-R ecorder-P layer with Arcade physics engine, to store commands with time.

  • Author: Rex
  • Member of scene

Arcade physics engine is fixed-step based, not tick time based.

This Arcade-TCRP has better result of replaying, which store step count via WORLD_STEP(worldstep) event.

"},{"location":"arcade-tcrp-recorder/#live-demos","title":"Live demos","text":"
  • Player
"},{"location":"arcade-tcrp-recorder/#usage","title":"Usage","text":"

Sample code

"},{"location":"arcade-tcrp-recorder/#install-plugin","title":"Install plugin","text":""},{"location":"arcade-tcrp-recorder/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexarcadetcrpplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexarcadetcrpplugin.min.js', true);\n
  • Create instance
    var recorder = scene.plugins.get('rexarcadetcrpplugin').addRecorder(scene);\n
"},{"location":"arcade-tcrp-recorder/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TCRPPlugin from 'phaser3-rex-plugins/plugins/arcadetcrp-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTCRP',\nplugin: TCRPPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var recorder = scene.plugins.get('rexTCRP').addRecorder(scene);\n
"},{"location":"arcade-tcrp-recorder/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TCRP from 'phaser3-rex-plugins/plugins/arcadetcrp.js';\n
  • Create instance
    var recorder = new TCRP.Recorder(scene);\n
"},{"location":"arcade-tcrp-recorder/#create-instance","title":"Create instance","text":"
var recorder = scene.plugins.get('rexTCRP').addRecorder(scene);\n
"},{"location":"arcade-tcrp-recorder/#start-recording","title":"Start recording","text":"
recorder.start();\n// recorder.start(startAt);  // start-at in step-count\n
"},{"location":"arcade-tcrp-recorder/#push-commands","title":"Push commands","text":"
recorder.addCommand([fnName, param0, param1, ...]);\n// recorder.addCommand([command0, command1, ...]);\n// recorder.addCommand([fnName, param0, param1, ...], offset);  // time-offset in step-count\n

See also Run commands

"},{"location":"arcade-tcrp-recorder/#get-commands","title":"Get commands","text":"
var commands = recorder.getCommands();        // Get a shallow copy of commands\n// var commands = recorder.getCommands(true); // Get reference of commands\n

Format of return commands:

[\n[time, [command]],\n[time, [command0,command1]],\n...\n]\n
  • time : Time in step-count
"},{"location":"arcade-tcrp-recorder/#pause-resume-stop-recording","title":"Pause, Resume, stop recording","text":"
recorder.pause();\nrecorder.resume();\nrecorder.stop();\n
"},{"location":"arcade-tcrp-recorder/#seek-elapsed-time","title":"Seek elapsed time","text":"
recorder.seek(time);   // elapsed time in step-count\n
"},{"location":"arcade-tcrp-recorder/#state-of-recorder","title":"State of recorder","text":"
var isRecording = recorder.isRecording;\nvar now = recorder.now;\n
  • now : Now time in step-count.
"},{"location":"arcade-tcrp-recorder/#time-scale","title":"Time-scale","text":"
  • Set
    recorder.setTimeScale(value);\n// recorder.timeScale = value;\n
    • timeScale : An integer equal or larger than 1
  • Get
    var timeScale = recorder.timeScale;\n
"},{"location":"arcade-tcrp-step-runner/","title":"Step runner","text":""},{"location":"arcade-tcrp-step-runner/#introduction","title":"Introduction","text":"

Execute command in next WORLD_STEP(worldstep) event, to synchronize command execution with step-counter of Recorder of Arcade-TCRP.

  • Author: Rex
  • Member of scene

Command might be executed before or after WORLD_STEP(worldstep) event, which is emitted in scene's update event.

  • Before: Command is executed in any input(touch/keyboard) event, or in scene's preupdate event.
  • After: Command is executed in scene.updat() method.
"},{"location":"arcade-tcrp-step-runner/#live-demos","title":"Live demos","text":"
  • Player
"},{"location":"arcade-tcrp-step-runner/#usage","title":"Usage","text":"

Sample code

"},{"location":"arcade-tcrp-step-runner/#install-plugin","title":"Install plugin","text":""},{"location":"arcade-tcrp-step-runner/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexarcadetcrpplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexarcadetcrpplugin.min.js', true);\n
  • Create instance
    var stepRunner = scene.plugins.get('rexarcadetcrpplugin').addStepRunner(scene);\n
"},{"location":"arcade-tcrp-step-runner/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TCRPPlugin from 'phaser3-rex-plugins/plugins/arcadetcrp-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTCRP',\nplugin: TCRPPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var stepRunner = scene.plugins.get('rexTCRP').addStepRunner(scene);\n
"},{"location":"arcade-tcrp-step-runner/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TCRP from 'phaser3-rex-plugins/plugins/arcadetcrp.js';\n
  • Create instance
    var stepRunner = new TCRP.StepRunner(scene);\n
"},{"location":"arcade-tcrp-step-runner/#create-instance","title":"Create instance","text":"
var stepRunner = scene.plugins.get('rexTCRP').addStepRunner(scene);\n
"},{"location":"arcade-tcrp-step-runner/#push-commands","title":"Push commands","text":"
stepRunner.add(commands, scope);\n

See also Run commands

"},{"location":"arcade-tcrp-step-runner/#offset-recorder","title":"Offset recorder","text":"

Since commands will be executed in next WORLD_STEP(worldstep) event, recorder have to add 1 step-count offset.

  • Offset at recording start
    recorder.start(1);\n
  • Add offset when pushing commands
    recorder.addCommand([fnName, param0, param1, ...], 1);\n
"},{"location":"arcade-world/","title":"World","text":""},{"location":"arcade-world/#introduction","title":"Introduction","text":"

World of Arcade physics engine in phaser.

  • Author: Richard Davey
"},{"location":"arcade-world/#usage","title":"Usage","text":""},{"location":"arcade-world/#configuration","title":"Configuration","text":"
var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n//    x: 0,\n//    y: 0,\n//    width: scene.sys.scale.width,\n//    height: scene.sys.scale.height,\n//    gravity: {\n//        x: 0,\n//        y: 0\n//    },\n//    checkCollision: {\n//        up: true,\n//        down: true,\n//        left: true,\n//        right: true\n//    },\n//    customUpdate: false,\n//    fixedStep: true,\n//    fps: 60,\n//    timeScale: 1,     // 2.0 = half speed, 0.5 = double speed\n//    customUpdate: false,\n//    overlapBias: 4,\n//    tileBias: 16,\n//    forceX: false,\n//    isPaused: false,\n//    debug: false,\n//    debugShowBody: true,\n//    debugShowStaticBody: true,\n//    debugShowVelocity: true,\n//    debugBodyColor: 0xff00ff,\n//    debugStaticBodyColor: 0x0000ff,\n//    debugVelocityColor: 0x00ff00,\n//    maxEntries: 16,\n//    useTree: true   // set false if amount of dynamic bodies > 5000\n}\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"arcade-world/#update","title":"Update","text":"
  • Default updating : World updating every tick
  • Custom updating :
    1. Set customUpdate of arcade config to false.
      • Enable world updating : scene.physics.enableUpdate()
      • Disable world updating : scene.physics.disableUpdate()
    2. Run world updating manually
      scene.physics.world.update(time, delta);\n
    3. Enable/disable world updating
      • Enable : scene.physics.enableUpdate()
      • Disable : scene.physics.disableUpdate()
"},{"location":"arcade-world/#step","title":"Step","text":"
  • Advances the simulation by a single step.
    scene.physics.world.singleStep();\n
  • Advances the simulation by a time increment.
    scene.physics.world.step(delta);\n
"},{"location":"arcade-world/#events","title":"Events","text":"
  • World step
    scene.physics.world.on('worldstep', function(delta) { /* ... */ });\n
    • delta : The delta time amount of this step, in seconds.
"},{"location":"arcade-world/#control","title":"Control","text":""},{"location":"arcade-world/#pause","title":"Pause","text":"
scene.physics.pause();\n
"},{"location":"arcade-world/#resume","title":"Resume","text":"
scene.physics.resume();\n
"},{"location":"arcade-world/#events_1","title":"Events","text":"
  • Pause world
    scene.physics.world.on('pause', function() { /* ... */ });\n
  • Resume world
    scene.physics.world.on('resume', function() { /* ... */ });\n
"},{"location":"arcade-world/#duration-per-frame","title":"Duration per frame","text":"
  • Time scale
    scene.physics.world.timeScale = timeScale;\n
    • 1.0 = normal speed
    • 2.0 = half speed
    • 0.5 = double speed
  • FPS
    scene.physics.world.setFPS(framerate);\n
"},{"location":"arcade-world/#tile-filter-options","title":"Tile filter options","text":"
var option = scene.physics.world.tileFilterOptions;\n
  • option
    {\nisColliding: true,\nisNotEmpty: true,\nhasInterestingFace: true\n}\n
"},{"location":"arcade-world/#body","title":"Body","text":""},{"location":"arcade-world/#enable","title":"Enable","text":"
scene.physics.world.enable(gameObject);\n// scene.physics.world.enable(gameObject, bodyType);\n
  • gameObject : A game object, or array of game objects, or game objects in a Group
  • bodyType :
    • 0 : Dynamic body. Default value.
    • 1 : Static body.

Or

scene.physics.add.existing(gameObject, bodyType);\n

See arcade-body

"},{"location":"arcade-world/#disable","title":"Disable","text":"
scene.physics.world.disable(gameObject);\n
  • gameObject : A game object, or array of game objects, or game objects in a Group
"},{"location":"arcade-world/#addremove-body","title":"Add/remove body","text":"
  • Add body to the local search trees.
    scene.physics.world.add(body);\n
  • Remove body from the local search trees.
    scene.physics.world.disableBody(body);\n
"},{"location":"arcade-world/#collision","title":"Collision","text":""},{"location":"arcade-world/#set-bound","title":"Set bound","text":"

See bound in body object, or game object.

"},{"location":"arcade-world/#collider-callback","title":"Collider & callback","text":"
  • Add collider
    • Push out
      scene.physics.add.collider(objectsA, objectsB);\n
    • Performs a collision check and separation between the two physics enabled objects given.
      var collider = scene.physics.add.collider(objectsA, objectsB, collideCallback);\n// var collider = scene.physics.add.collider(objectsA, objectsB, collideCallback, processCallback, callbackContext);\n
    • If you don't require separation then use overlap instead.
      var collider = scene.physics.add.overlap(objectsA, objectsB, collideCallback);\n// var collider = scene.physics.add.overlap(objectsA, objectsB, collideCallback, processCallback, callbackContext);\n
    • Parameters
      • objectsA, objectsB :
        • A game object
        • An array contains Game objects (Add or remove game objects)
        • Physics group/Group (Add or remove game objects)
        • An array contains Physics group/Group
      • collideCallback :
        var collideCallback = function(gameObject1, gameObject2) {\n// ...\n}\n
      • processCallback : Fired when gameObject1 intersects gameObject2, optional.
        var processCallback = function(gameObject1, gameObject2) {\nreturn true;  // return false will discard remaining collision checking\n}\n
  • Remove collider
    scene.physics.world.removeCollider(collider);\n
  • Deactivate collider
    collider.active = false;  // Set true to activate again\n
  • Name of collider (unused by engine)
    collider.name = name;\n
"},{"location":"arcade-world/#testing-wo-collider","title":"Testing wo collider","text":"
  • Test overlapping
    var isOverlapping = scene.physics.world.overlap(object1, object2);\n
    or
    var isOverlapping = scene.physics.world.overlap(object1, object2, collideCallback);\n// var isOverlapping = scene.physics.world.overlap(object1, object2, collideCallback, processCallback, callbackContext);\n
  • Test colliding, also push out
    var isCollided = scene.physics.world.collide(object1, object2);\n
    or
    var isCollided = scene.physics.world.collide(object1, object2, collideCallback);\n// var isCollided = scene.physics.world.collide(object1, object2, collideCallback, processCallback, callbackContext);\n
"},{"location":"arcade-world/#events_2","title":"Events","text":"
  • Two bodies overlap and at least one of them has their onOverlap property set to true.
    scene.physics.world.on('overlap', function(gameObject1, gameObject2, body1, body2) { /* ... */ });\n
  • Two bodies overlap and at least one of them has their onCollide property set to true.
    scene.physics.world.on('collide', function(gameObject1, gameObject2, body1, body2) { /* ... */ });\n
  • A body overlaps with a Tile and has its onOverlap property set to true.
    scene.physics.world.on('tileoverlap', function(gameObject, tile, body) { /* ... */ });\n
  • A body overlaps with a Tile and has its onCollide property set to true.
    scene.physics.world.on('tilecollide', function(gameObject, tile, body) { /* ... */ });\n
"},{"location":"arcade-world/#world-bounds","title":"World bounds","text":""},{"location":"arcade-world/#enable_1","title":"Enable","text":"
  • Body : Set body.setCollideWorldBounds() to enable worldBounds property.
  • World :
    • Set bounds rectangle and enable bounds
      scene.physics.world.setBounds(x, y, width, height);\n// scene.physics.world.setBounds(x, y, width, height, checkLeft, checkRight, checkUp, checkDown);\n
    • Set bounds rectangle
      scene.physics.world.bounds.setTo(x, y, width, height);\n
      or
      scene.physics.world.bounds.x = x;\nscene.physics.world.bounds.y = y;\nscene.physics.world.bounds.width = width;\nscene.physics.world.bounds.height = height;\n
    • Enable bounds
      scene.physics.world.setBoundsCollision();\n// scene.physics.world.setBoundsCollision(left, right, up, down);\n
      or
      scene.physics.world.checkCollision.left = left;\nscene.physics.world.checkCollision.right = right;\nscene.physics.world.checkCollision.up = up;\nscene.physics.world.checkCollision.down = down;\n
    • Get bounds rectangle
      var top = scene.physics.world.bounds.top;\nvar bottom = scene.physics.world.bounds.bottom;\nvar left = scene.physics.world.bounds.left;\nvar right = scene.physics.world.bounds.right;\n
"},{"location":"arcade-world/#bodies-inside-an-area","title":"Bodies inside an area","text":"
  • Overlap a rectangle area
    var bodies = scene.physics.overlapRect(x, y, width, height, includeDynamic, includeStatic);\n
    • includeDynamic : Set true to search Dynamic Bodies
    • includeStatic : Set true to search Static Bodies
  • Overlap a circle area
    var bodies = scene.physics.overlapCirc(x, y, radius, includeDynamic, includeStatic);\n
    • includeDynamic : Set true to search Dynamic Bodies
    • includeStatic : Set true to search Static Bodies
"},{"location":"arcade-world/#events_3","title":"Events","text":"
  • World bounds
    scene.physics.world.on('worldbounds', function(body, blockedUp, blockedDown, blockedLeft, blockedRight) { /* ... */ });\n
"},{"location":"arcade-world/#wrap","title":"Wrap","text":"
scene.physics.world.wrap(gameObject, padding);\n
  • gameObject:
    • game object
    • group
    • array of game objects
"},{"location":"arcade-world/#move-to","title":"Move to","text":"
  • Move to position with a steady velocity
    scene.physics.moveTo(gameObject, x, y, speed, maxTime);\n
  • Move to object with a steady velocity
    scene.physics.moveToObject(gameObject, destination, speed, maxTime);\n
"},{"location":"arcade-world/#accelerate-to","title":"Accelerate to","text":"
  • Accelerate to position
    scene.physics.accelerateTo(gameObject, x, y, acceleration, xSpeedMax, ySpeedMax);\n
  • Accelerate to object
    scene.physics.accelerateToObject(gameObject, destination, acceleration, xSpeedMax, ySpeedMax);\n
"},{"location":"arcade-world/#gravity","title":"Gravity","text":"
  • Set
    scene.physics.world.gravity.x = gx;\nscene.physics.world.gravity.y = gy;\n
  • Get
    var gx = scene.physics.world.gravity.x;\nvar gy = scene.physics.world.gravity.y;\n

Total Gravity = world.gravity + body.gravity

"},{"location":"arcade-world/#bodies","title":"Bodies","text":""},{"location":"arcade-world/#closestfurthest","title":"Closest/furthest","text":"
  • Closest
    var body = scene.physics.closest(point);  // point: {x,y}\n// var body = scene.physics.closest(point, targets);\n
    • targets : Array of Arcade Physics Game Object, Body or Static Body.
  • Furthest
    var body = scene.physics.furthest(point);  // point: {x,y}\n// var body = scene.physics.furthest(point, targets);\n
    • targets : Array of Arcade Physics Game Object, Body or Static Body.
"},{"location":"arcade-world/#debug","title":"Debug","text":""},{"location":"arcade-world/#draw-body-velocity","title":"Draw body & velocity","text":"
  • Bounds of dynamic Body
    • Enable drawing body
      scene.physics.world.defaults.debugShowBody = true;\n
    • Color
      scene.physics.world.defaults.bodyDebugColor = 0xff00ff;\n
  • Bounds of static Body
    • Enable drawing body
      scene.physics.world.defaults.debugShowStaticBody = true;\n
    • Color
      scene.physics.world.defaults.staticBodyDebugColor = 0x0000ff;\n
  • Direction and magnitude of velocity
    • Enable drawing body
      scene.physics.world.defaults.debugShowVelocity = true;\n
    • Color
      scene.physics.world.defaults.velocityDebugColor = 0x00ff00;\n
"},{"location":"arcade-world/#graphics","title":"Graphics","text":"

Draw debug body & velocity on a Graphics object.

var graphics = scene.physics.world.debugGraphic;\n
  • Set visible
    scene.physics.world.debugGraphic.setVisible();\n
  • Set invisible
    scene.physics.world.debugGraphic.setVisible(false);\n
"},{"location":"arcade-world/#update-loop","title":"Update loop","text":"
  1. scene.sys.events: update
    1. Update position & angle of each body
    2. Process each collider
    3. Update final position of each body
    4. Emit worldstep event
  2. scene.sys.events: postupdate
    1. Draw debug graphics
graph TB\n\nSceneEventUpdate>\"scene.sys.events: update<br><br>Update arcade world<br>gameObject.preUpdate()\"]\nSceneUpdate[\"scene.update()\"]\nSceneEventPostUpdate>\"scene.sys.events: postupdate<br><br>Post update arcade world\"]\nRender\n\nSceneEventUpdate --> SceneUpdate\nSceneUpdate --> SceneEventPostUpdate\nSceneEventPostUpdate --> Render
"},{"location":"array-addremove/","title":"Add/remove","text":""},{"location":"array-addremove/#introduction","title":"Introduction","text":"

Add/insert/remove item(s) of an array, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"array-addremove/#usage","title":"Usage","text":""},{"location":"array-addremove/#add-item","title":"Add item","text":"
Phaser.Utils.Array.Add(arr, item);\n// Phaser.Utils.Array.Add(arr, item, limit, callback, context);\n
  • item : An item, or an array of items.
  • limit : Optional limit which caps the size of the array.
  • callback : A callback to be invoked for each item successfully added to the array.
  • context : The context in which the callback is invoked.
"},{"location":"array-addremove/#insert-item-at","title":"Insert item at","text":"
Phaser.Utils.Array.AddAt(arr, item, index);\n// Phaser.Utils.Array.AddAt(arr, item, index, limit, callback, context);\n
  • index : The index in the array where the item will be inserted.
  • item : An item, or an array of items.
  • limit : Optional limit which caps the size of the array.
  • callback : A callback to be invoked for each item successfully added to the array.
  • context : The context in which the callback is invoked.
"},{"location":"array-addremove/#remove-item","title":"Remove item","text":"
Phaser.Utils.Array.Remove(arr, item);\n// Phaser.Utils.Array.Remove(arr, item, callback, context);\n
  • item : An item, or an array of items.
  • callback : A callback to be invoked for each item successfully removed from the array.
  • context : The context in which the callback is invoked.
"},{"location":"array-addremove/#remove-item-at","title":"Remove item at","text":"
var removed = Phaser.Utils.Array.RemoveAt(arr, index);\n// var removed = Phaser.Utils.Array.RemoveAt(arr, index, callback, context);\n
  • removed : Removed item.
  • index : The array index to remove the item from. The index must be in bounds or it will throw an error.
  • callback : A callback to be invoked for each item successfully removed from the array.
  • context : The context in which the callback is invoked.
"},{"location":"array-addremove/#remove-items-between","title":"Remove items between","text":"
var removed = Phaser.Utils.Array.RemoveBetween(arr, startIndex, endIndex);\n// var removed = Phaser.Utils.Array.RemoveBetween(arr, startIndex, endIndex, callback, context);\n
  • removed : Removed items.
  • startIndex : The start index to remove from.
  • callback : The end index to remove to.
  • callback : A callback to be invoked for each item successfully removed from the array.
  • context : The context in which the callback is invoked.
"},{"location":"array-addremove/#remove-random-item","title":"Remove random item","text":"
var item = Phaser.Utils.Array.RemoveRandomElement(arr);\n
"},{"location":"array-addremove/#replace-item","title":"Replace item","text":"

Replaces an element of the array with the new element. The new element cannot already be a member of the array.

Phaser.Utils.Array.Replace(arr, oldItem, newItem);\n
  • oldItem : An item in array.
  • newItem : Another item, which is not in array.
"},{"location":"array-filter/","title":"Filter/Map","text":""},{"location":"array-filter/#introduction","title":"Introduction","text":"

Built-in javascript object.

  • Author: Built-in javascript function
"},{"location":"array-filter/#usage","title":"Usage","text":""},{"location":"array-filter/#run-function-for-each-element","title":"Run function for each element","text":"
arr.forEach(function(element, index, arr) {\n//\n}, scope);\n
"},{"location":"array-filter/#filter-elements","title":"Filter elements","text":"

Creates a new array with all elements that pass the test function.

var result = arr.filter(function(element, index, arr) {\nreturn true; // false\n}, scope);\n
"},{"location":"array-filter/#find-one-element","title":"Find one element","text":"
var element = arr.find(function(element, index, arr) {\nreturn true; // false\n}, scope);\n
"},{"location":"array-filter/#map-elements-to-a-new-array","title":"Map elements to a new array","text":"
var newArray = arr.map(function(element, index, arr) {\nreturn newElement;\n}, scope);\n
"},{"location":"array-random/","title":"Random","text":""},{"location":"array-random/#introduction","title":"Introduction","text":"

Random operation of an array, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"array-random/#usage","title":"Usage","text":""},{"location":"array-random/#get-random-item","title":"Get random item","text":"
var item = Phaser.Utils.Array.GetRandom(arr);\n// var item = Phaser.Utils.Array.GetRandom(arr, startIndex, length);\n
"},{"location":"array-random/#remove-random-item","title":"Remove random item","text":"
var item = Phaser.Utils.Array.RemoveRandomElement(arr);\n// var item = Phaser.Utils.Array.RemoveRandomElement(arr, startIndex, length);\n
"},{"location":"array-random/#shuffle","title":"Shuffle","text":"
var arr = Phaser.Utils.Array.Shuffle(arr);\n
"},{"location":"array-sort/","title":"Sort","text":""},{"location":"array-sort/#introduction","title":"Introduction","text":"

Array sorting, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"array-sort/#usage","title":"Usage","text":""},{"location":"array-sort/#built-in-array-sort","title":"Built-in array sort","text":"
var out = arr.sort(compareFunction);\n
  • compareFunction : A function that defines an alternative sort order.
    function(a, b) {\n// return a - b;\n}\n
    • Return a negative value
    • Return 0
    • Return a positive value
"},{"location":"array-sort/#stable-array-sort","title":"Stable array sort","text":"
var out = Phaser.Utils.Array.StableSort(arr, compareFunction);\n
"},{"location":"array-sort/#shuffle","title":"Shuffle","text":"
var arr = Phaser.Utils.Array.Shuffle(arr);\n
"},{"location":"array-sort/#move-item","title":"Move item","text":"
  • Moves the given element to the top of the array.
    Phaser.Utils.Array.BringToTop(arr, item);\n
  • Moves the given element to the bottom of the array.
    Phaser.Utils.Array.SendToBack(arr, item);\n
  • Moves the given array element up.
    Phaser.Utils.Array.MoveUp(array, item);\n
  • Moves the given array element down.
    Phaser.Utils.Array.MoveDown(array, item);\n
  • Moves an element in an array to a new position.
    Phaser.Utils.Array.MoveTo(array, item, index);\n
  • Swaps the position of two elements.
    Phaser.Utils.Array.Swap(array, item1, item2);\n
  • Moves the element at the start of the array to the end, shifting all items in the process.
    Phaser.Utils.Array.RotateLeft(array, steps);\n
    • steps : The number of times to shift the array.
  • Moves the element at the end of the array to the start, shifting all items in the process.
    Phaser.Utils.Array.RotateRight(array, steps);\n
    • steps : The number of times to shift the array.
"},{"location":"audio/","title":"Audio","text":""},{"location":"audio/#introduction","title":"Introduction","text":"

Play sounds, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"audio/#usage","title":"Usage","text":""},{"location":"audio/#configuration","title":"Configuration","text":""},{"location":"audio/#web-audio","title":"Web audio","text":"

Web audio is the default audio context.

"},{"location":"audio/#html5-audio","title":"Html5 audio","text":"
var config = {\n// ....\naudio: {\ndisableWebAudio: true\n}\n// ....\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"audio/#no-audio","title":"No audio","text":"
var config = {\n// ....\naudio: {\nnoAudio: true\n}\n// ....\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"audio/#load-audio-file","title":"Load audio file","text":"
scene.load.audio(key, urls);  // urls: an array of file url\n// scene.load.audio(key, urls, {instances: 1}, xhrSettings);\n

See loader

"},{"location":"audio/#decode-audio","title":"Decode audio","text":"
scene.sound.decodeAudio(key, audioData);\n
  • audioData : Audio data
    • A base64 encoded string
    • An audio media-type data uri
    • An ArrayBuffer instance

Or

scene.sound.decodeAudio(audioFiles);\n
  • audioFiles : An array of {key, data}
    • data : Audio data
      • A base64 encoded string
      • An audio media-type data uri
      • An ArrayBuffer instance
"},{"location":"audio/#decoded-events","title":"Decoded events","text":"
  • Finished decoding an audio data
    scene.sound.on('decoded', key);\n
  • Finished decoding all audio data
    scene.sound.on('decodedall');\n
"},{"location":"audio/#unlock-audio","title":"Unlock audio","text":"

Unlocks Web Audio API/HTML5 Audio loading on the initial input event.

scene.sound.unlock();\n
"},{"location":"audio/#play-sound","title":"Play sound","text":"

Sound instance will be destroyed when playback ends.

scene.sound.play(key);\n

or

scene.sound.play(key, config);\n/*\nvar sound = scene.sound.add(key);\nsound.play(config);\n*/\n
"},{"location":"audio/#position-of-the-spatial-audio-listener","title":"Position of the Spatial Audio listener","text":"
scene.sound.setListenerPosition(x, y)\n
  • x, y : The x/y position of the Spatial Audio listener. Default value is center of the game canvas.

Note

Web audio only

"},{"location":"audio/#sound-instance","title":"Sound instance","text":""},{"location":"audio/#create-sound-instance","title":"Create sound instance","text":"
var music = scene.sound.add(key);\n
var music = scene.sound.add(key, config);\n
"},{"location":"audio/#configuration_1","title":"Configuration","text":"
{\nmute: false,\nvolume: 1,\nrate: 1,\ndetune: 0,\nseek: 0,\nloop: false,\ndelay: 0,\n\n// source of the spatial sound\nsource: {\nx: 0,\ny: 0,\nz: 0,\npanningModel: 'equalpower',\ndistanceModel: 'inverse',\norientationX: 0,\norientationY: 0,\norientationZ: -1,\nrefDistance: 1,\nmaxDistance: 10000,\nrolloffFactor: 1,\nconeInnerAngle: 360,\nconeOuterAngle: 0,\nconeOuterGain: 0,\nfollow: undefined\n}\n}\n
  • source : Source of the spatial sound
    • x, y : The horizontal/vertical position of the audio in a right-hand Cartesian coordinate system.
    • z : Represents the longitudinal (back and forth) position of the audio in a right-hand Cartesian coordinate system.
    • panningModel : An enumerated value determining which spatialization algorithm to use to position the audio in 3D space.
      • 'equalpower'
      • 'HRTF'
    • orientationX, orientationY : The horizontal/vertical position of the audio source's vector in a right-hand Cartesian coordinate system.
    • orientationZ : Represents the longitudinal (back and forth) position of the audio source's vector in a right-hand Cartesian coordinate system.
    • refDistance : A double value representing the reference distance for reducing volume as the audio source moves further from the listener. For distances greater than this the volume will be reduced based on rolloffFactor and distanceModel.
    • maxDistance : The maximum distance between the audio source and the listener, after which the volume is not reduced any further.
    • rolloffFactor : A double value describing how quickly the volume is reduced as the source moves away from the listener. This value is used by all distance models.
    • coneInnerAngle : The angle, in degrees, of a cone inside of which there will be no volume reduction.
    • coneOuterAngle : The angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the coneOuterGain property.
    • coneOuterGain : The amount of volume reduction outside the cone defined by the coneOuterAngle attribute. Its default value is 0, meaning that no sound can be heard. A value between 0 and 1.
    • follow : Set this Sound object to automatically track the x/y position of this object. Can be a Phaser Game Object, Vec2 or anything that exposes public x/y properties.
"},{"location":"audio/#play-sound-instance","title":"Play sound instance","text":"
  • Start playing
    music.play();\n
  • Start playing with configuration
    music.play(config);\n
    • config
  • Stop
    music.stop();\n
  • Pause
    music.pause();\n
  • Resume
    music.resume();\n
"},{"location":"audio/#methods","title":"Methods","text":""},{"location":"audio/#mute","title":"Mute","text":"
  • Set
    music.setMute(mute); // mute: true/false\n// music.mute = mute;\n
  • Get
    var mute = music.mute;\n
"},{"location":"audio/#volume","title":"Volume","text":"
  • Set
    music.setVolume(volume); // volume: 0 to 1\n// music.volume = volume;\n
  • Get
    var volume = music.volume;\n
"},{"location":"audio/#detune","title":"Detune","text":"
  • Set
    music.setDetune(detune); // detune: -1200 to 1200\n// music.detune = detune;\n
  • Get
    var detune = music.detune;\n
"},{"location":"audio/#play-rate","title":"Play-rate","text":"
  • Set
    music.setRate(rate); // rate: 1.0(normal speed), 0.5(half speed), 2.0(double speed)\n// music.rate = rate;\n
  • Get
    var rate = music.rate;\n
"},{"location":"audio/#seek-to","title":"Seek to","text":"
  • Seek to
    music.setSeek(time); // seek: playback time\n// music.seek = seek;\n
  • Get current playback time
    var time = music.seek;  // return 0 when playback ends\n
"},{"location":"audio/#loop","title":"Loop","text":"
  • Set
    music.setLoop(loop); // loop: true/false\n// music.loop = loop;\n
  • Get
    var loop = music.loop;\n
"},{"location":"audio/#properties","title":"Properties","text":"
  • Duration : duration of this sound
    var duration = music.duration;\n
  • Is playing
    var isPlaying = music.isPlaying;\n
  • Is paused
    var isPaused = music.isPaused;\n
  • Asset key
    var key = music.key;\n
"},{"location":"audio/#events","title":"Events","text":"
  • Start playing
    music.once('play', function(music){});\n
  • Playback end
    music.once('complete', function(music){});\n
  • Looping
    music.once('looped', function(music){});\n
  • Pause
    music.once('pause', function(music){});\n
  • Resume
    music.once('resume', function(music){});\n
  • Stop
    music.once('stop', function(music){});\n
  • Set mute
    music.once('mute', function(music, mute){});\n
  • Set volume
    music.once('volume', function(music, volume){});\n
  • Set detune
    music.once('detune', function(music, detune){});\n
  • Set play-rate
    music.once('rate', function(music, rate){});\n
  • Seek to
    music.once('seek', function(music, time){});\n
  • set loop
    music.once('loop', function(music, loop){});\n
"},{"location":"audio/#play-marked-sound","title":"Play marked sound","text":"

Sound instance will be destroyed when playback ends.

scene.sound.play(key, marker);\n
"},{"location":"audio/#marker","title":"Marker","text":"
{\nname: '',\nstart: 0,\nduration: music.duration,\nconfig: {\nmute: false,\nvolume: 1,\nrate: 1,\ndetune: 0,\nseek: 0,\nloop: false,\ndelay: 0\n}\n}\n
"},{"location":"audio/#markers-in-sound-instance","title":"Markers in sound instance","text":""},{"location":"audio/#add-marker","title":"Add marker","text":"
music.addMarker(marker);\n

Marker

"},{"location":"audio/#play-marked-sound_1","title":"Play marked sound","text":"
music.play(markerName);\n
music.play(markerName, config);\n

config

"},{"location":"audio/#audio-sprite","title":"Audio sprite","text":""},{"location":"audio/#load-audio-sprite","title":"Load audio sprite","text":"
scene.load.audioSprite(key, urls, markersConfig, config);\n

See loader

Format of markersConfig

{\nresources: urls, // an array of audio files\nspritemap: {\nmarkerName0: {\nstart: 0,\nend: 0\n},\nmarkerName1: {\nstart: 0,\nend: 0\n}\n// ...\n}\n}\n

"},{"location":"audio/#play-sound_1","title":"Play sound","text":"

Create a sound instance then play the marked section, this sound instance will be destroyed when playback ends.

scene.sound.playAudioSprite(key, markerName, config);\n

config

"},{"location":"audio/#sound-instance_1","title":"Sound instance","text":"

Create a sound instance with markers.

var music = scene.sound.addAudioSprite(key, config);\n

config

"},{"location":"audio/#play-sound-instance_1","title":"Play sound instance","text":"
music.play(markerName);\n
music.play(markerName, config);\n

config

"},{"location":"audio/#sound-manager","title":"Sound manager","text":""},{"location":"audio/#mute_1","title":"Mute","text":"
  • Set
    scene.sound.setMute(mute); // mute: true/false\n// scene.sound.mute = mute;\n
  • Get
    var mute = scene.sound.mute;\n
"},{"location":"audio/#volume_1","title":"Volume","text":"
  • Set
    scene.sound.setVolume(volume); // volume: 0 to 1\n// scene.sound.volume = volume;\n
  • Get
    var volume = scene.sound.volume;\n
"},{"location":"audio/#detune_1","title":"Detune","text":"
  • Set
    scene.sound.setDetune(detune); // detune: -1200 to 1200\n// scene.sound.detune = detune;\n
  • Get
    var detune = scene.sound.detune;\n
"},{"location":"audio/#play-rate_1","title":"Play-rate","text":"
  • Set
    scene.sound.setRate(rate); // rate: 1.0(normal speed), 0.5(half speed), 2.0(double speed)\n// scene.sound.rate = rate;\n
  • Get
    var rate = scene.sound.rate;\n
"},{"location":"audio/#get-music-instance","title":"Get music instance","text":"
  • Get first by key
    var music = scene.sound.get(key); // music instance, or null\n
  • Get all by key
    var musicArray = scene.sound.getAll(key); // music instance, or null\n
  • Get all
    var musicArray = scene.sound.getAll();\n
  • Get all playing
    var musicArray = scene.sound.getAllPlaying();\n
"},{"location":"audio/#is-playing","title":"Is playing","text":"
  • Is any sound playing
    var isPlaying = scene.sound.isPlaying();\n
  • Is any sound playing by key
    var isPlaying = scene.sound.isPlaying(key);\n
"},{"location":"audio/#remove-music-instance","title":"Remove music instance","text":"
  • Remove by key
    var removed = scene.sound.removeByKey(key);\n
    • removed : The number of matching sound objects that were removed.
  • Remove all
    scene.sound.removeAll();\n
"},{"location":"audio/#stop-music-instance","title":"Stop music instance","text":"
  • Stop by key
    var stopped = scene.sound.stopByKey(key);\n
    • stopped : How many sounds were stopped.
  • Stop all
    scene.sound.stopAll();\n
"},{"location":"audio/#analyser","title":"Analyser","text":"

Analyser node is only available in Web audio mode.

  1. Create analyser node
    var analyser = scene.sound.context.createAnalyser();\n
  2. Configure analyser node
    analyser.smoothingTimeConstant = 1;\nanalyser.fftSize = 8192;\nanalyser.minDecibels = -90;\nanalyser.maxDecibels = -10;\n
    • smoothingTimeConstant : Averaging constant with the last analysis frame.
      • 0(no time averaging) ~ 1. Default value is 0.8.
    • fftSize : Window size.
      • 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, and 32768. Defaults to 2048.
    • minDecibels : Minimum decibel value for scaling the FFT analysis data.
      • 0 dB is the loudest possible sound, -10 dB is a 10th of that, etc. The default value is -100 dB
    • maxDecibels : Maximum decibel value for scaling the FFT analysis data.
      • The default value is -30 dB.
  3. Set source of analyser node
    • Global volume nodee -> analyser node
      scene.sound.masterVolumeNode.connect(analyser);\n
    • A sound instance -> analyser node
      music.volumeNode.connect(analyser);\n
  4. Ouput analyser node to audio context
    analyser.connect(scene.sound.context.destination);\n
  5. Create output data array
    var dataArrayLength = analyser.frequencyBinCount;\nvar dataArray = new Uint8Array(dataArrayLength);\n
  6. Get output data
    analyser.getByteTimeDomainData(dataArray);\n
    • Retrieve output data
      for(var i= 0; i < dataArrayLength; i++) {\nvar data = dataArray[i];\n}\n
"},{"location":"awaitloader/","title":"Await loader","text":""},{"location":"awaitloader/#introduction","title":"Introduction","text":"

Await custom task in preload stage.

  • Author: Rex
  • Custom File of loader
"},{"location":"awaitloader/#live-demos","title":"Live demos","text":"
  • Wait 1000ms
"},{"location":"awaitloader/#usage","title":"Usage","text":"

Sample code

"},{"location":"awaitloader/#install-plugin","title":"Install plugin","text":""},{"location":"awaitloader/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    var sceneConfig = {\n// ....\npack: {\nfiles: [{\ntype: 'plugin',\nkey: 'rexawaitloaderplugin',\nurl: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/    rexawaitloaderplugin.min.js',\nstart: true\n}]\n}\n};\nclass MyScene extends Phaser.Scene {\nconstructor() {\nsuper(sceneConfig)\n}\n// ....\n\npreload() {\n// rexawaitloaderplugin will be installed before preload(), but not added to loader yet\n// Call addToScene(scene) to add this await loader to loader of this scene\nthis.plugins.get('rexawaitloaderplugin').addToScene(this);\n\nthis.load.rexAwait(function(successCallback, failureCallback) { // successCallback()\n});\n}\n}\n
"},{"location":"awaitloader/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import AwaitLoaderPlugin from 'phaser3-rex-plugins/plugins/awaitloader-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAwaitLoader',\nplugin: AwaitLoaderPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • In preload stage
    scene.load.rexAwait(function(successCallback, failureCallback) { // successCallback()\n});\n
"},{"location":"awaitloader/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Awaitloader from 'phaser3-rex-plugins/plugins/awaitloader.js';\n
  • Start loading task
    Awaitloader.call(scene.load, function(successCallback, failureCallback) {\n// successCallback();\n}, scope)\n
"},{"location":"awaitloader/#start-loading-task","title":"Start loading task","text":"

In preload stage:

scene.load.rexAwait(function(successCallback, failureCallback) {\n// successCallback();\n}, scope);\n

or

var callback = function(successCallback, failureCallback) {\n// successCallback();\n};\nscene.load.rexAwait(key, {\ncallback: callback,\n// scope: scope\n});\n
  1. This plugin runs callback to start custom task.
  2. Calls successCallback when custom task completed, or failureCallback if error.
"},{"location":"awaytime/","title":"Away time","text":""},{"location":"awaytime/#introduction","title":"Introduction","text":"

Get time from previous closing application to now.

  • Author: Rex
  • Standalone object
"},{"location":"awaytime/#usage","title":"Usage","text":"

Sample code

"},{"location":"awaytime/#install-plugin","title":"Install plugin","text":""},{"location":"awaytime/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexawaytimeplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexawaytimeplugin.min.js', true);\n
  • Get away-time
    var awayTime = scene.plugins.get('rexawaytimeplugin').awayTime;\n
"},{"location":"awaytime/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import AwayTimePlugin from 'phaser3-rex-plugins/plugins/awaytime-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAwayTime',\nplugin: AwayTimePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Get away-time
    var awayTime = scene.plugins.get('rexAwayTime').awayTime;\n
"},{"location":"awaytime/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import AwayTime from 'phaser3-rex-plugins/plugins/awaytime.js';\n
  • Get away-time
    var awayTime = (new AwayTime()).awayTime;\n
"},{"location":"awaytime/#default-away-timer","title":"Default away-timer","text":""},{"location":"awaytime/#get-away-time","title":"Get away-time","text":"
var awayTime = scene.plugins.get('rexAwayTime').awayTime;\n// var awayTime = scene.plugins.get('rexAwayTime').setKey(key).setPeriod(time).awayTime;\n
  • awayTime : Time in millisecond.
  • key : Save curent time-stamp in key of localstorage. Default value is 'away'.
  • time : Period of saving current time-stamp. Default value is 1000.

Note

This action also starts saving current time-stamp periodically into localstorage.

"},{"location":"awaytime/#set-key","title":"Set key","text":"
scene.plugins.get('rexAwayTime').setKey(key);\n
  • key : Save curent time-stamp in key of localstorage
"},{"location":"awaytime/#set-period","title":"Set period","text":"
scene.plugins.get('rexAwayTime').setPeriod(time);\n
  • time : Period of saving current time-stamp.
"},{"location":"awaytime/#add-away-timer-object","title":"Add away timer object","text":"
var awayTimer = scene.plugins.get('rexAwayTime').add({\nkey: 'away',\nperiod: 1000\n})\n
"},{"location":"awaytime/#get-away-time_1","title":"Get away-time","text":"
var awayTime = awayTimer.awayTime;\n

Will also start timer.

"},{"location":"awaytime/#stop-timer","title":"Stop timer","text":"
awayTimer.stop();\n
"},{"location":"base64/","title":"Base64","text":""},{"location":"base64/#introduction","title":"Introduction","text":"

Decode a base64 string to an array buffer, or create a base64 string from an array buffer, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"base64/#usage","title":"Usage","text":""},{"location":"base64/#base64-array-buffer","title":"Base64 -> Array buffer","text":"
var arrayBuffer = Phaser.Utils.Base64.Base64ToArrayBuffer(base64);\n
"},{"location":"base64/#array-buffer-base64","title":"Array buffer -> Base64","text":"
var base64 = Phaser.Utils.Base64.ArrayBufferToBase64(arrayBuffer, mediaType);\n
  • mediaType : An optional media type, i.e. audio/ogg or image/jpeg
"},{"location":"bbcodetext/","title":"BBCode Text","text":""},{"location":"bbcodetext/#introduction","title":"Introduction","text":"

Drawing text with BBCode protocol.

  • Author: Rex
  • Game object
"},{"location":"bbcodetext/#live-demos","title":"Live demos","text":"
  • BBCode text
  • Hit area of words
  • Align
  • Escape
  • Page, typing
  • Wrap
    • Mix wrap
  • Measure margin of text
  • Generate texture
  • Image height
  • RTL
"},{"location":"bbcodetext/#usage","title":"Usage","text":"

Sample code

"},{"location":"bbcodetext/#install-plugin","title":"Install plugin","text":""},{"location":"bbcodetext/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbbcodetextplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbbcodetextplugin.min.js', true);\n
  • Add text object
    var txt = scene.add.rexBBCodeText(x, y, content, config);\n
"},{"location":"bbcodetext/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BBCodeTextPlugin from 'phaser3-rex-plugins/plugins/bbcodetext-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBBCodeTextPlugin',\nplugin: BBCodeTextPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text object
    var txt = scene.add.rexBBCodeText(x, y, content, config);\n
"},{"location":"bbcodetext/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import BBCodeText from 'phaser3-rex-plugins/plugins/bbcodetext.js';\n
  • Add text object
    var txt = new BBCodeText(scene, x, y, content, config);\nscene.add.existing(txt);\n
"},{"location":"bbcodetext/#bbcode","title":"BBCode","text":"
  • Bold : [b]text[/b]
  • Weight : [weight=900]text[/weight]
    • Valid when text does not have bold tag.
  • Italic : [i]text[/i]
  • Color :
    • [color=red]text[/color]
    • [color=#FF0000]text[/color]
    • [color=rgb(255,0,0)]text[/color]
    • [color=rgba(255,0,0,1)]text[/color]
  • Size : [size=18]text[/size]
  • Stroke : [stroke]text[/stroke]
    • Stroke with color setting : [stroke=red]text[/stroke]
  • Shadow : [shadow]text[/shadow]
    • Shadow with color setting : [shadow=red]text[/shadow]
  • Underline : [u]text[/u]
    • Underline with color setting : [u=red]text[/u]
  • Strikethrough : [s]text[/s]
    • Strikethrough with color setting : [s=red]text[/s]
  • Background color :
    • [bgcolor=red]text[/bgcolor]
    • [bgcolor=#FF0000]text[/bgcolor]
    • [bgcolor=rgb(255,0,0)]text[/bgcolor]
    • [bgcolor=rgba(255,0,0,1)]text[/bgcolor]
  • Superscript, subscript : [y=-12]text[y]
  • Image : [img=imgKey]
  • Hit area of words : [area=key]text[/area]
  • Url link : [url=http...]text[/url]
    • Click this area to open web page on a new tab (window.open(url, '_blank'))
    • Will register hit area with key url:http...
  • Line alignment :
    • [align=left]text[/align],
    • [align=center]text[/align],
    • [align=right]text[/align]
  • Escape : Tags between [esc] ... [/esc] or [raw] ... [/raw] will be treated as content.
    • [esc][color=yellow]Text[/color][/esc]
    • [esc][raw]Text[/raw][/esc]
    • [raw][esc]Text[/esc][/raw]
    • [raw][b]Text[/b][/raw]
  • Do nothing, just a marker :
    • [id=0][color=red]Text[/id]TextText[/color]

Note

Can set delimiter [] to another custom value in style of constructor.

"},{"location":"bbcodetext/#add-text-object","title":"Add text object","text":"
var txt = scene.add.rexBBCodeText(x, y, '[b]h[/b]ello');\n// var txt = scene.add.rexBBCodeText(x, y, '[b]h[/b]ello', { fontFamily: 'Arial', fontSize: 64, color: '#00ff00' });\n

Default style

{\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,  // null, css string, or number\nbackgroundColor2: null,  // null, css string, or number\nbackgroundHorizontalGradient: true,\nbackgroundStrokeColor: null,  // null, css string, or number\nbackgroundStrokeLineWidth: 2,\n\nbackgroundCornerRadius: 0,  // 0   : no round corner, \n// > 0 : convex round corner\n// < 0 : concave round corner\n\nbackgroundCornerIteration: null,    color: '#fff',  // null, css string, or number\nstroke: '#fff',  // null, css string, or number\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',  // css string, or number\nblur: 0,\nstroke: false,\nfill: false\n},\nunderline: {\ncolor: '#000',  // css string, or number\nthickness: 0,\noffset: 0\n},\nstrikethrough: {\ncolor: '#000',  // css string, or number\nthickness: 0,\noffset: 0\n},\n// align: 'left',  // Equal to halign\nhalign: 'left', // 'left'|'center'|'right'\nvalign: 'top',  // 'top'|'center'|'bottom'\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\nmaxLines: 0,\nlineSpacing: 0,\nfixedWidth: 0,\nfixedHeight: 0,\ntestString: '|M\u00c9qgy',\n\nwrap: {\nmode: 'none',     // 0|'none'|1|'word'|2|'char'|'character'|3|'mix'\nwidth: null\n},\n// wordWrap: { width: 0 },   // Compatible with Text game object\n\n// rtl: false,\nmetrics: false,\n// metrics: {\n//     ascent: 0,\n//     descent: 0,\n//     fontSize: 0\n// },\n\n// images: {\n//     imgKey: {y: -8}\n// },\n\n// delimiters: '[]',\n\n// sharedPool: true,\n\n// urlTagCursorStyle: 'pointer',\n// interactive: false\n}\n

or

var txt = scene.add.rexBBCodeText({\nx: 0,\ny: 0,\ntext: '',\nstyle: {\nfontSize: '64px',\nfontFamily: 'Arial',\ncolor: '#ffffff',\nalign: 'center',\nbackgroundColor: '#ff00ff',\n// ...\n},\n})\n

or

var txt = scene.make.rexBBCodeText({\nx: 0,\ny: 0,\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n//x: 32,    // 32px padding on the left/right\n//y: 16     // 16px padding on the top/bottom\n},\ntext: 'Text\\nGame Object\\nCreated from config',\nstyle: {\nfontSize: '64px',\nfontFamily: 'Arial',\ncolor: '#ffffff',\nalign: 'center',\nbackgroundColor: '#ff00ff',\n// ...\n},\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
  • Alignment
    • halign, or align : Horizontal alignment.
      • 'left', 'center', 'right'
    • valign : Vertical alignment.
      • 'top', 'center', 'bottom'
  • images : See Image
  • delimiters : Delimiters of tags, default value is [].
    • Don't use () as delimiters, which is preserved for color value.
  • sharedPool :
    • true : Use shared resouce pools during game. Default behavior.
    • false : Use local resource pools, will be free when game object destroying.
  • urlTagCursorStyle : Cursor style when cursor moving over a url tag. Default value is 'pointer'.
  • interactive :
    • true : Invoke txt.setInteractive() for hit-area tag, or url tag.
    • false : Do nothing. Default behavior.
"},{"location":"bbcodetext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyText extends BBCodeText {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyText(scene, x, y, '[b]h[/b]ello');\n
"},{"location":"bbcodetext/#wrap","title":"Wrap","text":"
  • Wrap by word or character.
    var txt = scene.make.rexBBCodeText({\nx: 400,\ny: 100,\ntext: 'The sky above the port was the color of television, tuned to a dead channel.',\norigin: { x: 0.5, y: 0.5 },\nstyle: {\nfont: 'bold 25px Arial',\nfill: 'white',\nwrap: {\nmode: 'none',    // 0|'none'|1|'word'|2|'char'|'character'|3|'mix'\nwidth: 0\n}\n}\n});\n
    • wrap.mode :
      • 0, or 'none' : No wrapping, default behavior.
      • 1, or 'word' : Word wrapping.
      • 2, or 'char', or 'character' : Character wrapping.
      • 3, or 'mix' : Word wrapping for ASCII word, Character wrapping for other (unicode) word.
    • wrap.width : Maximun wrapping width of a line.
      • Wrap-fit : Set wrapping width to fixedWidth - padding.left - padding.right if fixedWidth > 0
  • Wrap mode
    • Get
      var mode = txt.style.wrapMode;\n
    • Set
      txt.setWrapMode(mode);\n
      • 0, or 'none' : No wrapping.
      • 1, or 'word' : Word wrapping.
      • 2, or 'char', or 'character' : Character wrapping.
      • 3, or 'mix' : Word wrapping for ASCII word, Character wrapping for other (unicode) word.
  • Wrap width
    • Get
      var width = txt.style.wrapWidth;\n
    • Set
      txt.setWrapWidth(width);\n// txt.setWordWrapWidth(width);\n
      • width : Maximun wrapping width of a line.
        • Wrap-fit : Set wrapping width to fixedWidth - padding.left - padding.right if fixedWidth > 0
"},{"location":"bbcodetext/#content","title":"Content","text":"
  • Get source text
    var curContent = txt.text;\n
  • Get plain text
    var plainText = txt.getPlainText();\n
    var plainText = txt.getPlainText(content);\n
  • Get sub-string
    var text = txt.getText(start, end);\n
  • Get wrapped lines
    var linesArray = txt.getWrappedText();\n
    var linesArray = txt.getWrappedText(content);\n
  • Set
    txt.setText('[b]h[/b]ello');\n// txt.text = '[b]h[/b]ello';\n
  • Append
    txt.appendText(text);\n// txt.text += '\\n' + text;\n
    or
    txt.appendText(text, false);\n// txt.text += text;\n
"},{"location":"bbcodetext/#set-style","title":"Set style","text":"
txt.setStyle(style);\ntxt.setFont(font);  // font: {fontFamily, fontSize, fontStyle}\ntxt.setFontFamily(family);\ntxt.setFontSize(size);\ntxt.setFontStyle(style);\n
"},{"location":"bbcodetext/#color","title":"Color","text":"
  • Text color
    • Get
      var color = txt.style.color;\n
    • Set
      txt.setColor(color);\n
      or
      txt.setFill(color);\n
      • color : null, css string, or number.
  • Stroke color, thickness
    • Get
      var color = txt.style.stroke;\nvar thickness = txt.style.strokeThickness;\n
    • Set
      txt.setStroke(color, thickness);\n
      • color : null, css string, or number.
    • Clear
      txt.setStroke();\n
  • Underline color, thickness
    • Get
      var color = txt.style.underlineColor;\nvar thickness = txt.style.underlineThickness;\nvar offset = txt.style.underlineOffset;\n
    • Set
      txt.setUnderline(color, thickness, ofset);\ntxt.setUnderlineColor(color);\ntxt.setUnderlineThinkness(thickness);\ntxt.setUnderlineOffset(ofset);\n
      • color : null, css string, or number.
  • Strikethrough color, thickness
    • Get
      var color = txt.style.strikethroughColor;\nvar thickness = txt.style.strikethroughThickness;\nvar offset = txt.style.strikethroughOffset;\n
    • Set
      txt.setStrikethrough(color, thickness, ofset);\ntxt.setStrikethroughColor(color);\ntxt.setStrikethroughThinkness(thickness);\ntxt.setStrikethroughOffset(ofset);\n
      • color : null, css string, or number.
  • Background
    • Color, or gradient color
      • Get
        var color = txt.style.backgroundColor;\nvar color2 = txt.style.backgroundColor2;\nvar isHorizontalGradient = txt.style.backgroundHorizontalGradient;\n
      • Set
        txt.setBackgroundColor(color);\n// txt.setBackgroundColor(color, color2, isHorizontalGradient);\n
        • color, color2 : null, css string, or number.
    • Stroke color
      • Get
        var color = txt.style.backgroundStrokeColor;\nvar lineWidth = txt.style.backgroundStrokeLineWidth;\n
      • Set
        txt.setBackgroundStrokeColor(color, lineWidth);\n
        • color : null, css string, or number.
    • Round rectangle
      • Get
        var radius = txt.style.backgroundCornerRadius;\nvar iteration = txt.style.backgroundCornerIteration;\n
        • radius :
          • 0 : No round corner
          • > 0 : Convex round corner
          • < 0 : Concave round corner
      • Set
        txt.setBackgroundCornerRadius(radius);\n// txt.setBackgroundCornerRadius(radius, iteration);\n
        • iteration :
          • undefined : Round rectangle
          • 0 : Octagon
  • Shadow
    • Get
      var color = txt.style.shadowColor;\nvar offsetX = txt.style.shadowOffsetX;\nvar offsetY = txt.style.shadowOffsetY;\nvar blur = txt.style.shadowBlur;\nvar stroke = txt.style.shadowStroke;\nvar enabled = txt.style.shadowFill;\n
    • Set
      txt.setShadow(x, y, color, blur, shadowStroke, shadowFill);\ntxt.setShadowOffset(x, y);\ntxt.setShadowColor(color);\ntxt.setShadowBlur(blur);\ntxt.setShadowStroke(enabled);\ntxt.setShadowFill(enabled);\n
      • color : null, css string, or number.
"},{"location":"bbcodetext/#align","title":"Align","text":"
  • Horizontal align
    • Get
      var align = txt.style.halign;\n
      • align : 'left', 'center', 'right'
    • Set
      txt.setHAlign(align);    
      or
      txt.setAlign(align);    
      • align : 'left', 'center', 'right'
  • Vertical align
    • Get
      var align = txt.style.valign;\n
      • align : 'top', 'center', 'bottom'
    • Set
      txt.setVAlign(align);    
      • align : 'top', 'center', 'bottom'
"},{"location":"bbcodetext/#image","title":"Image","text":"
  • Uses texture key as image key by default.
  • Add image render information
    txt.addImage(imgKey, {\nkey: textureKey,\nframe: frameName,\nwidth: undefined,\nheight: undefined,\ny: 0,\nleft: 0,\nright: 0,\noriginX: 0,\noriginY: 0,\ntintFill: false,\n});\n
    • imgKey : Image key used in text content, i.e. [img=imgKey].
    • key : Texture key.
    • frame : Frame name.
    • width : Render width, set undefined to use the cut width of frame.
    • height : Render height, set undefined to use the cut height of frame.
    • y : Extra offset y.
    • left : Left padding space.
    • Right : Right padding space.
    • originX : Offset x via frame width * originX
    • originY : Offset y via frame height * originY
    • tintFill :
      • false : Keep original color. Default behavior.
      • true : Change fill-color by color tag. [color=...][img=...].
  • Add some image render informations
    txt.addImage(data);\n
    • data : {imgKey, config}
"},{"location":"bbcodetext/#hit-area-of-words","title":"Hit area of words","text":"

Size of hit-area is word-width x line-height, or image-width x line-height.

"},{"location":"bbcodetext/#hitting-events","title":"Hitting events","text":"
  • Pointer down
    txt.on('areadown', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areadown-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
  • Pointer click : pointer down then up, without pointer out
    txt.on('areaclick', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areaclick-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
  • Pointer up
    txt.on('areaup', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areaup-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
  • Pointer over
    txt.on('areaover', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areaover-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
  • Pointer out
    txt.on('areaout', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areaout-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
"},{"location":"bbcodetext/#draw-hit-areas","title":"Draw hit-areas","text":"
txt.drawAreaBounds(graphics, color);\n
  • graphics : Graphics game object
  • color : Default value is 0xffffff
"},{"location":"bbcodetext/#line-spacing","title":"Line spacing","text":"

This value is added to the height of the font when calculating the overall line height.

  • Get
    var lineSpacing = txt.style.lineSpacing;\n
  • Set
    txt.setLineSpacing(value);\n
"},{"location":"bbcodetext/#padding","title":"Padding","text":"
  • Get
    var left = txt.padding.left;\nvar top = txt.padding.top;\nvar right = txt.padding.right;\nvar bottom = txt.padding.bottom;\n
  • Set
    txt.setPadding(left, top, right, bottom);\n// txt.setPadding(padding); // padding: {left, top, right, bottom}\n
"},{"location":"bbcodetext/#max-lines","title":"Max lines","text":"
  • Get
    var maxLines = txt.style.maxLines;\n
  • Set
    txt.setMaxLines(max);\n
"},{"location":"bbcodetext/#fixed-size","title":"Fixed size","text":"
  • Get
    var width = txt.style.fixedWidth;\nvar height = txt.style.fixedHeight;\n
  • Set
    txt.setFixedSize(width, height);\n
"},{"location":"bbcodetext/#margin-of-text","title":"Margin of text","text":"
var leftMargin = txt.measureTextMargins(testString).left;\n
  • testString : Measure left margin of this text.
"},{"location":"bbcodetext/#shift-start-position-of-text","title":"Shift start position of text","text":"
txt.setXOffset(value);\n
"},{"location":"bbcodetext/#resolution","title":"Resolution","text":"
  • Get
    var resolution = txt.style.resolution;\n
  • Set
    txt.setResolution(resolution);\n
"},{"location":"bbcodetext/#test-string","title":"Test string","text":"

Set the test string to use when measuring the font.

txt.setTestString(text);\n
"},{"location":"bbcodetext/#save-texture","title":"Save texture","text":"
txt.generateTexture(key);\n// txt.generateTexture(key, x, y, width, height);\n
"},{"location":"bbcodetext/#delimiters","title":"Delimiters","text":"
txt.setDelimiters(delimiters);  // '<>', or ['<', '>']\n

or

txt.setDelimiters(delimiterLeft, delimiterRight); // '<', '>'\n

Warning

Don't use () as delimiters, which is preserved for color value.

"},{"location":"bbcodetext/#rtl","title":"RTL","text":"
  • Set rtl in style config when creating this text game object
  • Change rtl during runtime
    txt.setRTL(rtl).setText(newContent);\n
    • Invoke setRTL method before setting new content.
"},{"location":"bbcodetext/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"bbcodetext/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"bbcodetext/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"bitmaptext/","title":"Static bitmap text","text":""},{"location":"bitmaptext/#introduction","title":"Introduction","text":"

Drawing text by texture, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"bitmaptext/#usage","title":"Usage","text":""},{"location":"bitmaptext/#load-bitmap-font","title":"Load bitmap font","text":"
  • Load bitmap font from texture and xml configuration
    scene.load.bitmapFont(key, textureURL, xmlURL);\n
    • Reference: load bitmap font
    • Loaded texture also can be used for Image, Sprite, or Arcade Image, Arcade Sprite
      scene.add.image(x, y, key, char);\n
  • Load retro bitmap font from texture and JSON configuration
    1. Load texture in preload stage
      scene.load.image(key, url);\n
      Reference: load image
    2. Add retro bitmap font
      var config = {\n// image\nimage: '',\noffset: {\nx: 0,\ny: 0\n},\n// characters\nwidth: 32,\nheight: 32,\nchars: '',\ncharsPerRow: 10,\n// spacing\nspacing: {\nx: 0,\ny: 0\n},\nlineSpacing: 0\n}\nscene.cache.bitmapFont.add(key, Phaser.GameObjects.RetroFont.Parse(scene, config));\n
      • Image :
        • image : The key of the image containing the font.
        • offset : If the font set doesn't start at the top left of the given image, specify the X/Y coordinate offset here.
      • Characters :
        • width : The width of each character in the font set.
        • height : The height of each character in the font set.
        • chars : The characters used in the font set, in display order.
          • Default characters set
        • charsPerRow : The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth.
      • Spacing :
        • spacing : If the characters in the font set have horizontal/vertical spacing between them set the required amount here.
        • lineSpacing : The amount of vertical space to add to the line height of the font.
"},{"location":"bitmaptext/#add-bitmap-text-object","title":"Add bitmap text object","text":"
var txt = scene.add.bitmapText(x, y, key, text);\n// var txt = scene.add.bitmapText(x, y, key, text, size, align);\n
  • size : The size of the font
  • align : The alignment of the text in a multi-line BitmapText object.
    • 0 : Left aligned (default)
    • 1 : Middle aligned
    • 2 : Right aligned

Add text from JSON

var txt = scene.make.bitmapText({\nx: 0,\ny: 0,\ntext: 'Text\\nGame Object\\nCreated from config',\nfont: '',\nsize: false,\nalign: 0,\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
"},{"location":"bitmaptext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyText extends Phaser.GameObjects.BitmapText {\nconstructor(scene, x, y, key, text, size, align) {\nsuper(scene, x, y, key, text, size, align);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyText(scene, x, y, key, text);\n
"},{"location":"bitmaptext/#set-text","title":"Set text","text":"
txt.setText('...');\n

or

txt.text = '...';\n
"},{"location":"bitmaptext/#set-align","title":"Set align","text":"
  • Left aligned
    txt.setLeftAlign();\n
  • Middle aligned
    txt.setCenterAlign();\n
  • Right aligned
    txt.setRightAlign();\n

or

txt.align = align;\n
  • align :
    • 0 : Left aligned (default)
    • 1 : Middle aligned
    • 2 : Right aligned
"},{"location":"bitmaptext/#set-letter-spacing","title":"Set letter spacing","text":"
txt.setLetterSpacing(spacing);\n

or

txt.letterSpacing = spacing;\n

Can be a positive value to increase the space, or negative to reduce it.

"},{"location":"bitmaptext/#set-line-spacing","title":"Set line spacing","text":"
txt.setLineSpacing(spacing);\n

or

txt.lineSpacing = spacing;\n

Can be a positive value to increase the space, or negative to reduce it.

"},{"location":"bitmaptext/#set-font-size","title":"Set font size","text":"
txt.setFontSize(size);\n

or

txt.fontSize = size;\n
"},{"location":"bitmaptext/#set-font","title":"Set font","text":"
txt.setFont(key);\n// txt.setFont(key, size, align);\n
"},{"location":"bitmaptext/#tint","title":"Tint","text":"

See Tint.

"},{"location":"bitmaptext/#color-of-characters","title":"Color of characters","text":"
  • By character
    txt.setCharacterTint(start, length, tintFill, color);\n// txt.setCharacterTint(start, length, tintFill, topLeft, topRight, bottomLeft, bottomRight);\n
    • start : Index starting character.
      • < 0 : Counts back from the end of the text.
    • length : Number of characters to tint.
      • -1 : All characters from start
    • tintFill :
      • true : Fill-based tint
      • false : Additive tint
    • color, or topLeft, topRight, bottomLeft, bottomRight : Color integer.
  • By word
    txt.setWordTint(word, count, tintFill, color);\n// txt.setWordTint(word, count, tintFill, topLeft, topRight, bottomLeft, bottomRight);\n
    • word : The word to search for.
      • A string
      • An index of the word in the words array.
    • count : Number of matching words to tint.
      • -1 : All matching words
    • tintFill :
      • true : Fill-based tint
      • false : Additive tint
    • color, or topLeft, topRight, bottomLeft, bottomRight : Color integer.
"},{"location":"bitmaptext/#drop-shadow-effect","title":"Drop shadow effect","text":"
txt.setDropShadow(x, y, color, alpha);\n

or

txt.dropShadowX = x;\ntxt.dropShadowY = y;\ntxt.dropShadowColor = color;\ntxt.dropShadowAlpha = alpha;\n
  • x, y : The horizontal/vertical offset of the drop shadow.
  • color : The color of the drop shadow.
  • alpha : The alpha of the drop shadow.

Note

WebGL only

"},{"location":"bitmaptext/#wrap","title":"Wrap","text":"
  • Wrap
    txt.setMaxWidth(width);\n// txt.setMaxWidth(width, wordWrapCharCode);\n
    • width : Line width in pixels.
    • wordWrapCharCode : The character code to check for when word wrapping. Defaults to 32 (the space character)
  • Disable wrapping
    txt.setMaxWidth(0);\n
"},{"location":"bitmaptext/#get-bounds","title":"Get bounds","text":"
var width = txt.width;\nvar height = txt.height;\n

or

var bounds = txt.getTextBounds(round);\n// bounds = {\n//     local: {\n//         x: 0,\n//         y: 0,\n//         width: 0,\n//         height: 0\n//     },\n//     global: {\n//         x: 0,\n//         y: 0,\n//         width: 0,\n//         height: 0\n//     },\n//     lines: {\n//         shortest: 0,\n//         longest: 0,\n//         lengths: null,\n//         height: 0\n//     },\n//     wrappedText: '',\n//     words: [],\n//     characters: [],\n//     scaleX: 0,\n//     scaleY: 0\n// };\n
  • round : Set true to round the results to the nearest integer.
  • local : The BitmapText based on fontSize and 0x0 coords.
  • global : The BitmapText, taking into account scale and world position.
  • lines : The BitmapText line data.
  • wrappedText : Wrapped content joined with '\\n'.
  • characters : Information of each character.
    {\nchar, code, i, idx, x, y, w, h, t, b, r, line\n}\n
    • char : Character (string).
    • code: Character code (number)
    • i : Index of character
    • x , y : World position of this character
    • w, h : Width/height of this character
    • t, b : The top/bottom of the line this character is on.
    • r : The right-most point of this character, including xAdvance.
    • line : The line number the character appears on.
  • words : Information of each word.
    {\nword, i, x, y, w, h, cr\n\n}\n
    • word : Word string.
    • i : Index of start character
    • x, y : World position of start character
    • w , h : Width/height of word
    • cr : Is last word of current line
  • scaleX, scaleY : Scale of width and height.
"},{"location":"bitmaptext/#get-information-of-character","title":"Get information of character","text":"
var data = txt.getCharacterAt(x, y);\n// var data = txt.getCharacterAt(x, y, camera);\n
  • x, y : World position.
  • camera : The Camera which is being tested against.
  • data : Information of character at world position.
    {\nchar, code, i, x, y, w, h, t, b, r, line\n}\n
    • char : Character (string).
    • code: Character code (number)
    • i : Index of character
    • x , y : World position of this character
    • w, h : Width/height of this character
    • t, b : The top/bottom of the line this character is on.
    • r : The right-most point of this character, including xAdvance.
    • line : The line number the character appears on.
"},{"location":"bitmaptext/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"bitmaptext/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"bitmaptext/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"bitmaptext/#appendix","title":"Appendix","text":""},{"location":"bitmaptext/#default-characters-set-of-retro-font","title":"Default characters set of retro font","text":"
  • Phaser.GameObjects.RetroFont.TEXT_SET1 :
    ' !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET2 :
    ' !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET3 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '\n
  • Phaser.GameObjects.RetroFont.TEXT_SET4 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET5 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() \\'!?-*:0123456789'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET6 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.\\' '\n
  • Phaser.GameObjects.RetroFont.TEXT_SET7 :
    'AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-\\'39'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET8 :
    '0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET9 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,\\'\"?!'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET10 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n
  • Phaser.GameObjects.RetroFont.TEXT_SET11 :
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()\\':;0123456789'\n
"},{"location":"bitmapzone/","title":"Bitmap zone","text":""},{"location":"bitmapzone/#introduction","title":"Introduction","text":"

Particles' emitter zone from canvas bitmap of text/canvas game object.

  • Author: Rex
  • Geometry object
"},{"location":"bitmapzone/#live-demo","title":"Live demo","text":"
  • Particles
"},{"location":"bitmapzone/#usage","title":"Usage","text":"

Sample code

"},{"location":"bitmapzone/#install-plugin","title":"Install plugin","text":""},{"location":"bitmapzone/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbitmapzoneplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbitmapzoneplugin.min.js', true);\n
  • Add bitmap-zone object
    var bitmapZone = scene.plugins.get('rexbitmapzoneplugin').add(gameObject, config);\n
"},{"location":"bitmapzone/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BitmapZonePlugin from 'phaser3-rex-plugins/plugins/bitmapzone-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBitmapZone',\nplugin: BitmapZonePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add bitmap-zone object
    var bitmapZone = scene.plugins.get('rexBitmapZone').add(gameObject, config);\n
"},{"location":"bitmapzone/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import BitmapZone from 'phaser3-rex-plugins/plugins/bitmapzone.js';\n
  • Add bitmap-zone object
    var bitmapZone = new BitmapZone(gameObject, config);\n
"},{"location":"bitmapzone/#create-shape","title":"Create shape","text":"
var bitmapZone = scene.plugins.get('rexBitmapZone').add(gameObject);\n
  • gameObject :
    • Any kind of text object : Text object, bbcode text object, or tag text object.
    • Canvas object
"},{"location":"bitmapzone/#emit-zone","title":"Emit zone","text":"
var particles = scene.add.particles(key,\n[\n// emitter config\n{\n// blendMode:\n// scale:\n// speed:\n// garvityY:\nemitZone: {\ntype: 'random',\nsource: bitmapZone\n}\n}\n]);\n

bitmapZone provides getRandomPoint method.

"},{"location":"bitmapzone/#update-content","title":"Update content","text":"
bitmapZone.setSource(gameObject);\n
"},{"location":"blendmode/","title":"Blend mode","text":""},{"location":"blendmode/#introduction","title":"Introduction","text":"

Constant value of blend modes.

  • Author: Richard Davey
"},{"location":"blendmode/#usage","title":"Usage","text":""},{"location":"blendmode/#webgl-and-canvas","title":"WebGL and Canvas","text":"
  • 'NORMAL', or Phaser.BlendModes.NORMAL, or 0
    • Default setting and draws new shapes on top of the existing canvas content.
  • 'ADD', or Phaser.BlendModes.ADD, or 1
    • Where both shapes overlap the color is determined by adding color values.
  • 'MULTIPLY', or Phaser.BlendModes.MULTIPLY, or 2
    • The pixels are of the top layer are multiplied with the corresponding pixel of the bottom layer. A darker picture is the result.
  • 'SCREEN', or Phaser.BlendModes.SCREEN, or 3
    • The pixels are inverted, multiplied, and inverted again. A lighter picture is the result (opposite of multiply)
  • 'ERASE', or Phaser.BlendModes.ERASE, or 17
    • Alpha erase blend mode. Only works when rendering to a framebuffer, like a Render Texture
"},{"location":"blendmode/#canvas-only","title":"Canvas only","text":"
  • 'OVERLAY', or Phaser.BlendModes.OVERLAY, or 4
    • A combination of multiply and screen. Dark parts on the base layer become darker, and light parts become lighter.
  • 'DARKEN', or Phaser.BlendModes.DARKEN, or 5
    • Retains the darkest pixels of both layers.
  • 'LIGHTEN', or Phaser.BlendModes.LIGHTEN, or 6
    • Retains the lightest pixels of both layers.
  • 'COLOR_DODGE', or Phaser.BlendModes.COLOR_DODGE, or 7
    • Divides the bottom layer by the inverted top layer.
  • 'COLOR_BURN', or Phaser.BlendModes.COLOR_BURN, or 8
    • Divides the inverted bottom layer by the top layer, and then inverts the result.
  • 'HARD_LIGHT', or Phaser.BlendModes.HARD_LIGHT, or 9
    • A combination of multiply and screen like overlay, but with top and bottom layer swapped.
  • 'SOFT_LIGHT', or Phaser.BlendModes.SOFT_LIGHT, or 10
    • A softer version of hard-light. Pure black or white does not result in pure black or white.
  • 'DIFFERENCE', or Phaser.BlendModes.DIFFERENCE, or 11
    • Subtracts the bottom layer from the top layer or the other way round to always get a positive value.
  • 'EXCLUSION', or Phaser.BlendModes.EXCLUSION, or 12
    • Like difference, but with lower contrast.
  • 'HUE', or Phaser.BlendModes.HUE, or 13
    • Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer.
  • 'SATURATION', or Phaser.BlendModes.SATURATION, or 14
    • Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer.
  • 'COLOR', or Phaser.BlendModes.COLOR, or 15
    • Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer.
  • 'LUMINOSITY', or Phaser.BlendModes.LUMINOSITY, or 16
    • Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer.
  • 'SOURCE_IN', or Phaser.BlendModes.SOURCE_IN, or 18
    • The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent.
  • 'SOURCE_OUT', or Phaser.BlendModes.SOURCE_OUT, or 19
    • The new shape is drawn where it doesn't overlap the existing canvas content.
  • 'SOURCE_ATOP', or Phaser.BlendModes.SOURCE_ATOP, or 20
    • The new shape is only drawn where it overlaps the existing canvas content.
  • 'DESTINATION_OVER', or Phaser.BlendModes.DESTINATION_OVER, or 21
    • New shapes are drawn behind the existing canvas content.
  • 'DESTINATION_IN', or Phaser.BlendModes.DESTINATION_IN, or 22
    • The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent.
  • 'DESTINATION_OUT', or Phaser.BlendModes.DESTINATION_OUT, or 23
    • The existing content is kept where it doesn't overlap the new shape.
  • 'DESTINATION_ATOP', or Phaser.BlendModes.DESTINATION_ATOP, or 24
    • The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content.
  • 'LIGHTER', or Phaser.BlendModes.LIGHTER, or 25
    • Where both shapes overlap the color is determined by adding color values.
  • 'COPY', or Phaser.BlendModes.COPY, or 26
    • Only the new shape is shown.
  • 'XOR', or Phaser.BlendModes.XOR, or 27
    • Shapes are made transparent where both overlap and drawn normal everywhere else.

Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these reasons try to be careful about the construction of your Scene and the frequency in which blend modes are used.

"},{"location":"blitter/","title":"Blitter","text":""},{"location":"blitter/#introduction","title":"Introduction","text":"

Display of static images, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"blitter/#usage","title":"Usage","text":""},{"location":"blitter/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"blitter/#add-blitter-container","title":"Add blitter container","text":"

Add blitter container

var blitter = scene.add.blitter(x, y, key);\n

Add blitter container from JSON

var blitter = scene.make.blitter({\nx: 0,\ny: 0,\nkey: '',\n\n// angle: 0,\n// alpha: 1\n// flipX: true,\n// flipY: true,\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
"},{"location":"blitter/#custom-class","title":"Custom class","text":"
  • Define class
    class MyBlitter extends Phaser.GameObjects.Blitter {\nconstructor(scene, x, y, texture, frame) {\nsuper(scene, x, y, texture, frame);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var blitter = new MyBlitter(scene, x, y, key);\n
"},{"location":"blitter/#add-bob-object","title":"Add bob object","text":"
var bob = blitter.create(x, y);\n// var bob = blitter.create(x, y, frame, visible, index);\n
  • frame : The Frame the Bob will use. It must be part of the Texture the parent Blitter object is using.
  • visible : Should the created Bob render or not?
  • index : The position in the Blitters Display List to add the new Bob at. Defaults to the top of the list.
"},{"location":"blitter/#add-mutiple-bob-objects","title":"Add mutiple bob objects","text":"
var bobs = blitter.createMultiple(quantity, frame, visible);\n
  • quantity : The quantity of Bob objects to create.
"},{"location":"blitter/#add-bob-object-from-callback","title":"Add bob object from callback","text":"
var bobs = blitter.createFromCallback(callback, quantity, frame, visible)\n// var callback = function(bob, i){};\n
"},{"location":"blitter/#get-bob-objects","title":"Get bob objects","text":"
var bobs = blitter.children.list;\n
"},{"location":"blitter/#clear-all-bob-objects","title":"Clear all bob objects","text":"
blitter.clear();\n
"},{"location":"blitter/#bob-object","title":"Bob object","text":"

A Bob has a position, alpha value and a frame from a texture that it uses to render with. You can also toggle the flipped and visible state of the Bob.

"},{"location":"blitter/#position","title":"Position","text":"
  • Get
    var x = bob.x;\nvar y = bob.y;\n
  • Set
    bob.setPosition(x, y);\n// bob.x = 0;\n// bob.y = 0;\n
    or
    bob.reset(x, y);\n// bob.reset(x, y, frame);\n
"},{"location":"blitter/#frame","title":"Frame","text":"
  • Get
    var frame = bob.frame;\n
    • frame : Frame object.
  • Set
    bob.setFrame(frame);\n
"},{"location":"blitter/#flip","title":"Flip","text":"
  • Get
    var flipX = bob.flipX;\nvar flipY = bob.flipY;\n
  • Set
    bob.setFlip(boolX, boolY);\n// bob.setFlipX(boolean);\n// bob.setFlipY(boolean);\n// bob.flipX = flipX;\n// bob.flipY = flipY;\n
    or
    bob.resetFlip(); // bob.setFlip(false, false)\n
"},{"location":"blitter/#visible","title":"Visible","text":"
  • Get
    var visible = bob.visible;\n
  • Set
    bob.setVisible(boolean);\n// bob.visible = v;\n
"},{"location":"blitter/#alpha","title":"Alpha","text":"
  • Get
    var alpha = bob.alpha;\n
  • Set
    bob.setAlpha(v);\n// bob.aplha = v;\n
"},{"location":"blitter/#tint","title":"Tint","text":"
  • Get
    var tint = bob.tint;\n
  • Set
    bob.setTint(tint);\n// bob.tint = tint;\n
    • tint : Tint value, between 0 and 0xffffff.
"},{"location":"blitter/#destroy","title":"Destroy","text":"
bob.destroy();\n
"},{"location":"blitter/#data","title":"Data","text":"
var data = bob.data;  // {}\n
"},{"location":"blitter/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"blitter/#create-mask","title":"Create mask","text":"
var mask = bob.createBitmapMask();\n

See mask

"},{"location":"blitter/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"board-bejeweled/","title":"Bejeweled","text":""},{"location":"board-bejeweled/#introduction","title":"Introduction","text":"

Match3-like gameplay template.

  • Author: Rex
  • Template
"},{"location":"board-bejeweled/#live-demos","title":"Live demos","text":"
  • Events
  • Custom input
  • Mask
"},{"location":"board-bejeweled/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-bejeweled/#install-plugin","title":"Install plugin","text":""},{"location":"board-bejeweled/#load-minify-file","title":"Load minify file","text":"
  • Load rexBoard plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\nscene.load.script('rexbejeweled', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbejeweled.min.js');\n
  • Add bejeweled object
    var bejeweled = new rexbejeweled(scene, config);\n
"},{"location":"board-bejeweled/#import-template","title":"Import template","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install rexBoard plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nimport Bejeweled from 'phaser3-rex-plugins/templates/bejeweled/Bejeweled.js';\n\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add bejeweled object
    var bejeweled = new Bejeweled(scene, config);\n
"},{"location":"board-bejeweled/#create-bejeweled-object","title":"Create bejeweled object","text":"
var bejeweled = new Bejeweled(scene, {\n// rexBoard: 'rexBoard',\n\nboard: {\ngrid: {\ngridType: 'quadGrid',\nx: 30,\ny: 30 - 600,\ncellWidth: 60,\ncellHeight: 60,\n},\nwidth: 10,\nheight: 20 // Prepared rows: upper 10 rows\n},\nmatch: {\n// wildcard: undefined\n// dirMask: undefined\n},\nchess: {\n// pick random symbol from array, or a callback to return symbol\nsymbols: [0, 1, 2, 3, 4, 5],\n// symbols: function(board, tileX, tileY, excluded) { return symbol; }\n\n// User-defined chess game object\ncreate: function (board) {\n// Create Game object (Shape, Image, or Sprite)\nvar scene = board.scene;\nvar gameObject = scene.add.sprite(0, 0, textureKey, frame);\n// Initial 'symbol' value\ngameObject.setData('symbol', undefined);\n// Add data changed event of 'symbol` key\ngameObject.data.events.on('changedata_symbol', function (gameObject, value, previousValue) {\n// Change the appearance of game object via new symbol value\ngameObject.setFrame(newFrame);\n});\nreturn gameObject;\n},\n\n// scope for callbacks\nscope: undefined,\n\n// moveTo behavior\nmoveTo: {\nspeed: 400\n},\n// tileZ: 1,\n},\n// mask: false,\n\nselect1Action: undefined,\nselect2Action: undefined,\nswapAction: undefined,\nundoSwapAction: undefined,\neliminatingAction: undefined,\nfallingAction: undefined,\n\n// input: true\n})\n

Configurations

  • rexBoard : Key of 'rexBoard' plugin. Default is 'rexBoard'.
  • Board properties
    • board.width : Board width in tiles.
    • board.height : Board height in tiles.
    • board.grid.x, board.grid.y : World position of tile (0, 0)
    • board.grid.cellWidth, board.grid.cellHeight : The width/height of the cell, in pixels.
  • Chess properties
    • chess.symbols : An array of possible symbols, or a callback to return a symbol. See Generate symbol
    • chess.create, chess.scope : Callback of creating chess object.
    • chess.moveTo.speed : Constant moving speed of chess, in pixel per-second.
  • Custom actions
    • select1Action : Custom select first chess Action
    • select2Action : Custom select second chess Action
    • swapAction : Custon swap action
    • undoSwapAction : Custon undo-swap action
    • eliminatingAction : Custon eliminating action
    • fallingAction : Custon falling action
  • Touch input
    • input : Set true to register default touch input logic.
  • Mask
    • mask :
      • false : No mask. Default behavior.
      • true : Mask invisible upper rows.
        1. Create an internal layer
        2. Mask this internal layer.
"},{"location":"board-bejeweled/#board-height","title":"Board height","text":"

Board is separated into two parts: upper and bottom

  • Bottom : Visible N rows, to swap chess and run matching.
  • Upper : Invisible N rows, chess in these rows will move down, to fill bottom rows.

For example, if amount of visible rows is 10, board.height should set to 20.

"},{"location":"board-bejeweled/#generate-symbol","title":"Generate symbol","text":"

Symbols are declared in property chess.symbols in a symbol array like [0, 1, 2, 3, 4, 5], or a callback to return a symbol. The callback also use chess.scope as the scope.

function(board, tileX, tileY, excluded) {\nreturn symbol\n}\n
  • excluded : undefined or a symbol array. Don't return these symbols.
"},{"location":"board-bejeweled/#create-chess-object","title":"Create chess object","text":"

Return a game object from a callback.

function(board) {\n// Create Game object (Image, Sprite, or Shape)\nvar scene = board.scene;\nvar gameObject = scene.add.sprite(0, 0, textureKey, frame);\n// Initial 'symbol' value\ngameObject.setData('symbol', undefined);\n// Add data changed event of 'symbol` key\ngameObject.data.events.on('changedata_symbol', function (gameObject, value, previousValue) {\n// Change the appearance of game object via new symbol value\ngameObject.setFrame(newFrame);\n});\nreturn gameObject;\n}\n

Each chess has a symbol value stored in 'symbol' key in private data. Add data changed event of 'symbol' key to change the appearance of game object via new symbol value.

"},{"location":"board-bejeweled/#states","title":"States","text":"
graph TD\n\nStart((Start)) --> Select1Start[select1-start]\n\nsubgraph Select 1 states\n  Select1Start --> |Input| Select1[select1]\nend\n\nSelect1 --> select2Start[select2-start]\n\nsubgraph Select 2 states\n  select2Start --> |Input| select2[select2]\nend\n\nselect2Start --> Select1Start\nselect2 --> Swap[swap]\nSwap --> MatchStart[match-start]\n\nsubgraph Match states\n  MatchStart --> Match[match]\n  Match --> Eliminate[eliminate]\n  Match --> MatchEnd[match-end]\n  Eliminate --> Fall[fall]\n  Fall --> Fill[fill]\n  Fill --> Match\nend\n\nMatchEnd --> UndoSwap[undo-swap]\nUndoSwap --> Select1Start\nMatchEnd --> Select1Start
"},{"location":"board-bejeweled/#select-first-chess","title":"Select first chess","text":"

Fire 'select1' event

bejeweled.on('select1', function(board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#custom-select-first-chess-action","title":"Custom Select first chess Action","text":"

Default select action:

function (chess, board, bejeweled) {\n// Do nothing\n}\n
"},{"location":"board-bejeweled/#select-second-chess","title":"Select second chess","text":"

Fire 'select2' event

bejeweled.on('select2', function(board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
    • Selected first chess :
      var chess = bejeweled.getSelectedChess1();\n
"},{"location":"board-bejeweled/#custom-select-second-chess-action","title":"Custom Select second chess Action","text":"

Default select action: The same as Select first chess Action

"},{"location":"board-bejeweled/#swap-selected-chess","title":"Swap selected chess","text":"

Fire 'swap' event

bejeweled.on('swap', function(selectedChess1, selectedChess2, board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#custom-swap-action","title":"Custom Swap Action","text":"

Default swap action:

function (chess1, chess2, board, bejeweled) {\nvar tileXYZ1 = board.chessToTileXYZ(chess1);\nvar tileXYZ2 = board.chessToTileXYZ(chess2);\nvar tileX1 = tileXYZ1.x,\ntileY1 = tileXYZ1.y,\ntileX2 = tileXYZ2.x,\ntileY2 = tileXYZ2.y,\ntileZ = tileXYZ1.z;\n\n// TileZ of chess1 and chess2 are the same, change tileZ of chess2 to a different value\nboard.moveChess(chess2, tileX2, tileY2, `#${tileZ}`, false);\n\n// Move chess1 to tileXYZ2, chess2 to tileXYZ1\nvar moveTo1 = bejeweled.getChessMoveTo(chess1);\nvar moveTo2 = bejeweled.getChessMoveTo(chess2);\nmoveTo1.moveTo(tileX2, tileY2);\nmoveTo2.moveTo(tileX1, tileY1);\n\n// Change tileZ of chess2 back\nboard.moveChess(chess2, tileX1, tileY1, tileZ, false);\n\nif (moveTo1.isRunning) {\nbejeweled.waitEvent(moveTo1, 'complete');\n}\nif (moveTo2.isRunning) {\nbejeweled.waitEvent(moveTo2, 'complete');\n}\n};\n
  • bejeweled.getChessMoveTo(chess) : Get moveTo behavior of a chess.
  • bejeweled.waitEvent(moveTo, 'complete') : Wait 'complete' event of this moveTo behavior.
"},{"location":"board-bejeweled/#match-start","title":"Match start","text":"

Fire 'match-start' event

bejeweled.on('match-start', function(board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#match-lines","title":"Match lines","text":"

Fire 'match' event

bejeweled.on('match', function(lines, board, bejeweled) {\n\n}, scope);\n
  • lines : An array of matched lines, each line is a built-in Set object.
    • Length of each line (lines[i].size) could be 5, 4, or 3.
    • lines[i].entries : An array of chess (Game Object) in a matched line.
    • Get cross chess of two lines via lineA.intersect(lineB).
    • All chess game objects in matched lines will be eliminated in next stage.
      • Add/remove chess game object in a line.
      • Add new line/remove a line in lines array to change the eliminated targets.
  • board : Board object.
    • Get tile position {x,y,z} of a chess game object via
      var tileXYZ = board.chessToTileXYZ(gameObject);\n//var tileXYZ = gameObject.rexChess.tileXYZ;\n
    • Get chess game object of a tile position {x,y,z} via
      var gameObject = board.tileXYZToChess(tileX, tileY, tileZ);\n
    • Get array of neighbor chess of a chess game object via
      var gameObjects = board.getNeighborChess(chess, null);\n
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#eliminating-chess","title":"Eliminating chess","text":"

Fire 'eliminate' event

bejeweled.on('eliminate', function(chessArray, board, bejeweled) {\n\n}, scope);\n
  • chessArray : An array of chess (Game Object) to be eliminated.
  • board : Board object
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#custom-eliminating-action","title":"Custom Eliminating Action","text":"

Default eliminating action:

function (chessArray, board, bejeweled) {\nconst duration = 500; //ms\nfor (var i = 0, cnt = chessArray.length; i < cnt; i++) {\nvar fade = FadeOutDestroy(chessArray[i], duration);\nbejeweled.waitEvent(fade, 'complete');\n}\n}\n
  • bejeweled.waitEvent(fade, 'complete') : Wait 'complete' event of this fade-out-destroy behavior.
"},{"location":"board-bejeweled/#falling-chess","title":"Falling chess","text":"

Fire 'fall' event

bejeweled.on('fall', function(board, bejeweled) {\n\n}, scope);\n
  • board : Board object
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#custom-falling-action","title":"Custom Falling Action","text":"

Default falling action:

function (board, bejeweled) {\nvar tileZ = bejeweled.chessTileZ,\nchess, moveTo;\n\nfor (var tileY = (board.height - 1); tileY >= 0; tileY--) { // bottom to top\nfor (var tileX = 0, cnt = board.width; tileX < cnt; tileX++) { // left to right\nchess = board.tileXYZToChess(tileX, tileY, tileZ);\nif (chess === null) {\ncontinue;\n}\nmoveTo = bejeweled.getChessMoveTo(chess);\ndo {\nmoveTo.moveToward(1);\n} while (moveTo.lastMoveResult)\nif (moveTo.isRunning) {\nbejeweled.waitEvent(moveTo, 'complete');\n}\n}\n}\n}\n
  • bejeweled.getChessMoveTo(chess) : Get moveTo behavior of a chess.
  • bejeweled.waitEvent(moveTo, 'complete') : Wait 'complete' event of this moveTo behavior.
"},{"location":"board-bejeweled/#fill-chess","title":"Fill chess","text":"

Fire 'fill' event

bejeweled.on('fill', function(board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#match-end","title":"Match end","text":"

Fire 'match-end' event

bejeweled.on('match-end', function(board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#undo-swap-selected-chess","title":"Undo-swap selected chess","text":"

Fire 'undo-swap' event

bejeweled.on('undo-swap', function(selectedChess1, selectedChess2, board, bejeweled) {\n\n}, scope);\n
  • board : Board object.
  • bejeweled : This bejeweled object.
"},{"location":"board-bejeweled/#custom-undo-swap-action","title":"Custom Undo-Swap Action","text":"

Default undo-swap action : Equal to Swap action

"},{"location":"board-bejeweled/#start-gameplay","title":"Start gameplay","text":"
bejeweled.start();\n
"},{"location":"board-bejeweled/#input-control","title":"Input control","text":""},{"location":"board-bejeweled/#default-input","title":"Default input","text":"
  1. Enable default input control
    var bejeweled = new Bejeweled(scene, {\n// ...\ninput: true\n});\n
  2. Enable/disable temporarily.
    • Enable
      bejeweled.setInputEnable();\n
    • Disable
      bejeweled.setInputEnable(false);\n
"},{"location":"board-bejeweled/#custom-input","title":"Custom input","text":"
  1. Discard default input control
    var bejeweled = new Bejeweled(scene, {\n// ...\ninput: false\n});\n
  2. Add custom input logic like
    scene.input\n.on('pointerdown', function (pointer) {\nvar chess = bejeweled.worldXYToChess(pointer.worldX, pointer.worldY);\nif (chess) {\nbejeweled.selectChess1(chess);\n}\n}, scene)\n.on('pointermove', function (pointer) {\nif (!pointer.isDown) {\nreturn;\n}\nvar chess = bejeweled.worldXYToChess(pointer.worldX, pointer.worldY);\nif (chess && (chess !== this.bejeweled.getSelectedChess1())) {\nbejeweled.selectChess2(chess);\n}\n}, scene);\n
    • Invoke bejeweled.selectChess1(chess), and bejeweled.selectChess2(chess) under custom logic.

Helper methods

  • Get chess via worldXY position
    var chess = bejeweled.worldXYToChess(worldX, worldY);\n
  • Get chess via tileXY position
    var chess = bejeweled.tileXYToChess(tileX, tileY);\n
  • Get neighbor chess via angle
    var chess2 = bejeweled.getNeighborChessAtAngle(chess1, angle);\n
    • chess1 : Chess object, or tileXY position {x, y}.
    • angle : Angle in radius.
  • Get neighbor chess via direction
    var chess2 = bejeweled.getNeighborChessAtDirection(chess1, direction);\n
    • chess1 : Chess object, or tileXY position {x, y}.
    • direction : Number, or string number.
      • 0 ~ 3 : Quad grid in 4 directions mode.
      • 0 ~ 7 : Quad grid in 8 directions mode.
      • 0 ~ 5 : Hexagon grid.
"},{"location":"board-bejeweled/#data","title":"Data","text":"
  • Get
    var value = bejeweled.getData(key);\nvar values = bejeweled.getData(keys); // keys: an array of keys\nvar value = bejeweled.data.values[key];\n
  • Set
    bejeweled.setData(key, value);\nbejeweled.setData(obj); // obj: {key0:value0, key1:value1, ...}\nbejeweled.data.values[key] = value;\nbejeweled.data.values[key] += inc;\n
  • Enable
    bejeweled.setDataEnabled();\n
  • Events :
    • Set data evant
      bejeweled.on('setdata', function(bejeweled, key, value){ /* ... */ });\n
    • Change data event
      bejeweled.on('changedata', function(bejeweled, key, value, previousValue){ /* ... */ });\n
      bejeweled.on('changedata-' + key, function(bejeweled, value, previousValue){ /* ... */ });\n

See data manager

Note

Ensure data manager is created before binding any data-changed events.

"},{"location":"board-bejeweled/#misc","title":"Misc","text":"
  • Board instance
    var board = bejeweled.getBoard();\n
    • board : Board instance.
  • Match instance
    var match = bejeweled.getMatch();\n
    • match : Match instance.
"},{"location":"board-chessdata/","title":"Chess data","text":""},{"location":"board-chessdata/#introduction","title":"Introduction","text":"

Properties of chess, chess behavior of Board system.

  • Author: Rex
  • Behavior of chess
"},{"location":"board-chessdata/#usage","title":"Usage","text":""},{"location":"board-chessdata/#add-chess-data-object","title":"Add chess data object","text":"

Chess data will be added to game object via gameObject.rexChess once adding this game object to board, or attach any chess behavior.

"},{"location":"board-chessdata/#get-chess-data","title":"Get chess data","text":"
var chessData = gameObject.rexChess;\n
"},{"location":"board-chessdata/#set-tile-z","title":"Set tile Z","text":"
gameObject.rexChess.setTileZ(tileZ);\n

(tileX, tileY) won't be changed.

"},{"location":"board-chessdata/#get-tile-position","title":"Get tile position","text":"
var tileXYZ = gameObject.rexChess.tileXYZ;\n
  • tileXYZ : Tile position {x,y,z}, return null if this chess is not added to any board.
"},{"location":"board-chessdata/#get-board","title":"Get board","text":"
var board = gameObject.rexChess.board;\n
  • board : Board object, or null if this chess is not added to any board.

See also

"},{"location":"board-chessdata/#blocker","title":"Blocker","text":"
  • Set
    gameObject.rexChess.setBlocker();\n
  • Disable
    gameObject.rexChess.setBlocker(false);\n
  • Get
    var blocker = gameObject.rexChess.blocker;\n
"},{"location":"board-fieldofview/","title":"Field of view","text":""},{"location":"board-fieldofview/#introduction","title":"Introduction","text":"

Visible testing, to find field of view, chess behavior of Board system.

  • Author: Rex
  • Behavior of chess
"},{"location":"board-fieldofview/#live-demos","title":"Live demos","text":"
  • Field of view
  • Line of sigh
  • Filter visible chess
  • Pre-test callback
"},{"location":"board-fieldofview/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-fieldofview/#install-plugin","title":"Install plugin","text":""},{"location":"board-fieldofview/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add field-of-view object
    var fieldOfView = scene.rexBoard.add.fieldOfView(chess, config);\n
"},{"location":"board-fieldofview/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add field-of-view object
    var fieldOfView = scene.rexBoard.add.fieldOfView(chess, config);\n
"},{"location":"board-fieldofview/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { FieldOfView } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add field-of-view object
    var fieldOfView = new FieldOfView(chess, config);\n
"},{"location":"board-fieldofview/#create-instance","title":"Create instance","text":"
var fieldOfView = scene.rexBoard.add.fieldOfView(chess, {\n// face: 0,\n// cone: undefined,\n// coneMode: 0,\n// perspective: false,\n\n// ** pre-test **\n// occupiedTest: false,\n// blockerTest: false,\n// preTestCallback: undefined,\n// preTestCallbackScope: undefined,\n\n// ** cost **\n// costCallback: undefined,\n// costCallbackScope: undefined,\n// cost: undefined,   // constant cost\n\n// debug: {\n//     graphics: undefined,\n//     visibleLineColor: 0x00ff00,\n//     invisibleLineColor: 0xff0000,\n//     log: false,\n// }\n})\n
  • face : Face of chess.
    • 0 ~ 3 : Quad grid.
    • 0 ~ 5 : Hexagon grid.
  • cone : View of cone. Tile position or chess which not in view of cone will be invisible.
    • undefined : Ignore this feature
  • coneMode : Unit of cone , in direction or angle.
    • 'direction', or 0 : Cone in directions. For example, visible directions are between (0 - 2/2) to (0 + 2/2) if set
      face : 0,\ncone : 2,\nconeMode: 0\n
    • 'angle', or 1 : Cone in angle. For example, visible angle is between (0 - 120/2) to (0 + 120/2) if set
      face : 0,\ncone : 120,\nconeMode: 1\n
  • perspective :
    • false : Test visible until blocked tiles. Default behavior.
    • true : Test visible until out-of-board. Will test cross any blocked (invisible) tile.
  • Pre-test : Test tiles on visible path.
    • occupiedTest : Set true to test if target tile position is occupied or not.
    • blockerTest : Set true to test blocker property.
    • preTestCallback, preTestCallbackScope : Custom pre-test function, return false to discard cost function.
      function(tileXYArray, visiblePoints, fieldOfView) {\n// return false;\n}\n
      • tileXYArray[0] is current tileXY position of chess.
  • Cost function of each tile on visible path
    • cost : A constant cost for each non-blocked tile
    • costCallback, costCallbackScope : Get cost via callback
      function(curTile, fieldOfView, tileXYArray) {\nreturn cost;\n}\n
      • Cost of blocker : fieldOfView.BLOCKER.
      • curTile : Currest testing tileXY.
      • tileXYArray : A read only tileXY array of sight path.
  • debug :
    • debug.graphics : A graphics object for showing debug messages.
    • debug.visibleLineColor : Color of visible line. Set undefined to not draw any line.
    • debug.invisibleLineColor : Color of invisible line. Set undefined to not draw any line.

Note

Blocker is visible, but tiles behind blocker are invisible.

"},{"location":"board-fieldofview/#set-pre-test-function","title":"Set pre-test function","text":"
fieldOfView.setPreTestFunction(callback, scope);\n
  • callback
    var callback = function(tileXYArray, visiblePoints, fieldOfView) {\nreturn false;\n}\n
    • tileXYArray[0] is current tileXY position of chess.
"},{"location":"board-fieldofview/#set-cost-function","title":"Set cost function","text":"
  • Constant cost for each non-blocked tile
    fieldOfView.setCostFunction(cost);\n
  • Get cost via callback
    fieldOfView.setCostFunction(callback, scope);\n
    • callback
      var callback = function(curTile, fieldOfView, tileXYArray) {\nreturn cost;\n}\n
      • Cost of blocker : fieldOfView.BLOCKER
      • curTile : Currest testing tileXY.
      • tileXYArray : A read only tileXY array of sight path.
"},{"location":"board-fieldofview/#is-tilexychess-visible","title":"Is tileXY/chess visible","text":"
var isVisible = fieldOfView.isInLOS(chess);\n// var isVisible = fieldOfView.isInLOS(chess, visiblePoints);\n// var isVisible = fieldOfView.isInLOS(chess, visiblePoints, originTileXY);\n
  • chess : Chess object or tileXY
  • visiblePoints
    • fieldOfView.INFINITY (undefined) : Infinity visible points. Default value.
  • originTileXY : Put chess at this tileXY position for visible testing temporary.
    • undefined : Use current tileXY position for visible testing.
"},{"location":"board-fieldofview/#get-tilexy-array-in-field-of-view","title":"Get tileXY array in field of view","text":"
var tileXYArray = fieldOfView.findFOV();\n// var tileXYArray = fieldOfView.findFOV(visiblePoints);\n// var tileXYArray = fieldOfView.findFOV(visiblePoints, originTileXY);\n// var out = fieldOfView.findFOV(visiblePoints, out);\n// var out = fieldOfView.findFOV(visiblePoints, originTileXY, out);\n
  • visiblePoints
    • fieldOfView.INFINITY (undefined) : Infinity visible points. Default value.
  • out : Returned tileXY array.
  • originTileXY : Put chess at this tileXY position for visible testing temporary.
    • undefined : Use current tileXY position for visible testing.
"},{"location":"board-fieldofview/#filter-visible-tilexy-array","title":"Filter visible tileXY array","text":"
  • Filter visible tileXY array
    var out = fieldOfView.LOS(chessArray);\n// var out = fieldOfView.LOS(chessArray, originTileXY);\n// var out = fieldOfView.LOS(chessArray, out);\n// var out = fieldOfView.LOS(chessArray, originTileXY, out);\n
    • chessArray : Array of chess object or tileXY
    • out : Array of visible chess object or tileXY
    • originTileXY : Put chess at this tileXY position for visible testing temporary.
      • undefined : Use current tileXY position for visible testing.
  • Filter visible tileXY array with visible points
    var out = fieldOfView.LOS(chessArray, visiblePoints);\n// var out = fieldOfView.LOS(chessArray, visiblePoints, originTileXY);\n// var out = fieldOfView.LOS(chessArray, visiblePoints, out);\n// var out = fieldOfView.LOS(chessArray, visiblePoints, originTileXY, out);\n
    • chessArray : Array of chess object or tileXY
    • out : Array of visible chess object or tileXY
    • originTileXY : Put chess at this tileXY position for visible testing temporary.
      • undefined : Use current tileXY position for visible testing.
"},{"location":"board-fieldofview/#face","title":"Face","text":"

Face direction

  • Get
    var face = fieldOfView.face;\n
  • Set
    fieldOfView.setFace(direction);\n
    or
    fieldOfView.face = direction;\n// fieldOfView.face ++;\n
  • face :
    • 0 ~ 3 : Quad grid.
    • 0 ~ 5 : Hexagon grid.
"},{"location":"board-fieldofview/#debug","title":"Debug","text":"
  • Clear debug graphics
    fieldOfView.clearDebugGraphics();\n
  • Set color of lines
    fieldOfView.setDebugLineColor(visibleLineColor, invisibleLineColor);\n
    • visibleLineColor, invisibleLineColor : Set undefined to not draw any line.
"},{"location":"board-hexagongrid/","title":"Hexagon","text":""},{"location":"board-hexagongrid/#introduction","title":"Introduction","text":"

Hexagon grid object of Board system.

  • Author: Rex
  • Grid object of board
"},{"location":"board-hexagongrid/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-hexagongrid/#create-instance","title":"Create instance","text":"
var grid = scene.rexBoard.add.hexagonGrid({\nx: 0,\ny: 0,\ncellWidth: 0,\ncellHeight: 0,\n// size: undefined,\nstaggeraxis: 1,\nstaggerindex: 1\n});\n

or

// import { HexagonGrid } from 'phaser3-rex-plugins/plugins/board-components.js';\nvar grid = new HexagonGrid(config);\n
  • x, y : World position of origin tile (i.e. tileX = 0, tileY = 0)
  • cellWidth : The width of the cell, in pixels.
  • cellHeight : The height of the cell, in pixels.
  • size : Distance between center to each corner. Get cellWidth and cellHeight from size if this parameter is not undefined.
  • staggeraxis
    • 0, or y
    • 1, or x
  • staggerindex
    • 0, or even
    • 1, or odd
"},{"location":"board-hexagongrid/#world-position-of-tile-0-0","title":"World position of tile (0, 0)","text":"
  • Get
    var worldX = grid.x;\nvar worldY = grid.y;\n
  • Set
    grid.setOriginPosition(worldX, worldY);\n
    or
    grid.x = worldX;\ngrid.y = worldY;\n
"},{"location":"board-hexagongrid/#cell-size","title":"Cell size","text":"
  • Get
    var width = grid.width;\nvar height = grid.height;\n
  • Set
    grid.setCellSize(width, height);\n
    or
    grid.width = width;\ngrid.height = height;\n
    or
    grid.setCellRadius(size);\n
    • size : Distance between center to each corner.
"},{"location":"board-hexagongrid/#grid-type","title":"Grid type","text":"
  • Get
    var staggeraxis = grid.staggeraxis;\nvar staggerindex = grid.staggerindex;\n
  • Set
    grid.setType(staggeraxis, staggerindex);\n
    • staggeraxis
      • 0, or y
      • 1, or x
    • staggerindex
      • 0, or even
      • 1, or odd
"},{"location":"board-hexagongrid/#get-world-position","title":"Get world position","text":"
var worldXY = grid.getWorldXY(tileX, tileY);  // worldXY: {x, y}\n// var out = grid.getWorldXY(tileX, tileY, out);\n
"},{"location":"board-hexagongrid/#get-tile-position","title":"Get tile position","text":"
var tileXY = grid.getTileXY(worldX, worldY);  // tileXY: {x, y}\n// var out = grid.getTileXY(worldX, worldY, out);\n
"},{"location":"board-hexagongrid/#directions","title":"Directions","text":"
  • staggeraxis = 0/y
    • 0 : Down-right
    • 1 : Down
    • 2 : Down-left
    • 3 : Up-left
    • 4 : Up
    • 5 : Up-right
  • staggeraxis = 1/x
    • 0 : Right
    • 1 : Down-right
    • 2 : Down-left
    • 3 : Left
    • 4 : Up-left
    • 5 : Up-right
"},{"location":"board-hexagonmap/","title":"Hexagon map","text":""},{"location":"board-hexagonmap/#introduction","title":"Introduction","text":"

Create tile positions in hexagon/triangle/parallelogram geometry in hexagon grid.

  • Author: Rex
  • Help method of board
"},{"location":"board-hexagonmap/#live-demos","title":"Live demos","text":"
  • Hexagon
"},{"location":"board-hexagonmap/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-hexagonmap/#install-plugin","title":"Install plugin","text":""},{"location":"board-hexagonmap/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Create tile positions
    var tileXYArray = scene.rexBoard.add.hexagonMap.hexagon(board, radius);\nvar tileXYArray = scene.rexBoard.add.hexagonMap.parallelogram(board, type, width, height);\nvar tileXYArray = scene.rexBoard.add.hexagonMap.triangle(board, type, height);\n
"},{"location":"board-hexagonmap/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create tile positions
    var tileXYArray = scene.rexBoard.add.hexagonMap.hexagon(board, radius);\nvar tileXYArray = scene.rexBoard.add.hexagonMap.parallelogram(board, type, width, height);\nvar tileXYArray = scene.rexBoard.add.hexagonMap.triangle(board, type, height);\n
"},{"location":"board-hexagonmap/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { HexagonMap } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Create tile positions
    var tileXYArray = HexagonMap.hexagon(board, radius);\nvar tileXYArray = HexagonMap.parallelogram(board, type, width, height);\nvar tileXYArray = HexagonMap.triangle(board, type, height);\n
"},{"location":"board-hexagonmap/#create-tile-positions","title":"Create tile positions","text":""},{"location":"board-hexagonmap/#hexagon","title":"Hexagon","text":"
var tileXYArray = scene.rexBoard.hexagonMap.hexagon(board, radius);\n// var out = scene.rexBoard.hexagonMap.hexagon(board, radius, out);\n
  • tileXYArray : An array of tile position {x, y}.
  • board : Board object.
  • radius : Radius in tile count.
staggeraxis y x"},{"location":"board-hexagonmap/#parallelogram","title":"Parallelogram","text":"
var tileXYArray = scene.rexBoard.hexagonMap.parallelogram(board, type, width, height);\n// var out = scene.rexBoard.hexagonMap.parallelogram(board, type, width, height, out);\n
  • tileXYArray : An array of tile position {x, y}.
  • board : Board object.
  • width, height : Size of parallelogram
type\\staggeraxis y x 0 1 2"},{"location":"board-hexagonmap/#triangle","title":"Triangle","text":"
var tileXYArray = scene.rexBoard.hexagonMap.triangle(board, type, height);\n// var out = scene.rexBoard.hexagonMap.triangle(board, type, height, out);\n
  • tileXYArray : An array of tile position {x, y}.
  • board : Board object.
  • height : Size of Triangle
type\\staggeraxis y x 0 1"},{"location":"board-hexagonmap/#retrieve-tile-positions","title":"Retrieve tile positions","text":"
  1. Offset all of tile positions to (0, 0), and set board size to fit these tile positions.
    var tileXYArray = board.fit(tileXYArray);\n
  2. Retrieve tile positions
    var tileXY;\nfor(var i = 0, cnt = tileXYArray.length; i < cnt; i++) {\ntileXY = tileXYArray[i];\n// ...\n}\n
"},{"location":"board-image/","title":"Image","text":""},{"location":"board-image/#introduction","title":"Introduction","text":"

Image chess object.

  • Author: Rex
  • Chess Game object of Board system
"},{"location":"board-image/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-image/#install-plugin","title":"Install plugin","text":""},{"location":"board-image/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add chess object
    var chess = scene.rexBoard.add.image(board, tileX, tileY, tileZ, key, frame);\n
"},{"location":"board-image/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add chess object
    var chess = scene.rexBoard.add.image(board, tileX, tileY, tileZ, key, frame);\n
"},{"location":"board-image/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Image } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add chess object
    var chess = new Image(board, tileX, tileY, tileZ, key, frame);\nscene.add.existing(chess);\n
"},{"location":"board-image/#add-chess-object","title":"Add chess object","text":"
  • Create chess object and add to board
    var chess = scene.rexBoard.add.image(board, tileX, tileY, tileZ, key, frame);\n
    • board : Board object
    • tileX, tileY, tileZ : Tile position
    • key, frame : Frame of this image chess object
  • Create chess object but not add to board
    var chess = scene.rexBoard.add.image(board, x, y, undefined, key, frame, false);\n
    • board : Board object
    • x, y : World position
    • key, frame : Frame of this image chess object
"},{"location":"board-image/#other-properties","title":"Other properties","text":"

See Image game object, game object

"},{"location":"board-match/","title":"Match","text":""},{"location":"board-match/#introduction","title":"Introduction","text":"

Get matched chess in lines, or neighbors grouping.

  • Author: Rex
  • Application of Board system
"},{"location":"board-match/#live-demos","title":"Live demos","text":"
  • Match line
  • Match neighbors
"},{"location":"board-match/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-match/#install-plugin","title":"Install plugin","text":""},{"location":"board-match/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add match object
    var match = scene.rexBoard.add.match(config);\n
"},{"location":"board-match/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add match object
    var match = scene.rexBoard.add.match(config);\n
"},{"location":"board-match/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Match } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add match object
    var match = new Match(config);\n
"},{"location":"board-match/#add-match-object","title":"Add match object","text":"
var match = scene.rexBoard.add.match({\nboard: board,\n// wildcard: undefined\n// dirMask: undefined\n});\n
  • board : A board object
  • wildcard : A string or a number
  • dirMask : Enable/Disable matching at directions, all directions are enbale by default.
    • Quad grid, 4 directions
      {\n0: true,  // set false to disable left/right matching\n1: true   // set false to disable up/down matching\n}\n
    • Quad grid, 8 directions
      {\n0: true,  // set false to disable left/right matching\n1: true,  // set false to disable up/down matching\n4: true,  // set false to disable left-down/right-up matching\n5: true   // set false to disable right-down/left-up matching\n}\n
    • Hexagon grid
      {\n0: true,\n1: true,\n3: true\n}\n
"},{"location":"board-match/#custom-class","title":"Custom class","text":"
  • Define class
    class MyMatch extends RexPlugins.Board.Match {\nconstructor(config) {\nsuper(config);\n// ...\n}\n// ...\n}\n
  • Create instance
    var match = new MyMatch(config);\n
"},{"location":"board-match/#set-board","title":"Set board","text":"

Board object could be assigned later.

match.setBoard(board);\n
"},{"location":"board-match/#update-symbols","title":"Update symbols","text":"

Each tile position (tileX, tileY) has a symbol.

"},{"location":"board-match/#update-all-symbols-in-board","title":"Update all symbols in board","text":"
match.refreshSymbols(function(tileXY, board) {\n// var chess = board.tileXYZToChess(tileXY.x, tileXY.y, 0);\n// if (chess == null) { return null; }\nreturn symbol;\n}, scope);\n
  • tileXY : Tile position {x, y}
  • board : Board object
  • symbol : A string or a number
    • null : No symbol
"},{"location":"board-match/#updata-a-symbol","title":"Updata a symbol","text":"
match.setSymbol(tileX, tileY, symbol);\n
"},{"location":"board-match/#get-symbol","title":"Get symbol","text":"
var symbol = match.getSymbol(tileX, tileY);\n
"},{"location":"board-match/#for-each-symbol-cahce","title":"For each symbol cahce","text":"
match.forEach(function(tileXY, symbol, board) {\n// return true; // Break for each loop\n}, scope)\n
  • tileXY : Tile position {x, y}
  • symbol : A string or a number
    • null : No symbol
  • board : Board object
"},{"location":"board-match/#wildcard-symbol","title":"Wildcard symbol","text":"
  • Set
    match.setWildcard(symbol);\n
    or
    match.wildcard = symbol;\n
  • Get
    var wildcard = match.wildcard;\n
"},{"location":"board-match/#directions-mask","title":"Directions mask","text":"

Enable/Disable matching at directions, all directions are enbale by default.

match.setDirMask(dir, value);\n
  • dir :
    • Quad grid, 4 directions : 0, 1
    • Quad grid, 8 directions : 0, 1, 4, 5
    • Hexagon grid : 0, 1, 2
  • value : true or false
"},{"location":"board-match/#line-grouping","title":"Line grouping","text":""},{"location":"board-match/#match-n","title":"Match-N","text":"
match.match(n, function (result, board) {\n// var chess = board.tileXYArrayToChess(result.tileXY, 0);\n// GroupCall(chess, function (chess) { chess.setScale(0.8); });\n\n// return true; // Break for each loop\n}, scope);\n
  • n : A number, to get matched chess with n equal symbols
  • result : A group of chess
    {\ntileXY: [],\ndirection: 0\npattern: symbol\n}\n
    • tileXY : An array of tile positions {x, y}
    • direction : Direction of this chess group
      • 0, 1, for quad grid with 4 directions
      • 0, 1, 4, 5, for quad grid with 8 directions
      • 0, 1, 2, for hexagon grid
    • pattern : Matched symbol
  • board : Board object
"},{"location":"board-match/#any-match-n","title":"Any match-N","text":"
var hasAnyMatchN = match.anyMatch(n);\n
"},{"location":"board-match/#match-pattern","title":"Match pattern","text":"
match.match(pattern, function (result, board) {\n// var chess = board.tileXYArrayToChess(result.tileXY, 0);\n// GroupCall(chess, function (chess) { chess.setScale(0.8); });\n}, scope);\n
  • pattern : A list of symbols
"},{"location":"board-match/#any-match-pattern","title":"Any match pattern","text":"
var hasAnyMatchN = match.anyMatch(pattern);\n
"},{"location":"board-match/#neighbors-grouping","title":"Neighbors grouping","text":"
  • Group by neighbors with the same symbol
    tileXYArray = match.group(startTileX, startTileY);\n// out = match.group(startTileX, startTileY, out);\n
    • startTileX, startTileY : Tile position of grouping, to group neighbors with the same symbol. Can't start from null, undefined or wildcard symbol.
"},{"location":"board-miniboard/","title":"Mini board","text":""},{"location":"board-miniboard/#introduction","title":"Introduction","text":"

Chess Container, to rotate/mirror/drag chess together.

  • Author: Rex
  • Container Game object of chess group
"},{"location":"board-miniboard/#live-demos","title":"Live demos","text":"
  • Group 4
  • Drag & drop, mirror, rotate
"},{"location":"board-miniboard/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-miniboard/#install-plugin","title":"Install plugin","text":""},{"location":"board-miniboard/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add container
    var miniBoard = scene.rexBoard.add.miniBoard(x, y, config);\n
"},{"location":"board-miniboard/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add container
    var miniBoard = scene.rexBoard.add.miniBoard(x, y, config);\n
"},{"location":"board-miniboard/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { MiniBoard } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add match object
    var miniBoard = new MiniBoard(scene, x, y, config);\n
"},{"location":"board-miniboard/#add-container","title":"Add Container","text":"
var miniBoard = scene.rexBoard.add.miniBoard(x, y, {\ngrid: grid,\ndraggable: undefined,\n});\n
  • grid : Create board object first, then get grid object via board.grid.
    • gridType :
      • 'quadGrid' : Quad grid
      • 'hexagonGrid' : hexagon grid
  • draggable : Set true to enable dragging events
"},{"location":"board-miniboard/#add-chess","title":"Add chess","text":"
miniBoard.addChess(gameObject, tileX, tileY, tileZ);\n
  • chess : A game object.
  • tileX , tileY , tileZ : Tile position.
    • tileX , tileY : Number.
    • tileZ : Number or string.

Chess and tile position

  • Any chess has a (tileX, tileY, tileZ) index
  • Any (tileX, tileY, tileZ) index contains only 1 chess.
  • (tileX, tileY) could have more then 1 chess with different tileZ index.
  • tileZ is not equal to depth.

These world properties of chess will be changed with container.

  • Position/Angle/Scale
  • Visible
  • Alpha
  • Scroll factor
  • Mask
"},{"location":"board-miniboard/#remove-chess","title":"Remove chess","text":"
  • Remove chess object from board
    miniBoard.removeChess(chess, null, null, null, destroy);\n
    • chess : A game object
    • destroy : Set true to desrtoy chess object.
  • Remove chess at (tileX, tileY, tileZ) from board
    miniBoard.removeChess(null, tileX, tileY, tileZ, destroy);\n
    • tileX, tileY, tileZ : Tile position
    • destroy : Set true to desrtoy chess object.
  • Remove all chess
    miniBoard.removeAllChess(destroy);\n
    • destroy : Set true to desrtoy chess object.
"},{"location":"board-miniboard/#set-origin","title":"Set origin","text":"
  • Set origin tileXY by offset tileXY of all chess.
    miniBoard.setOrigin(origin);\n// miniBoard.setOrigin(originX, originY);\n
    • originX, originY: 0~1.
      • 0 : Left/top.
      • 0.5 : Center.
      • 1 : Right/bottom.
  • Set origin tileXY to center by offset tileXY of all chess.
    miniBoard.setOrigin();\n// miniBoard.setOrigin('center');\n
  • Set origin tileXY to top-left.
    miniBoard.setOrigin('top-left');\n
"},{"location":"board-miniboard/#main-board","title":"Main board","text":"

Put chess to a main-board (Board object) with the same tile position in mini-board, or pull chess out from main-board.

"},{"location":"board-miniboard/#put-on-main-board","title":"Put on main-board","text":"
miniBoard.putOnMainBoard(mainBoard, tileX, tileY);\n// miniBoard.putOnMainBoard(mainBoard, tileX, tileY, align);\n
  • mainBoard : Board object.
  • tileX, tileY : Tile position to put on.
  • align : Set true to align world position of each chess Game object to grid of main-board. Default is true.

or

miniBoard.putOnMainBoard(mainBoard);\n

To put this mini-board to nearest grid of main-board.

"},{"location":"board-miniboard/#pull-out-from-main-board","title":"Pull out from main-board","text":"
miniBoard.pullOutFromMainBoard();\n

Remove all chess from main-board.

"},{"location":"board-miniboard/#put-back-to-previous-main-board","title":"Put back to previous main-board","text":"
miniBoard.putBack();\n

Previous main-board and tile position will be remembered for putting back.

"},{"location":"board-miniboard/#is-overlapping-to-main-board","title":"Is overlapping to main-board","text":"

Return true if any chess is overlapping to main-board.

miniBoard.isOverlapping(mainBoard);\n

or

miniBoard.isOverlapping(mainBoard, tileZ);\n
"},{"location":"board-miniboard/#align-world-position-to-grid-of-main-board","title":"Align world position to grid of main-board","text":"
miniBoard.alignToMainBoard(mainBoard, tileX, tileY);\n
  • mainBoard : Board object
  • tileX, tileY : Tile position on main-board

or

miniBoard.alignToMainBoard(mainBoard);\n

to align this mini-board to nearest grid of main-board.

"},{"location":"board-miniboard/#get-current-main-board","title":"Get current main-board","text":"
var board = miniBoard.mainBoard;\n
  • board : Board object

Return null if this mini-board is not at any main-board.

"},{"location":"board-miniboard/#rotate","title":"Rotate","text":""},{"location":"board-miniboard/#can-rotate","title":"Can rotate","text":"
miniBoard.canRotate(n);\n
  • n : Rotate to direction current direction + n

or

miniBoard.canRotateTo(direction);\n
  • direction : Rotate to direction
    • 0 ~ 3 : Quad grid.
    • 0 ~ 5 : Hexagon grid.

Always return true if this mini-board is not on a main-board.

"},{"location":"board-miniboard/#rotate_1","title":"Rotate","text":"
miniBoard.rotate(n);\n
  • n : Rotate direction to current direction + n

or

miniBoard.rotateTo(direction);\n
  • direction : Rotate to direction
    • 0 ~ 3 : Quad grid.
    • 0 ~ 5 : Hexagon grid.

Return true if this rotating request is accepted.

var isSuccess = miniBoard.lastTransferResult;\n
"},{"location":"board-miniboard/#mirror","title":"Mirror","text":""},{"location":"board-miniboard/#can-mirror","title":"Can mirror","text":"
miniBoard.canMirror(mode);\n
  • mode :
    • 0, or 'x' : Set tileX to -tileX
    • 1, or 'y' : Set tileY to -tileY
    • 3, or 'x&y' : Set tileX to -tileX, and tileY to -tileY

Always return true if this mini-board is not on a main-board.

"},{"location":"board-miniboard/#mirror_1","title":"Mirror","text":"
miniBoard.mirror(mode);\n
  • mode :
    • 0, or 'x' : Set tileX to -tileX
    • 1, or 'y' : Set tileY to -tileY
    • 3, or 'x&y' : Set tileX to -tileX, and tileY to -tileY

Return true if this mirroring request is accepted.

var isSuccess = miniBoard.lastTransferResult;\n
"},{"location":"board-miniboard/#touch-events","title":"Touch events","text":""},{"location":"board-miniboard/#set-interactive","title":"Set interactive","text":"
  • Enable
    miniBoard.setInteractive();\n
  • Disable
    miniBoard.setInteractive(false);\n
"},{"location":"board-miniboard/#set-drag-able","title":"Set drag-able","text":"
  • Enable
    miniBoard.setDragEnable();\n
  • Disable
    miniBoard.setDragEnable(false);\n
"},{"location":"board-miniboard/#touch-event","title":"Touch event","text":""},{"location":"board-miniboard/#pointer-down","title":"Pointer down","text":"
  • Pointer down at any chess
    miniBoard.on('pointerdown', function(pointer, miniBoard) {\n})\n
  • Pointer down at a chess
    miniBoard.on('gameobjectdown', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('miniboard.pointerdown', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board-miniboard/#pointer-up","title":"Pointer up","text":"
  • Pointer up
    miniBoard.on('pointerup', function(pointer, miniBoard) {\n})\n
  • Pointer up at a chess
    miniBoard.on('gameobjectup', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('miniboard.pointerup', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board-miniboard/#pointer-move","title":"Pointer move","text":"
  • Pointer move
    miniBoard.on('pointermove', function(pointer, miniBoard) {\n})\n
  • Pointer move to another chess
    miniBoard.on('gameobjectmove', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('miniboard.pointermove', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board-miniboard/#drag-events","title":"Drag events","text":"
  • Drag-start
    miniBoard.on('dragstart', function(pointer, dragX, dragY){\n/*\n    miniBoard.pullOutFromMainBoard();\n    */\n}, scope);\n
    Pull out from main-board for dragging.
  • Dragging
    miniBoard.on('drag', function(pointer, dragX, dragY){\n/*\n    miniBoard.setPosition(dragX, dragY);\n    if (miniBoard.isOverlapping(mainBoard)) {\n        miniBoard.alignToMainBoard(mainBoard);\n    }\n    */\n}, scope);\n
    Set world position of mini-board via (dragX, dragY), align to nearest grid of main-board if overlapping with that main-board.
  • Drag-end
    miniBoard.on('dragend', function(pointer, dragX, dragY){\n/*\n    miniBoard.putOnMainBoard(mainBoard);\n    if (miniBoard.mainBoard) {\n    }\n    */\n}, scope);\n
    Put chess on main-board at nearest grid.
"},{"location":"board-monopoly/","title":"Monopoly","text":""},{"location":"board-monopoly/#introduction","title":"Introduction","text":"

Move through path tiles, used in monopoly-like application, chess behavior of Board system.

  • Author: Rex
  • Behavior of chess
"},{"location":"board-monopoly/#live-demos","title":"Live demos","text":"
  • Monopoly
"},{"location":"board-monopoly/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-monopoly/#install-plugin","title":"Install plugin","text":""},{"location":"board-monopoly/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add monopoly behavior
    var monopoly = scene.rexBoard.add.monopoly(chess, config);\n
"},{"location":"board-monopoly/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add monopoly behavior
    var monopoly = scene.rexBoard.add.monopoly(chess, config);\n
"},{"location":"board-monopoly/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Monopoly } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add monopoly behavior
    var board = new Monopoly(chess, config);\n
"},{"location":"board-monopoly/#create-instance","title":"Create instance","text":"
var monopoly = scene.rexBoard.add.monopoly(chess, {\nface: 0,\n\n// ** cost **\n// pathTileZ: 0,\n// cost: 1,   // constant cost\n// costCallback: undefined,\n// costCallbackScope: undefined\n})\n
  • face : Moving direction.
    • 0 ~ 3 : Quad grid in 4 directions mode.
    • 0 ~ 7 : Quad grid in 8 directions mode.
    • 0 ~ 5 : Hexagon grid.
  • Cost function
    • pathTileZ : TileZ of path tiles.
    • cost : A constant cost for each non-blocked tile
    • costCallback, costCallbackScope : Get cost via callback
      function(curTileXY, preTileXY, monopoly) {\nreturn cost;\n}\n
"},{"location":"board-monopoly/#cost-function","title":"Cost function","text":"
var callback = function(curTileXY, preTileXY, monopoly) {\nreturn cost;\n}\n
  • cost : Number cost.
  • curTileXY, preTileXY : TileXY position {x, y}. Cost of moving from preTileXY to curTileXY.
  • monopoly : Path finder object.
    • monopoly.board : Board object
    • monopoly.gameObject : Chess game object.
    • monopoly.STOP, or -1 : Cost of stop. Return this value means chess will stop at curTileXY.
    • monopoly.BLOCKER, or null : Cost of blocker. Return this value means that chess can not move to curTileXY.
"},{"location":"board-monopoly/#set-cost-function","title":"Set cost function","text":"
  • Constant cost for each non-blocked tile
    monopoly.setCostFunction(cost);\n
  • Get cost via callback
    monopoly.setCostFunction(callback, scope);\n
"},{"location":"board-monopoly/#set-face-direction","title":"Set face direction","text":"
monopoly.setFace(direction);\n
  • direction :
    • 0 ~ 3 : Quad grid in 4 directions mode.
    • 0 ~ 7 : Quad grid in 8 directions mode.
    • 0 ~ 5 : Hexagon grid.

Moving direction

Get path toward this face direction.

"},{"location":"board-monopoly/#get-path","title":"Get path","text":"
var tileXYArray = monopoly.getPath(movingPoints);\n// var out = monopoly.getPath(movingPoints, out);\n
  • tileXYArray : Moving path in an array of tile positions {x,y}
    • Uses moveTo behavior to move chess along path.
"},{"location":"board-moveto/","title":"Move to","text":""},{"location":"board-moveto/#introduction","title":"Introduction","text":"

Move chess towards target position with a steady speed, chess behavior of Board system.

  • Author: Rex
  • Behavior of chess
"},{"location":"board-moveto/#live-demos","title":"Live demos","text":"
  • Push
  • Follow chess
"},{"location":"board-moveto/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-moveto/#install-plugin","title":"Install plugin","text":""},{"location":"board-moveto/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add move-to behavior
    var moveTo = scene.rexBoard.add.moveTo(chess, config);\n
"},{"location":"board-moveto/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add move-to behavior
    var moveTo = scene.rexBoard.add.moveTo(chess, config);\n
"},{"location":"board-moveto/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { MoveTo } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add move-to behavior
    var moveTo = new MoveTo(chess, config);\n
"},{"location":"board-moveto/#create-instance","title":"Create instance","text":"
var moveTo = scene.rexBoard.add.moveTo(chess, {\n// speed: 400,\n\n// rotateToTarget: false,\n\n// occupiedTest: false,\n// blockerTest: false,\n// moveableTest: undefined,\n// moveableTestScope: undefined,\n\n// sneak: false,\n})\n
  • speed : moving speed, pixels in second.
  • rotateToTarget : Set true to change angle towards path.
  • occupiedTest : Set true to test if target tile position is occupied or not, in moveable testing.
  • blockerTest : Set true to test blocker property in moveable testing.
  • moveableTest, moveableTestScope : Custom moveable test callback
    function(fromTileXYZ, toTileXYZ, direction, board) {\nreturn true;\n}\n
    • fromTileXYZ, toTileXYZ : Move chess from tileXYZ {x, y, z}, to tileXYZ {x, y, z}
    • direction :
      • 0 ~ 3 : Quad grid in 4 directions mode.
      • 0 ~ 7 : Quad grid in 8 directions mode.
      • 0 ~ 5 : Hexagon grid.
    • board : Board object.
  • sneak : Set true to allow changing tileZ when target tile position is occupied. Changing back when target tile position is not occupied.
    • occupiedTest will be ignored when sneak is true.
"},{"location":"board-moveto/#move-to-destination-tile","title":"Move to destination tile","text":"
moveTo.moveTo(tileX, tileY);\n// moveTo.moveTo(tileXY);\n
  • tileXY : Tile position {x,y}
"},{"location":"board-moveto/#move-to-neighbor-tile","title":"Move to neighbor tile","text":"
moveTo.moveToward(direction);\n
  • direction :
    • 0 ~ 3 : Quad grid in 4 directions mode.
    • 0 ~ 7 : Quad grid in 8 directions mode.
    • 0 ~ 5 : Hexagon grid.
"},{"location":"board-moveto/#move-to-random-neighbor-tile","title":"Move to random neighbor tile","text":"
moveTo.moveToRandomNeighbor();\n
"},{"location":"board-moveto/#move-away-or-move-closer","title":"Move away or move closer","text":"
  • Move away from a tile position
    moveTo.moveAway(tileX, tileY);\n
    or
    moveTo.moveAway(tileXY);\n
    • tileXY : Tile position {x,y}
  • Move closer to a tile position
    moveTo.moveCloser(tileX, tileY);\n
    or
    moveTo.moveCloser(tileXY);\n
    • tileXY : Tile position {x,y}
"},{"location":"board-moveto/#can-move-to-tile","title":"Can move to tile","text":"
var canMoveTo = moveTo.canMoveTo(tileX, tileY);\n

Return true if chess can move to (tileX, tileY)

"},{"location":"board-moveto/#last-move-result","title":"Last move result","text":"
var lastMoveResult = moveTo.lastMoveResult;\n

Return true if chess is moved by moveTo.moveTo(), moveTo.moveToward(), or moveTo.moveToRandomNeighbor()

"},{"location":"board-moveto/#destination","title":"Destination","text":"
var destinationTileX = moveTo.destinationTileX;\nvar destinationTileY = moveTo.destinationTileY;\nvar destinationDirection = moveTo.destinationDirection;\n
"},{"location":"board-moveto/#pause-resume-stop-moving","title":"Pause, Resume, stop moving","text":"
moveTo.pause();\nmoveTo.resume();\nmoveTo.stop();\n
"},{"location":"board-moveto/#enable","title":"Enable","text":"
  • Enable/resume (default)
    moveTo.setEnable();\n
    or
    moveTo.enable = true;\n
  • Disable/pause
    moveTo.setEnable(false);\n
    or
    moveTo.enable = false;\n
"},{"location":"board-moveto/#set-speed","title":"Set speed","text":"
moveTo.setSpeed(speed);\n// moveTo.speed = speed;\n
"},{"location":"board-moveto/#set-rotate-to-target","title":"Set rotate-to-target","text":"
moveTo.setRotateToTarget(rotateToTarget);\n
  • rotateToTarget : Set true to change angle towards target
"},{"location":"board-moveto/#events","title":"Events","text":"
  • Try to move on an occupied tile position
    moveTo.on('occupy', function(occupiedChess, gameObject, moveTo){\n// Move away occupiedChess\n});\n
  • On reached target
    moveTo.on('complete', function(gameObject, moveTo){});\n// moveTo.once('complete', function(gameObject, moveTo){});\n
"},{"location":"board-moveto/#status","title":"Status","text":"
  • Is moving
    var isRunning = moveTo.isRunning;\n
"},{"location":"board-overview/","title":"Overview","text":""},{"location":"board-overview/#install-plugin","title":"Install plugin","text":""},{"location":"board-overview/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add board object
    var board = scene.rexBoard.add.board(config);\n
"},{"location":"board-overview/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add board object
    var board = scene.rexBoard.add.board(config);\n
"},{"location":"board-overview/#using-typescript-declaration-file","title":"Using typescript declaration file","text":"
import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\n\nclass Game extends Phaser.Scene {\nrexBoard: BoardPlugin;  // Declare scene property 'rexBoard' as BoardPlugin type\n\ncreate() {\nvar board = this.rexBoard.add.board({\n// ...\n})\n}\n}\n\nvar game = new Phaser.Game({\nscene: Game,\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n});\n
  • 'phaser3-rex-plugins/plugins/board-plugin' : Factories of board components.
  • 'phaser3-rex-plugins/plugins/board-components' : Class of board components.
    import { Board } from 'phaser3-rex-plugins/plugins/board-components';\n

See this example

"},{"location":"board-overview/#list-of-board-plugins","title":"List of board plugins","text":""},{"location":"board-overview/#board","title":"Board","text":"
  • Board
  • Grids
    • Quad grid
    • Hexagon grid
  • Chess
"},{"location":"board-overview/#chess-game-object","title":"Chess game object","text":"
  • Shape game object
  • Image game object
  • Sprite game object
  • Tile texture
"},{"location":"board-overview/#behaviors","title":"Behaviors","text":"
  • Move to
"},{"location":"board-overview/#applications","title":"Applications","text":"
  • Path finder
  • Monopoly
  • Field of view
  • Match
  • Hexagon map
"},{"location":"board-overview/#mini-board","title":"Mini-board","text":"
  • Mini-board
"},{"location":"board-overview/#templates","title":"Templates","text":"
  • Bejeweled
"},{"location":"board-pathfinder/","title":"Path finder","text":""},{"location":"board-pathfinder/#introduction","title":"Introduction","text":"

Find moveable area or moving path, chess behavior of Board system.

  • Author: Rex
  • Application of Board system, or behavior of chess
"},{"location":"board-pathfinder/#live-demos","title":"Live demos","text":"
  • Find area, get path
  • Draw path
  • Energy drain
  • Turning cost
  • Move from high to low
  • Chinese checkers
"},{"location":"board-pathfinder/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-pathfinder/#install-plugin","title":"Install plugin","text":""},{"location":"board-pathfinder/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add path-finder
    var pathFinder = scene.rexBoard.add.pathFinder(config);\n
"},{"location":"board-pathfinder/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add path-finder
    var pathFinder = scene.rexBoard.add.pathFinder(config);\n
"},{"location":"board-pathfinder/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PathFinder } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add path-finder
    var pathFinder = new PathFinder(config);\n
"},{"location":"board-pathfinder/#create-instance","title":"Create instance","text":"
var pathFinder = scene.rexBoard.add.pathFinder({\n// occupiedTest: false,\n// blockerTest: false,\n\n// ** cost **\n// cost: 1,   // constant cost\n// costCallback: undefined,\n// costCallbackScope: undefined,\n// cacheCost: true,\n\n// pathMode: 10,  // A*\n// weight: 10,   // weight for A* searching mode\n// shuffleNeighbors: false,\n})\n
  • occupiedTest : Set true to test if target tile position is occupied or not, in cost function.
  • blockerTest : Set true to test blocker property in cost function.
  • Cost function
    • cost : A constant cost for each non-blocked tile
    • costCallback, costCallbackScope : Get cost via callback
      function(curTile, preTile, pathFinder) {\nreturn cost;\n}\n
      • Board : pathFinder.board
      • Chess game object : pathFinder.gameObject
      • Cost of blocker : pathFinder.BLOCKER
  • pathMode
    • Shortest path
      • 'random', or 0
      • 'diagonal', or 1
      • 'straight', or 2
      • 'line', or 3
    • A* path
      • 'A*', or 10
      • 'A*-random', or 11
      • 'A*-line', or 12
  • weight : Weight parameter for A* searching mode.
  • cacheCost : Set false to get cost every time. It is useful when cost is a function of (current tile, previous tile).
  • shuffleNeighbors : Shuffle neighbors.
"},{"location":"board-pathfinder/#create-behavior","title":"Create behavior","text":"
var pathFinder = scene.rexBoard.add.pathFinder(chess, config);\n
"},{"location":"board-pathfinder/#set-chess","title":"Set chess","text":"
pathFinder.setChess(chess);\n

Note

Don't use this method if pathFinder is a behavior of Chess

"},{"location":"board-pathfinder/#cost-function","title":"Cost function","text":"
var callback = function(curTileXY, preTileXY, pathFinder) {\nreturn cost;\n}\n
  • cost : Number cost.
  • curTileXY, preTileXY : TileXY position {x, y}. Cost of moving from preTileXY to curTileXY.
    • preTileXY.pathCost : Path cost of preTilexY.
    • preTileXY.preNodes : Previous tiles of preTileXY.
  • pathFinder : Path finder object.
    • pathFinder.board : Board object
    • pathFinder.gameObject : Chess game object.
    • pathFinder.BLOCKER : Cost of blocker. Return this value means that chess can not move to curTileXY.
"},{"location":"board-pathfinder/#set-cost-function","title":"Set cost function","text":"
  • Constant cost for each non-blocked tile
    pathFinder.setCostFunction(cost);\n
  • Get cost via callback
    pathFinder.setCostFunction(callback, scope);\n
"},{"location":"board-pathfinder/#set-path-mode","title":"Set path mode","text":"
pathFinder.setPathMode(pathMode)\n
  • pathMode
    • Shortest path
      • 'random', or 0
      • 'diagonal', or 1
      • 'straight', or 2
      • 'line', or 3
    • A* path
      • 'A*', or 10
      • 'A*-random', or 11
      • 'A*-line', or 12
"},{"location":"board-pathfinder/#find-moveable-area","title":"Find moveable area","text":"
var tileXYArray = pathFinder.findArea(movingPoints);\n// var out = pathFinder.findArea(movingPoints, out);\n
  • movingPoints
    • pathFinder.INFINITY (undefined) : Infinity moving points. Default value.
  • tileXYArray : An array of moveable tile positions {x,y,pathCost}
"},{"location":"board-pathfinder/#get-shortest-path-to-a-moveable-tile","title":"Get shortest path to a moveable tile","text":"
var tileXYArray = pathFinder.getPath(endTileXY);\n
  • endTileXY : Tile position of moveable area in last result of pathFinder.findArea()
  • tileXYArray : Moving path in an array of tile positions {x,y,pathCost}
    • Uses moveTo behavior to move chess along path.

Path mode

  • Path info of each tile is calculated during pathFinder.findArea()
"},{"location":"board-pathfinder/#find-moving-path","title":"Find moving path","text":"
var tileXYArray = pathFinder.findPath(endTileXY);\n// var tileXYArray = pathFinder.findPath(endTileXY, movingPoints, isClosest, out);\n
  • endTileXY : Tile position
  • tileXYArray : Moving path in an array of tile positions {x,y,pathCost}
    • Uses moveTo behavior to move chess along path.
  • movingPoints
    • pathFinder.INFINITY (undefined) : Infinity moving points. Default value.
  • isClosest : Set true to get closest path.

Path mode

  • Set pathMode to A* ('A*', 'A*-random', or 'A*-line') to speed up calculating.
"},{"location":"board-pathfinder/#cost-of-tile","title":"Cost of tile","text":"

During or after finding moveable area...

  • Get cost of path from chess to tile
    var pathCost = pathFinder.tileXYToCost(tileX, tileY, true);\n
  • Get cost of tile
    var tileCost = pathFinder.tileXYToCost(tileX, tileY, false);\n
"},{"location":"board-quadgrid/","title":"Quad","text":""},{"location":"board-quadgrid/#introduction","title":"Introduction","text":"

Quad grid object of Board system.

  • Author: Rex
  • Grid object of board
"},{"location":"board-quadgrid/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-quadgrid/#create-instance","title":"Create instance","text":"
var grid = scene.rexBoard.add.quadGrid({\nx: 0,\ny: 0,\ncellWidth: 0,\ncellHeight: 0,\ntype: 0,\n// dir: 4\n});\n

or

// import { QuadGrid } from 'phaser3-rex-plugins/plugins/board-components.js';\nvar grid = new QuadGrid(config);\n
  • x, y : World position of tile (0, 0)
  • cellWidth : The width of the cell, in pixels.
  • cellHeight : The height of the cell, in pixels.
  • type
    • 0, or orthogonal
    • 1, or isometric
  • dir :
    • 4 or '4dir' : Left/Down/Right/Up
    • 8 or '8dir' : Left/Down/Right/Up/Left-down/Down-right/Right-up/Up-left
"},{"location":"board-quadgrid/#world-position-of-tile-0-0","title":"World position of tile (0, 0)","text":"
  • Get
    var worldX = grid.x;\nvar worldY = grid.y;\n
  • Set
    grid.setOriginPosition(worldX, worldY);\n
    or
    grid.x = worldX;\ngrid.y = worldY;\n
"},{"location":"board-quadgrid/#cell-size","title":"Cell size","text":"
  • Get
    var width = grid.width;\nvar height = grid.height;\n
  • Set
    grid.setCellSize(width, height);\n
    or
    grid.width = width;\ngrid.height = height;\n
"},{"location":"board-quadgrid/#grid-type","title":"Grid type","text":"
  • Get
    var mode = grid.mode;\n
  • Set
    grid.setType(mode);\n
    • mode
      • 0, or orthogonal
      • 1, or isometric
"},{"location":"board-quadgrid/#get-world-position","title":"Get world position","text":"
var worldXY = grid.getWorldXY(tileX, tileY);  // worldXY: {x, y}\n// var out = grid.getWorldXY(tileX, tileY, out);\n
"},{"location":"board-quadgrid/#get-tile-position","title":"Get tile position","text":"
var tileXY = grid.getTileXY(worldX, worldY);  // tileXY: {x, y}\n// var out = grid.getTileXY(worldX, worldY, out);\n
"},{"location":"board-quadgrid/#directions","title":"Directions","text":"
  • 0 : Right
  • 1 : Down
  • 2 : Left
  • 3 : Up
  • 4 : Right-down
  • 5 : Left-down
  • 6 : Left-up
  • 7 : Right-up
6|3|7\n-+-+-\n2|A|0\n-+-+-\n5|1|4\n
"},{"location":"board-shape/","title":"Shape","text":""},{"location":"board-shape/#introduction","title":"Introduction","text":"

Grid (polygon) shape chess object.

  • Author: Rex
  • Chess Game object of Board system
"},{"location":"board-shape/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-shape/#install-plugin","title":"Install plugin","text":""},{"location":"board-shape/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add chess object
    var chess = scene.rexBoard.add.shape(board, tileX, tileY, tileZ, fillColor);\n
"},{"location":"board-shape/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add chess object
    var chess = scene.rexBoard.add.shape(board, tileX, tileY, tileZ, fillColor);\n
"},{"location":"board-shape/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Shape } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add chess object
    var chess = new Shape(board, tileX, tileY, tileZ, fillColor);\nscene.add.existing(chess);\n
"},{"location":"board-shape/#add-chess-object","title":"Add chess object","text":"
  • Create chess object and add to board
    var chess = scene.rexBoard.add.shape(board, tileX, tileY, tileZ, fillColor, fillAlpha);\n
    • board : Board object
    • tileX, tileY, tileZ : Tile position
    • fillColor, fillAlpha : Color of this shape chess object
  • Create chess object but not add to board
    var chess = scene.rexBoard.add.shape(board, x, y, undefined, fillColor, fillAlpha, false);\n
    • board : Board object
    • x, y : World position
    • fillColor, fillAlpha : Color of this shape chess object
"},{"location":"board-shape/#set-color","title":"Set color","text":"
  • Fill color
    chess.setFillStyle(color, alpha)\n
  • Stroke color
    chess.setStrokeStyle(lineWidth, color, alpha)\n

No tint methods

Uses shape.setFillStyle(color, alpha) to change color.

"},{"location":"board-shape/#other-properties","title":"Other properties","text":"

See polygon shape game object, game object

"},{"location":"board-sprite/","title":"Sprite","text":""},{"location":"board-sprite/#introduction","title":"Introduction","text":"

Sprite chess object.

  • Author: Rex
  • Chess Game object of Board system
"},{"location":"board-sprite/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-sprite/#install-plugin","title":"Install plugin","text":""},{"location":"board-sprite/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add chess object
    var chess = scene.rexBoard.add.sprite(board, tileX, tileY, tileZ, key, frame);\n
"},{"location":"board-sprite/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add chess object
    var chess = scene.rexBoard.add.sprite(board, tileX, tileY, tileZ, key, frame);\n
"},{"location":"board-sprite/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Sprite } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add chess object
    var chess = new Sprite(board, tileX, tileY, tileZ, key, frame);\nscene.add.existing(chess);\n
"},{"location":"board-sprite/#add-chess-object","title":"Add chess object","text":"
  • Create chess object and add to board
    var chess = scene.rexBoard.add.sprite(board, tileX, tileY, tileZ, key, frame);\n
    • board : Board object
    • tileX, tileY, tileZ : Tile position
    • key, frame : Frame of this sprite chess object
  • Create chess object but not add to board
    var chess = scene.rexBoard.add.sprite(board, x, y, undefined, key, frame, false);\n
    • board : Board object
    • x, y : World position
    • key, frame : Frame of this sprite chess object
"},{"location":"board-sprite/#other-properties","title":"Other properties","text":"

See Sprite game object, game object

"},{"location":"board-texture/","title":"Tile texture","text":""},{"location":"board-texture/#introduction","title":"Introduction","text":"

Create canvas-texture of tile.

  • Author: Rex
  • Help method of board
"},{"location":"board-texture/#live-demos","title":"Live demos","text":"
  • Tile texture
"},{"location":"board-texture/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-texture/#install-plugin","title":"Install plugin","text":""},{"location":"board-texture/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Create tile texture
    scene.rexBoard.createTileTexture(board, key, fillStyle, strokeStyle, lineWidth);\n
"},{"location":"board-texture/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create tile texture
    scene.rexBoard.createTileTexture(board, key, fillStyle, strokeStyle, lineWidth);\n
"},{"location":"board-texture/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { CreateTileTexture } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Create tile texture
    CreateTileTexture(board, key, fillStyle, strokeStyle, lineWidth);\n
"},{"location":"board-texture/#create-tile-texture","title":"Create tile texture","text":""},{"location":"board-texture/#hexagon","title":"Hexagon","text":"
CreateTileTexture(board, key, fillStyle, strokeStyle, lineWidth);\n// CreateTileTexture(board, key, fillStyle, strokeStyle, lineWidth, overlapGrid, lineJoin);\n
  • board : Board object.
  • fillStyle : Fill color of tile texture.
    • undefined : Don't fill tile texture.
  • strokeStyle, lineWidth : Stroke color, stroke line width of tile texture.
    • undefined : Don't stroke tile texture.
  • overlapGrid :
    • true : Overlap grid. i.e. Grid width = lineWidth. Default behavior.
    • false : Don't overlap grid. i.e. Grid width = 2 * lineWidth.
  • lineJoin : Join style of stroke lines. 'round', 'bevel' and 'miter'. Default is 'miter'.
"},{"location":"board-tilemap/","title":"Tilemap","text":""},{"location":"board-tilemap/#introduction","title":"Introduction","text":"

Create board from tilemap

  • Author: Rex
  • Help method of board
"},{"location":"board-tilemap/#live-demos","title":"Live demos","text":"
  • Create board from tilemap
"},{"location":"board-tilemap/#usage","title":"Usage","text":"

Sample code

"},{"location":"board-tilemap/#install-plugin","title":"Install plugin","text":""},{"location":"board-tilemap/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Create board from tilemap
    var board = scene.rexBoard.createBoardFromTilemap(tilemap, layers);\n
"},{"location":"board-tilemap/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create board from tilemap
    var board = scene.rexBoard.createBoardFromTilemap(tilemap, layers);\n
"},{"location":"board-tilemap/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { CreateBoardFromTilemap } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Create board from tilemap
    var board = CreateBoardFromTilemap(tilemap, layers);\n
"},{"location":"board-tilemap/#create-board-from-tilemap","title":"Create board from tilemap","text":"
var board = CreateBoardFromTilemap(tilemap, layers);\n
  • tilemap : Tilemap object
  • layers : Add tiles of layers into board, tileZ will be name of layer (layer.name)
    • undefined : Add tiles of all layers.
    • Array of TilemapLayer game object, or a TilemapLayer game object
    • Array of layers' name, or a name of layer.
  • board : Board object.
"},{"location":"board/","title":"Board","text":""},{"location":"board/#introduction","title":"Introduction","text":"

Core object of Board system.

  • Author: Rex
  • Member of scene
"},{"location":"board/#live-demos","title":"Live demos","text":"
  • Touch events
  • Get tileXY at direction
  • Line to tileXY array
  • Triangle to tileXY array
  • Ellipse to tileXY array
  • Bounds
"},{"location":"board/#usage","title":"Usage","text":"

Sample code

"},{"location":"board/#install-plugin","title":"Install plugin","text":""},{"location":"board/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexboardplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboardplugin.min.js', 'rexBoard', 'rexBoard');\n
  • Add board object
    var board = scene.rexBoard.add.board(config);\n
"},{"location":"board/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoardPlugin from 'phaser3-rex-plugins/plugins/board-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexBoard',\nplugin: BoardPlugin,\nmapping: 'rexBoard'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add board object
    var board = scene.rexBoard.add.board(config);\n
"},{"location":"board/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Board, HexagonGrid, QuadGrid } from 'phaser3-rex-plugins/plugins/board-components.js';\n
  • Add board object
    var board = new Board(scene, {\ngrid: QuadGrid(gridConfig),  // or HexagonGrid(gridConfig)\n// ...\n});\n
"},{"location":"board/#add-board-object","title":"Add board object","text":"
  • Quad board
    var board = scene.rexBoard.add.board({\ngrid: {\ngridType: 'quadGrid',\nx: 0,\ny: 0,\ncellWidth: 0,\ncellHeight: 0,\ntype: 'orthogonal'  // 'orthogonal'|'isometric'\n},\n// width: 0,\n// height: 0,\n// wrap: false,\n// infinity: false,\n});\n
  • Hexagon board
    var board = scene.rexBoard.add.board({\ngrid: {\ngridType: 'hexagonGrid',\nx: 0,\ny: 0,\ncellWidth: 0,\ncellHeight: 0,\nstaggeraxis: 'x',   // 'x'|'y'\nstaggerindex: 'odd' // 'odd'|'even'\n},\n// width: 0,\n// height: 0,\n// wrap: false,\n// infinity: false,\n});\n

Configuration

  • grid :
    • gridType :
      • 'quadGrid' : Quad grid
      • 'hexagonGrid' : hexagon grid
  • width : Board width in tiles
  • height : Board height in tiles
  • wrap : Set true to wrap board bounds. Default value is false.
  • infinity : Infinity board size if set to true. Default value is false.
"},{"location":"board/#custom-class","title":"Custom class","text":"
  • Define class
    class MyBoard extends RexPlugins.Board.Board {\nconstructor(scene) {\nsuper(scene, {\ngrid: {\ngridType: 'quadGrid',\nx: 0,\ny: 0,\ncellWidth: 0,\ncellHeight: 0,\ntype: 'orthogonal'  // 'orthogonal'|'isometric'\n},\nwidth: 0,\nheight: 0\n});\n// ...\n}\n// ...\n}\n
  • Create instance
    var board = new MyBoard(scene);\n
"},{"location":"board/#board-size","title":"Board size","text":"
  • Width : Board width in tiles
    • Get
      var width = board.width;\n
    • Set
      board.setBoardWidth(width);\n
  • Height : Board height in tiles
    • Get
      var height = board.height;\n
    • Set
      board.setBoardHeight(height);\n
"},{"location":"board/#add-chess","title":"Add chess","text":"
board.addChess(chess, tileX, tileY, tileZ, align);\n
  • chess : A game object.
  • tileX , tileY , tileZ : Tile position.
    • tileX , tileY : Number.
    • tileZ : Number or string.
  • align : Set true to align (i.e. set position) chess to grid (tileX, tileY). Default is true.

Chess and tile position

  • Any chess has a (tileX, tileY, tileZ) index
  • Any (tileX, tileY, tileZ) index contains only 1 chess.
  • (tileX, tileY) could have more then 1 chess with different tileZ index.
  • tileZ is not equal to depth.
"},{"location":"board/#kick-out-event","title":"Kick-out event","text":"

Board will fire kickout event when adding chess to an occupied grid.

board.on('kickout', function(chessToAdd, occupiedChess, tileXYZ){\n})\n

chessToAdd kicks out occupiedChess at tile position tileXYZ({x,y,z}).

"},{"location":"board/#remove-chess","title":"Remove chess","text":"
  • Remove chess object from board
    board.removeChess(chess, null, null, null, destroy);\n
    • chess : A game object
    • destroy : Set true to desrtoy chess object.
  • Remove chess at (tileX, tileY, tileZ) from board
    board.removeChess(null, tileX, tileY, tileZ, destroy);\n
    • tileX, tileY, tileZ : Tile position
    • destroy : Set true to desrtoy chess object.
  • Remove all chess
    board.removeAllChess(destroy);\n
    • destroy : Set true to desrtoy chess object.
"},{"location":"board/#move-chess","title":"Move chess","text":"
board.moveChess(chess, toTileX, toTileY, toTileZ, align);\n
  • chess : A game object
  • toTileX, toTileY, toTileZ : Target tile position
  • align : Set true to align (i.e. set position) chess to grid (tileX, tileY). Default is true.

Do nothing if chess is not at this board.

"},{"location":"board/#set-tilez-of-chess","title":"Set tileZ of chess","text":"
board.setChessTileZ(chess, toTileZ, align);\n
  • chess : A game object
  • toTileZ : Target tileZ
  • align : Set true to align (i.e. set position) chess to grid (tileX, tileY). Default is false.
"},{"location":"board/#swap-chess","title":"Swap chess","text":"
board.swapChess(chessA, chessB, align);\n
  • chessA, chessB : Game objects
  • align : Set true to align (i.e. set position) chess to grid (tileX, tileY).
"},{"location":"board/#chess-tile-position","title":"Chess -> tile position","text":"
var tileXYZ = board.chessToTileXYZ(chess);\n
  • chess : A game object
  • tileXYZ : {x,y,z} or null if chess is not added to board.
"},{"location":"board/#tile-position-chess","title":"Tile position -> chess","text":"
  • Get chess at (tileX, tileY, tileZ)
    var chess = board.tileXYZToChess(tileX, tileY, tileZ);\n
    • chess : A game object
  • Get chess at (tileX, tileY)
    var out = board.tileXYToChessArray(tileX, tileY);\n// var out = board.tileXYToChessArray(tileX, tileY, out);\n
    • out : An array of chess
  • Get chess at tileZ
    var out = board.tileZToChessArray(tileZ);\n// var out = board.tileZToChessArray(tileZ, out);\n
    • out : An array of chess
  • Get chess from array of (tileX, tileY)
    var out = board.tileXYArrayToChessArray(tileXYArray);\n// var out = board.tileXYArrayToChessArray(tileXYArray, out);\n
    or
    var out = board.tileXYArrayToChessArray(tileXYArray, tileZ);\n// var out = board.tileXYArrayToChessArray(tileXYArray, tileZ, out);\n
    • tileXYArray : An array of tileXY {x, y}
    • out : An array of chess
"},{"location":"board/#world-position-chess","title":"World position -> chess","text":"
  • Get chess at (worldX, worldY)
    var out = board.worldXYToChessArray(worldX, worldY);\n// var out = board.worldXYToChessArray(worldX, worldY, out);\n
    • out : An array of chess
  • Get chess at (worldX, worldY), tileZ
    var chess = board.worldXYToChess(worldX, worldY, tileZ);\n
    • chess : A game object
  • Get chess at (worldX, worldY)
    var chess = board.worldXYToChess(worldX, worldY);\n
    • chess : A game object at a tileZ.
"},{"location":"board/#contains","title":"Contains","text":"
  • Is (tileX, tileY) inside board?
    var isTileInBoard = board.contains(tileX, tileY);\n
  • Does (tileX, tileY, tileZ) have chess?
    var isTileInBoard = board.contains(tileX, tileY, tileZ);\n
  • Is chess inside board?
    var isChessInBoard = board.exists(chess);\n
    • chess : A game object
"},{"location":"board/#for-each-tile","title":"For each tile","text":"
board.forEachTileXY(function(tileXY, board) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n}, scope);\n

Iteration order :

board.forEachTileXY(function(tileXY, board) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n\n// return isBreak;\n}, scope, order);\n
  • order :
    • 0, or 'x+' : Increasing x, increasing y.
    • 1, or 'x-' : Decreasing x, increasing y.
    • 2, or 'y+' : Increasing y, increasing x.
    • 3, or 'y-' : Decreasing y, increasing x.

Or using for-loop

for (var tileY = 0; tileY < board.height; tileY++) {\nfor (var tileX = 0; tileX < board.width; tileX++) {\n// ...\n}\n}\n
  • board.width , board.height : Board width/height in tiles.
"},{"location":"board/#for-each-tile-in-viewport-of-a-camera","title":"For each tile in viewport of a camera","text":"
board.forEachCullTileXY(function(tileXY, board) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n}, scope);\n
board.forEachCullTileXY(function(tileXY, board) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n}, scope, {\ncamera: board.scene.cameras.main,\npaddingX: 1,\npaddingY: 1,\norder: 0,\n});\n
  • camera : Camera of scene. Default value is the main camera.
  • paddingX , paddingY : Padding space of camera's viewport
  • order :
    • 0, or 'x+' : Increasing x, increasing y.
    • 1, or 'x-' : Decreasing x, increasing y.
    • 2, or 'y+' : Increasing y, increasing x.
    • 3, or 'y-' : Decreasing y, increasing x.
"},{"location":"board/#tile-position-world-position","title":"Tile position -> world position","text":"
var worldXY = board.tileXYToWorldXY(tileX, tileY);  // worldXY: {x, y}\n// var out = board.tileXYToWorldXY(tileX, tileY, out);\n
"},{"location":"board/#world-position-tile-position","title":"World position -> tile position","text":"
var tileXY = board.worldXYToTileXY(worldX, worldY);  // tileXY: {x, y}\n// var out = board.worldXYToTileXY(worldX, worldY, out);\n
"},{"location":"board/#world-position-grid-world-position","title":"World position -> Grid world position","text":"
var gridWorldXY = board.worldXYSnapToGrid(worldX, worldY);\n// var out = board.worldXYSnapToGrid(worldX, worldY, out);\n
"},{"location":"board/#grid-distance","title":"Grid distance","text":"
var distance = board.getDistance(tileA, tileB);\n
  • tileA, tileB : Chess object, or tileXY {x, y}.
"},{"location":"board/#ring-tile-position","title":"Ring -> tile position","text":"
  • Get array of tile position around a ring.
    var out = board.ringToTileXYArray(centerTileXY, radius);\n// var out = board.ringToTileXYArray(centerTileXY, radius, out);\n
    • centerTileXY : Chess object, or tileXY {x, y} of ring center.
    • radius : Radius of the ring.
  • Get array of tile position within a filled ring. centerTileXY will be included.
    var out = board.filledRingToTileXYArray(centerTileXY, radius);\nvar out = board.filledRingToTileXYArray(centerTileXY, radius, nearToFar);\n// var out = board.filledRingToTileXYArray(centerTileXY, radius, out);\n// var out = board.filledRingToTileXYArray(centerTileXY, radius, nearToFar, out);\n
    • centerTileXY : Chess object, or tileXY {x, y} of ring center.
    • radius : Radius of the ring.
    • nearToFar : From near ring to far ring. Default value is true.
"},{"location":"board/#ring-chess","title":"Ring -> chess","text":"
  • Get array of chess around a ring.
    var out = board.ringToChessArray(centerTileXY, radius, tileZ);\n// var out = board.ringToChessArray(centerTileXY, radius, tileZ, out);\n
    • centerTileXY : Chess object, or tileXY {x, y} of ring center.
  • Get array of chess within a filled ring. Chess at centerTileXY will be included.
    var out = board.filledRingToTileXYArray(centerTileXY, radius, tileZ);\nvar out = board.filledRingToTileXYArray(centerTileXY, radius, tileZ, nearToFar);\n// var out = board.filledRingToTileXYArray(centerTileXY, radius, tileZ, out);\n// var out = board.filledRingToTileXYArray(centerTileXY, radius, tileZ, nearToFar, out);\n
    • centerTileXY : Chess object, or tileXY {x, y} of ring center.
"},{"location":"board/#shape-tile-position","title":"Shape -> tile position","text":""},{"location":"board/#line-tile-position","title":"Line -> tile position","text":"

Get array of tile position along a line defined via (startWorldX, startWorldY) to (endWorldX, endWorldY)

var out = board.lineToTileXYArray(startWorldX, startWorldY, endWorldX, endWorldY);\n// var out = board.lineToTileXYArray(startWorldX, startWorldY, endWorldX, endWorldY, out);\n
  • startWorldX, startWorldY, endWorldX, endWorldY : Start and end pointer of a line
  • out : An array of tile position

or

var out = board.lineToTileXYArray(line);\n// var out = board.lineToTileXYArray(line, out);\n
  • line : Line object
"},{"location":"board/#circle-tile-position","title":"Circle -> tile position","text":"

Get array of tile position inside a circle shape

var out = board.circleToTileXYArray(circle);\n// var out = board.circleToTileXYArray(circle, out);\n// var out = board.circleToTileXYArray(circle, testMode, out);\n
  • circle : Circle shape
  • testMode :
    • 0 : Test if shape is overlapping center position of a grid. Default behavior.
    • 1 : Test if shape is overlapping grid bounds of a grid.
    • 2 : Test if shape is overlapping grid points of a grid.
  • out : An array of tile position.
"},{"location":"board/#rectangle-tile-position","title":"Rectangle -> tile position","text":"

Get array of tile position inside a rectangle shape

var out = board.rectangleToTileXYArray(rectangle);\n// var out = board.rectangleToTileXYArray(rectangle, out);\n// var out = board.rectangleToTileXYArray(rectangle, testMode, out);\n
  • rectangle : Rectangle shape
  • testMode :
    • 0 : Test if shape is overlapping center position of a grid. Default behavior.
    • 1 : Test if shape is overlapping grid bounds of a grid.
    • 2 : Test if shape is overlapping grid points of a grid.
  • out : An array of tile position.
"},{"location":"board/#ellipse-tile-position","title":"Ellipse -> tile position","text":"

Get array of tile position inside a ellipse shape

var out = board.ellipseToTileXYArray(ellipse);\n// var out = board.ellipseToTileXYArray(ellipse, out);\n// var out = board.ellipseToTileXYArray(ellipse, testMode, out);\n
  • ellipse : Ellipse shape
  • testMode :
    • 0 : Test if shape is overlapping center position of a grid. Default behavior.
    • 1 : Test if shape is overlapping grid bounds of a grid.
    • 2 : Test if shape is overlapping grid points of a grid.
  • out : An array of tile position.
"},{"location":"board/#triangle-tile-position","title":"Triangle -> tile position","text":"

Get array of tile position inside a triangle shape

var out = board.triangleToTileXYArray(triangle);\n// var out = board.triangleToTileXYArray(triangle, out);\n// var out = board.triangleToTileXYArray(triangle, testMode, out);\n
  • triangle : Triangle shape
  • testMode :
    • 0 : Test if shape is overlapping center position of a grid. Default behavior.
    • 1 : Test if shape is overlapping grid bounds of a grid.
    • 2 : Test if shape is overlapping grid points of a grid.
  • out : An array of tile position.
"},{"location":"board/#polygon-tile-position","title":"Polygon -> tile position","text":"

Get array of tile position inside a polygon shape

var out = board.polygonToTileXYArray(polygon);\n// var out = board.polygonToTileXYArray(polygon, out);\n// var out = board.polygonToTileXYArray(polygon, testMode, out);\n
  • polygon : Polygon shape
  • testMode :
    • 0 : Test if shape is overlapping center position of a grid. Default behavior.
    • 1 : Test if shape is overlapping grid bounds of a grid.
    • 2 : Test if shape is overlapping grid points of a grid.
  • out : An array of tile position.
"},{"location":"board/#angle-between-world-position-of-2-tiles","title":"Angle between world position of 2 tiles","text":"
var radian = board.angleBetween(tileA, tileB);\n
  • tileA, tileB : Chess object, or tileXY {x, y} of ring center.
  • radian : Angle between world position of 2 tiles, in radian.
"},{"location":"board/#is-angle-in-cone","title":"Is angle in cone","text":"
var isInCone = board.isAngleInCone(chessA, chessB, face, cone);\n
  • chessA, chessB : Chess object, or tileXY {x, y}.
  • face, cone : Range of compared angle is between face - (cone/2) to face + (cone/2). Angle in radian.
"},{"location":"board/#direction-between-2-tiles","title":"Direction between 2 tiles","text":"
var direction = board.directionBetween(chessA, chessB);\n
  • chessA, chessB : A chess object, or tile position {x,y}.
  • direction : Integer number.
    • Quad grid : 0, 1, 2, 3, 4, 5, 6, 7.
    • Hexagon grid : 0, 1, 2, 3, 4, 5.
var direction = board.directionBetween(chessA, chessB, false);\n
  • direction : Integer number, or float number.
    • Quad grid : 0, 1, 2, 3, 4, 5, 6, 7, or float number between 0~1, 1~2, 2~3, 3~4, 4~5, 5~6, 6~7.
    • Hexagon grid : 0, 1, 2, 3, 4, 5, or float number between 0~1, 1~2, 2~3, 3~4, 4~5, 5~6.
"},{"location":"board/#is-direction-in-cone","title":"Is direction in cone","text":"
var isInCone = board.isDirectionInCone(chessA, chessB, face, cone);\n
  • chessA, chessB : Chess object, or tileXY {x, y}.
  • face, cone : Range of compared direction is between face - (cone/2) to face + (cone/2). Integer number, or float number.
    • Quad grid : 0, 1, 2, 3, or float number between 0~1, 1~2, 2~3, 3~4.
    • Hexagon grid : 0, 1, 2, 3, 4, 5, or float number between 0~1, 1~2, 2~3, 3~4, 4~5, 5~6.
"},{"location":"board/#opposite-direction","title":"Opposite direction","text":"
var direction = board.getOppositeDirection(tileX, tileY, direction);\n

or

var direction = board.getOppositeDirection(tileXY, direction);\n
  • tileXY : Chess object, or tileXY {x, y}.
"},{"location":"board/#angle-snap-to-direction","title":"Angle snap to direction","text":"
var direction = board.angleSnapToDirection(tileXY, angle);\n
  • tileXY : Chess object, or tileXY {x, y}, or undefined.
  • angle : Angle in radius.
  • direction : Integer number.
    • Quad grid : 0, 1, 2, 3, 4, 5, 6, 7.
    • Hexagon grid : 0, 1, 2, 3, 4, 5.
"},{"location":"board/#align-world-position-to-grid","title":"Align world position to grid","text":"
  • Align one chess object
    board.gridAlign(chess);\n
  • Align all chess
    board.gridAlign();\n
"},{"location":"board/#is-overlapping-with-world-position","title":"Is overlapping with world position","text":"
var isOverlapping = board.isOverlappingPoint(worldX, worldY);\n

or

var isOverlapping = board.isOverlappingPoint(worldX, worldY, tileZ);\n
"},{"location":"board/#neighbors","title":"Neighbors","text":""},{"location":"board/#neighbor-tile-position","title":"Neighbor tile position","text":"
  • Get neighbor tile position at 1 direction
    var neighborTileXY = board.getNeighborTileXY(srcTileXY, direction);\n// var out = board.getNeighborTileXY(srcTileXY, direction, out);\n
    • srcTileXY : Chess object, or tileXY {x, y} of source.
    • direction : Number, or string number.
      • 0 ~ 3 : Quad grid in 4 directions mode.
      • 0 ~ 7 : Quad grid in 8 directions mode.
      • 0 ~ 5 : Hexagon grid.
    • neighborTileXY : Tile position {x, y} of neighbor. Retrun null if no neighbor there (i.e. source chess is at the edge of board.)
  • Get neighbor tile position at directions
    var neighborTileXY = board.getNeighborTileXY(srcTileXY, directions);\n// var out = board.getNeighborTileXY(srcTileXY, directions, out);\n
    • directions
      • Array of numbers, [0, 2, 4].
      • String number concatenated via ,, '0,2,4'.
    • out : Tile position array of all neighbors
  • Get neighbor tile position at all directions
    var out = board.getNeighborTileXY(srcTileXY, null);\n// var out = board.getNeighborTileXY(srcTileXY, null, out);\n
    • out : Tile position array of all neighbors
  • Get direction between 2 tile positions
    var direction = board.getNeighborTileDirection(srcTile, neighborTileXY);\n
    • srcTile, neighborTileXY : Chess object, or tileXY {x, y}.
    • direction : Retu1rn null if these 2 tile positions are not neighbors.
  • Get neighbor tile position at angle
    var neighborTileXY = board.getNeighborTileXYAtAngle(srcTileXY, angle);\n// var out = board.getNeighborTileXYAtAngle(srcTileXY, angle, out);\n
    • srcTileXY : Tile position {x, y} of source.
    • angle : Angle in radius.
    • neighborTileXY : Tile position {x, y} of neighbor. Retrun null if no neighbor there (i.e. source chess is at the edge of board.)
"},{"location":"board/#neighbor-chess","title":"Neighbor chess","text":"
  • Get neighbor chess at 1 direction
    var neighborChess = board.getNeighborChess(chess, direction); // neighborTileZ = tileZ of chess\n// var neighborChess = board.getNeighborChess(chess, direction, neighborTileZ);\n
    • chess : A chess object, or tile position {x, y, z}.
    • direction : Number, or string number.
      • 0 ~ 3 : Quad grid in 4 directions mode.
      • 0 ~ 7 : Quad grid in 8 directions mode.
      • 0 ~ 5 : Hexagon grid.
    • neighborChess : A chess object.
  • Get neighbor chess at directions
    var out = board.getNeighborChess(chess, directions); // neighborTileZ = tileZ of chess\n// var out = board.getNeighborChess(chess, directions, neighborTileZ);\n
    • chess : A chess object, or tile position {x,y,z}.
    • directions
      • Array of numbers, [0, 2, 4].
      • String number concatenated via ,, '0,2,4'.
    • out : Chess array of neighbors.
  • Get neighbor chess at all directions
    var out = board.getNeighborChess(chess, null); // neighborTileZ = tileZ of chess\n// var out = board.getNeighborChess(chess, null, neighborTileZ);\n
    • chess : A chess object, or tile position {x, y, z}.
    • out : Chess array of all neighbors.
  • Get direction between 2 chess
    var direction = board.getNeighborChessDirection(chess, neighborChess);\n
    • direction : Return null if these 2 chess are not neighbors.
  • Are 2 chess neighbors?
    var areNeighbor = board.areNeighbors(tileA, tileB);\n
  • tileA, tileB : A chess object, or tile position {x, y}.
  • areNeighbor : Return true if chessA and chessB are neighbors.
"},{"location":"board/#map-neighbor-tile-position","title":"Map neighbor tile position","text":"
var newArray = board.mapNeighbors(chess, function(neighborTileXY, index, neighborTileXYArray){\nreturn {};\n}, scope);\n

or

var newArray = board.mapNeighbors(chess, distance, function(neighborTileXY, index, neighborTileXYArray){\nreturn {};\n}, scope);\n
  • chess : A chess object, or tile position {x,y,z}.
  • neighborTileXY : Neighbor tile position {x,y,direction}
"},{"location":"board/#tile-at-direction","title":"Tile at direction","text":"
  • Get tile position at 1 direction
    var out = board.getTileXYAtDirection(srcTileXY, direction, distance);\n// var out = board.getTileXYAtDirection(srcTileXY, direction, distance, out);\n
    • srcTileXY : A chess object, or tile position {x, y} of source.
    • direction : Number, or string number.
      • 0 ~ 3 : Quad grid in 4 directions mode.
      • 0 ~ 7 : Quad grid in 8 directions mode.
      • 0 ~ 5 : Hexagon grid.
    • distance : A JSON, number, or number array.
      • JSON : Range of distances. {end: 3} is equal to [1,2,3].
        {\nstart: 1,\nend: 1,\nstep: 1\n}\n
        • start : Start distance. Default value is 1.
        • end : End distance. Default value is 1.
        • step : Step. Default value is 1.
      • Number, 3.
      • Array of numbers, [2, 3, 5] : Array of distances.
    • out :
      • A single tile position, if distance is a number.
      • Tile position {x, y} array, if distance is a JSON or a number array.
  • Get tile positions at directions
    var neighborTileXY = board.getTileXYAtDirection(srcTileXY, directions, distance);\n// var out = board.getTileXYAtDirection(srcTileXY, directions, distance, out);\n
    • directions
      • Array of numbers, [0, 2, 4].
      • String number concatenated via ,, '0,2,4'.
    • out : Tile position {x, y} array.
  • Get tile positions at all directions
    var out = board.getTileXYAtDirection(srcTileXY, null, distance);\n// var out = board.getTileXYAtDirection(srcTileXY, null, distance, out);\n
    • out : Tile position {x, y} array.
"},{"location":"board/#empty-tile-position","title":"Empty tile position","text":"
  • Is tile empty? (TileXY is inside board, and TileXYZ has no chess)
    var isEmpty = board.isEmptyTileXYZ(tileX, tileY, tileZ);\n
  • Get a random tile position which does not have any chess
    var tileXY = board.getRandomEmptyTileXY(tileZ);\n// var out = board.getRandomEmptyTileXY(tileZ, out);\n
    • tileXY : Tile position {x, y},
      • null : All positions are occupied.
  • Get an array of tile position which does not have any chess
    var tileXYArray = board.getEmptyTileXYArray(tileZ);\n// var out = board.getEmptyTileXYArray(tileZ, out);\n
    • tileXYArray : An array of tile position
  • Get a random tile position of neighbor which does not have any chess
    var tileXY = board.getRandomEmptyTileXYInRange(centerTileXY, radius, tileZ);\n// var out = board.getRandomEmptyTileXYInRange(centerTileXY, radius, tileZ, out);\n
    • centerTileXY : Chess object, or tileXY {x, y} of ring center.
    • radius : Radius of the ring.
    • tileXY : Tile position {x, y},
      • null : All positions are occupied.
  • Get an array of tile position of neighbors which does not have any chess
    var tileXYArray = board.getEmptyTileXYArrayInRange(centerTileXY, radius, tileZ);\n// var out = board.getEmptyTileXYArrayInRange(centerTileXY, radius, tileZ, out);\n
    • centerTileXY : Chess object, or tileXY {x, y} of ring center.
    • radius : Radius of the ring.
    • tileXYArray : An array of tile position
"},{"location":"board/#get-all-chess","title":"Get all chess","text":"
var chessArray = board.getAllChess();\n
"},{"location":"board/#fit","title":"Fit","text":"
var out = board.fit(tileXYArray);\n
  • tileXYArray : An array of tile position {x,y}.

Offset all of tile positions to (0, 0), and set board size to fit these tile positions.

"},{"location":"board/#blocker","title":"Blocker","text":"
  • Set blocker property : See chess data
  • Has blocker at tile position (tileX, tileY, tileZ)
    var hasBlocker = board.hasBlocker(tileX, tileY, tileZ);\n// var hasBlocker = board.hasBlocker(chess);  // chess or tileXYZ\n
  • Any chess at (tileX, tileY) has blocker property
    var hasBlocker = board.hasBlocker(tileX, tileY);\n// var hasBlocker = board.hasBlocker(chess);  // chess or tileXY\n
"},{"location":"board/#touch-events","title":"Touch events","text":""},{"location":"board/#set-interactive","title":"Set interactive","text":"
  • Enable
    board.setInteractive();\n// board.setInteractive({ useTouchZone: false });\n
    • useTouchZone :
      • true : Detect touch input by input event of a full-screen zone game object. Default behavior.
      • false : Detect touch input by input event of scene.
  • Disable
    board.setInteractive(false);\n
"},{"location":"board/#touch-zone","title":"Touch Zone","text":"
  • Get
    var touchZone = board.getTouchZone();\n// var touchZone = board.touchZone;\n
    • Return null if useTouchZone is false.
  • Set depth
    touchZone.setDepth(depth);\n
    or
    scene.children.bringToTop(touchZone);\nscene.children.sendToBack(touchZone);\nscene.children.moveUp(touchZone);\nscene.children.moveDown(touchZone);\nscene.children.moveUp(touchZone);\nscene.children.moveTo(touchZone, index);\nscene.children.moveAbove(touchZone, child); // Move touchZone above child\nscene.children.moveBelow(touchZone, child); // Move touchZone below child\nscene.children.swap(touchZone, child);\n
"},{"location":"board/#pointer-down","title":"Pointer down","text":"
  • Pointer down at any tile
    board.on('tiledown', function(pointer, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • pointer : Touch pointer
    • tileXY : {x, y}
  • Pointer down at chess
    board.on('gameobjectdown', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('board.pointerdown', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#pointer-up","title":"Pointer up","text":"
  • Pointer up at any tile
    board.on('tileup', function(pointer, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • tileXY : {x, y}
  • Pointer up at chess
    board.on('gameobjectup', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('board.pointerup', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#pointer-move","title":"Pointer move","text":"
  • Pointer move to another tile
    board.on('tilemove', function(pointer, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • tileXY : {x, y}
    • Only triggered when tileXY is changed.
  • Pointer move to another chess
    board.on('gameobjectmove', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('board.pointermove', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#pointer-over","title":"Pointer over","text":"
  • Pointer over to another tile
    board.on('tileover', function(pointer, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • tileXY : {x, y}
    • Only triggered when tileXY is changed.
  • Pointer over to another chess
    board.on('gameobjectover', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('board.pointerover', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#pointer-out","title":"Pointer out","text":"
  • Pointer out tile
    board.on('tileout', function(pointer, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • tileXY : {x, y}
    • Only triggered when tileXY is changed.
  • Pointer out chess
    board.on('gameobjectout', function(pointer, gameObject) {\n})\n
    or
    gameObject.on('board.pointerout', function(pointer) {\n})\n
    • pointer : Touch pointer
    • gameObject : Game object at pointer-out (tileX, tileY)
"},{"location":"board/#tap","title":"Tap","text":"
  • Tap at any tile
    board.on('tiletap', function(tap, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n// var tapsCount = tap.tapsCount;\n});\n
    • tap : Tap behavior.
      • tap.tapsCount : Taps count.
    • tileXY : {x, y}
  • N-taps at any tile
    board.on('tile' + tapsCount + 'tap' , function(tap, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • 'tile' + tapsCount + 'tap' : 'tile1tap', 'tile2tap', 'tile3tap', etc ...
    • tap : Tap behavior.
    • tileXY : {x, y}
  • Tap at chess
    board.on('gameobjecttap', function(tap, gameObject) {\n// var tapsCount = tap.tapsCount;\n})\n
    or
    gameObject.on('board.tap', function(tap) {\n// var tapsCount = tap.tapsCount;\n})\n
    • tap : Tap behavior.
      • tap.tapsCount : Taps count.
    • gameObject : Game object at touched (tileX, tileY)
  • N-taps at chess
    board.on('gameobject' + tapsCount + 'tap' , function(tap, gameObject) {\n})\n
    or
    gameObject.on('board.' + tapsCount + 'tap', function(tap) {\n})\n
    • 'gameobject' + tapsCount + 'tap' : 'gameobject1tap', 'gameobject2tap', 'gameobject3tap', etc ...
    • 'board.' + tapsCount + 'tap' : 'board.1tap', 'board.2tap', 'board.3tap', etc ...
    • tap : Tap behavior.
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#press","title":"Press","text":"
  • Press-start at any tile
    board.on('tilepressstart', function(press, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • press : Press behavior.
    • tileXY : {x, y}
  • Press-end at any tile
    board.on('tilepressend', function(press, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n});\n
    • press : Press behavior.
    • tileXY : {x, y}
  • Press-star at chess
    board.on('gameobjectpressstart', function(press, gameObject) {\n})\n
    or
    gameObject.on('board.pressstart', function(press) {\n})\n
    • press : Press behavior.
    • gameObject : Game object at touched (tileX, tileY)
  • Press-end at chess
    board.on('gameobjectpressend', function(press, gameObject) {\n})\n
    or
    gameObject.on('board.pressend', function(press) {\n})\n
    • press : Press behavior.
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#swipe","title":"Swipe","text":"
  • Swipe at any tile
    board.on('tileswipe', function(swipe, tileXY) {\n// var tileX = tileXY.x;\n// var tileY = tileXY.y;\n// var direction = swipe.direction;\n});\n
    • swipe : Swipe behavior.
      • swipe.direction : Integer number.
        • Quad grid : 0, 1, 2, 3, 4, 5, 6, 7.
        • Hexagon grid : 0, 1, 2, 3, 4, 5.
    • tileXY : {x, y}
  • Swipe at chess
    board.on('gameobjectswipe', function(swipe, gameObject) {\n// var direction = swipe.direction;\n})\n
    or
    gameObject.on('board.swipe', function(swipe) {\n// var direction = swipe.direction;\n})\n
    • swipe : Swipe behavior.
      • swipe.direction : Integer number.
        • Quad grid : 0, 1, 2, 3, 4, 5, 6, 7.
        • Hexagon grid : 0, 1, 2, 3, 4, 5.
    • gameObject : Game object at touched (tileX, tileY)
"},{"location":"board/#grid-points","title":"Grid points","text":"
  • Get an array of grid points at tile position (tileX, tileY).
    var points = board.getGridPoints(tileX, tileY);\n// var out = board.getGridPoints(tileX, tileY, out);\n// var points = board.getGridPoints(chess, out);  // chess or tileXY\n
    • points :\u3000Array of world position {x, y}.
  • Draw grid polygon on graphics object
    graphics.strokePoints(points, true);\n
"},{"location":"board/#bounds","title":"Bounds","text":""},{"location":"board/#board-bounds","title":"Board bounds","text":"
  • Get a rectangle of all tiles
    var rectangle = board.getBoardBounds();\n// var out = board.getGridBounds(out);\n
    • rectangle : Rectangle object.
  • Draw rectangle on graphics object
    graphics.strokeRectShape(rectangle);\n
"},{"location":"board/#grid-bounds","title":"Grid bounds","text":"
  • Get a rectangle of a tile
    var rectangle = board.getGridBounds(tileX, tileY);\n// var out = board.getGridBounds(tileX, tileY, out);\n// var rectangle = board.getGridBounds(chess, out);  // chess or tileXY\n
    • rectangle : Rectangle object.
  • Draw rectangle on graphics object
    graphics.strokeRectShape(rectangle);\n
"},{"location":"board/#get-board","title":"Get Board","text":"
  • Static method

    var board = Board.GetBoard(chess);\n

    • GetBoard is a static method of Board class.
  • Member method

    var board = board.chessToBoard(chess);\n

  • Board property
    • Chess
      var board = chess.rexChess.board;\n
    • Miniboard
      var board = miniboard.mainBoard;\n
"},{"location":"board/#other-properties","title":"Other properties","text":"
  • Scene
    var scene = board.scene;\n
  • Grid object
    • Get
      var grid = board.grid;\n
      • grid : Quad grid, or hexagon grid.
    • Set
      board.setGrid(grid);\n
      • grid : Quad grid, or hexagon grid.
"},{"location":"bounds/","title":"Bounds","text":""},{"location":"bounds/#introduction","title":"Introduction","text":"

Clamp or wrap position of game object inside target bounds.

  • Author: Rex
  • Behavior of game object
"},{"location":"bounds/#live-demos","title":"Live demos","text":"
  • Drag inside bounds
  • Target bounds
  • Wrap bounds
"},{"location":"bounds/#usage","title":"Usage","text":"

Sample code

"},{"location":"bounds/#install-plugin","title":"Install plugin","text":""},{"location":"bounds/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexboundsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexboundsplugin.min.js', true);\n
  • Add bounds behavior
    var bounds = scene.plugins.get('rexboundsplugin').add(gameObject, config);\n
"},{"location":"bounds/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BoundsPlugin from 'phaser3-rex-plugins/plugins/bounds-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBounds',\nplugin: BoundsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add bounds behavior
    var bounds = scene.plugins.get('rexBounds').add(gameObject, config);\n
"},{"location":"bounds/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Bounds from 'phaser3-rex-plugins/plugins/bounds.js';\n
  • Add bounds behavior
    var bounds = new Bounds(gameObject, config);\n
"},{"location":"bounds/#create-instance","title":"Create instance","text":"
var bounds = scene.plugins.get('rexBounds').add(gameObject, {\n// target: undefined,\n// bounds: undefined,\n// enable: true,\n\n// boundsHitMode: 'clamp',  // 'clamp', or 'wrap'\n// boundsHitMode: {\n//     left: 'clamp',\n//     right: 'clamp',\n//     top: 'clamp',\n//     bottom: 'clamp' \n// },\n\n// alignMode: 0\n});\n
  • target :
    • A game object : Update target bounds from this game object in each tick.
    • undefined, null, or false : Set target bounds in bounds parameter. Default behavior.
  • bounds : Target bounds used when target is not a game object.
    • A rectangle object
    • An object :
      {\nwidth: 0, height: 0,\nx: 0, y: 0,\ncenterX: 0, centerY: 0,            }\n
      • width, height : Size of target bounds.
      • x, y, or centerX, centerY : Position of target bounds.
  • enable :
    • true : Clamp or wrap game object's position when game object overlap left/right/top/bottom bounds.
    • false : Don't clamp or wrap game object's position at any bound
    • An objecct : Set true to clamp or wrap game object's position at a bound
      {\nleft: true,\nright: true,\ntop: true,\nbottom: true\n}\n
  • boundsHitMode : Position mode when game object overlap bounds
    • 0, or 'clamp' : Clamp game object's position when game object overlap left/right/top/bottom bounds.
    • 1, or 'wrap' : Wrap game object's position when game object overlap left/right/top/bottom bounds.
    • An objecct : Set 0/'clamp', or 1/'wrap' to clamp or wrap game object's position at a bound
      {\nleft: 0,   // 0,'clamp',1,'wrap'\nright: 0,  // 0,'clamp',1,'wrap'\ntop: 0,    // 0,'clamp',1,'wrap'\nbottom: 0  // 0,'clamp',1,'wrap'\n}\n
  • alignMode :
    • 0, or 'bounds' : Align bounds of game object to target bound. Default behavior if boundsHitMode are all set to clamp mode.
    • 1, or 'origin' : Set position of game object to target bound. Default behavior if boundsHitMode has wrap mode.
"},{"location":"bounds/#target-game-object","title":"Target game object","text":"
  • Set
    bounds.setBoundsTarget(gameObject);\n// bounds.boundsTarget = gameObject;\n
  • Clear
    bounds.setBoundsTarget();\n// bounds.boundsTarget = undefined;\n
  • Get
    var gameObject = bounds.boundsTarget;\n
"},{"location":"bounds/#target-bounds","title":"Target bounds","text":"
  • Set
    bounds.setBounds(bounds);\n
    • bounds : Target bounds used when target is not a game object.
      • A rectangle
      • An object :
        {\nwidth: 0, height: 0,\nx: 0, y: 0,\ncenterX: 0, centerY: 0,            }\n
        • width, height : Size of target bounds.
        • x, y, or centerX, centerY : Position of target bounds.
  • Get
    var rect = bounds.bounds;\n
    • rect : A rectangle object
"},{"location":"bounds/#enable","title":"Enable","text":"
  • Set
    • Enable all bounds
      bounds.setEnable();\n//  bounds.setEnable(true);\n
    • Disable all bounds
      bounds.setEnable(false);\n
    • Enable bounds via object
      bounds.setEnable({\nleft: true,\nright: true,\ntop: true,\nbottom: true\n});\n
  • Get
    var enable = bounds.enable;\n
    • true : Has any enabled bounds
    • false : All bounds are disabled.
  • Get enabled of a bound
    var enableLeftBound = bounds.boundsEnable.left;\nvar enableRightBound = bounds.boundsEnable.right;\nvar enableTopBound = bounds.boundsEnable.top;\nvar enableBottomBound = bounds.boundsEnable.bottom;\n
"},{"location":"bounds/#bound-hit-mode","title":"Bound hit mode","text":"
  • Set
    bounds.setBoundsHitMode(mode);\n
    • 0, or 'clamp' : Clamp game object's position when game object overlap left/right/top/bottom bounds.
    • 1, or 'wrap' : Wrap game object's position when game object overlap left/right/top/bottom bounds.
    • An objecct : Set 0/'clamp', or 1/'wrap' to clamp or wrap game object's position at a bound
      {\nleft: 0,   // 0,'clamp',1,'wrap'\nright: 0,  // 0,'clamp',1,'wrap'\ntop: 0,    // 0,'clamp',1,'wrap'\nbottom: 0  // 0,'clamp',1,'wrap'\n}\n
  • Get
    var leftBoundHitMode = bounds.boundsHitMode.left;\nvar rightBoundHitMode = bounds.boundsHitMode.right;\nvar topBoundHitMode = bounds.boundsHitMode.top;\nvar bottomBoundHitMode = bounds.boundsHitMode.bottom;\n
"},{"location":"bounds/#align-mond","title":"Align mond","text":"
  • Set
    bounds.setAlignMode(mode);\n
    • 0, or 'bounds' : Align bounds of game object to target bound.
    • 1, or 'origin' : Set position of game object to target bound.
  • Get
    var alignMode = bounds.alignMode;\n
    • 0 : Align bounds of game object to target bound.
    • 1 : Set position of game object to target bound.
"},{"location":"bounds/#hit-result","title":"Hit result","text":"
  • Game object is hitting any bound
    var isHitAny = bounds.isHitAny;\n
  • Game object is hitting a bound
    var isHitLeft = this.isHitLeft;\nvar isHitRight = this.isHitRight;\nvar isHitTop = this.isHitTop;\nvar isHitBottom = this.isHitBottom;\n
"},{"location":"bounds/#event","title":"Event","text":"
  • On hit any bound
    bounds.on('hitany', function(gameObject, bounds) {\n\n})\n
  • On hit left bound
    bounds.on('hitleft', function(gameObject, bounds) {\n\n})\n
  • On hit right bound
    bounds.on('hitright', function(gameObject, bounds) {\n\n})\n
  • On hit top bound
    bounds.on('hittop', function(gameObject, bounds) {\n\n})\n
  • On hit bottom bound
    bounds.on('hitbottom', function(gameObject, bounds) {\n\n})\n
"},{"location":"bracketparser/","title":"Bracket parser","text":""},{"location":"bracketparser/#introduction","title":"Introduction","text":"

A lite-weight delimiter parser.

  • Author: Rex
  • Object
"},{"location":"bracketparser/#live-demoes","title":"Live demoes","text":"
  • Basic
  • Markup text
"},{"location":"bracketparser/#usage","title":"Usage","text":"

Sample code

"},{"location":"bracketparser/#install-plugin","title":"Install plugin","text":""},{"location":"bracketparser/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbracketparserplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbracketparserplugin.min.js', true);\n
  • Add parser object
    var parser = scene.plugins.get('rexbracketparserplugin').add(config);\n
"},{"location":"bracketparser/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BracketParserPlugin from 'phaser3-rex-plugins/plugins/bracketparser-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBracketParser',\nplugin: BracketParserPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add parser object
    var parser = scene.plugins.get('rexBracketParser').add(config);\n
"},{"location":"bracketparser/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import BracketParser from 'phaser3-rex-plugins/plugins/bracketparser.js';\n
  • Add parser object
    var parser = new BracketParser(config);\n
"},{"location":"bracketparser/#create-instance","title":"Create instance","text":"
var parser = scene.plugins.get('rexBracketParser').add({\n// delimiters: '<>', // or ['<', '>']\n// valueConvert: true,\n// translateTagNameCallback: undefined,\n});\n
  • delimiters: String of left-delimiter and right-delimiter.
    • A single string with 2 characters. Default value is '<>'.
    • A array with 2 strings
  • valueConvert : A callback to convert values.
    • true : Use defaule value converter. Values will be converted to number (include hex number string like '0xFF'), boolean, null, or string.
    • false, or null : Bypass string value.
    • Function object:
      function(s) {\nreturn s;\n}\n
  • translateTagNameCallback : Callback to translate tag-name
    • undefined : Use original tag-name. Default behavior.
    • A function, return new tag name.
      function(tagName) {\nreturn newTagName;\n}\n
"},{"location":"bracketparser/#tag-and-content","title":"Tag and content","text":"

Assume that left-delimiter and right-delimiter is '<>'

  • Start-tag : '<TAG>'
    • Start-tag with a single value : '<TAG=value>'
      • value : If valueConvert is true,
        • Number
        • Boolean
        • null
        • String
    • Start-tag with array values, separated via ',' : '<TAG=value0,value1,value2>'
  • End-tag : '<\\TAG>'
  • Content : Any string outside of tag-start, or tag-end.
"},{"location":"bracketparser/#start-parsing","title":"Start parsing","text":"
parser.start(text);\n

These events will be emitted under this method.

"},{"location":"bracketparser/#pause","title":"Pause","text":"
  • Pause
    parser.pause();\n
  • Pause until event
    parser.pauseUntilEvent(eventEmitter, eventName);\n
    • Will invoke
      eventEmitter.once(eventName, function() {\nparser.next();\n})\n

Invoke this method during tag-start,tag-end, or content events to suspend parsing.

"},{"location":"bracketparser/#resume","title":"Resume","text":"
parser.next();\n
"},{"location":"bracketparser/#skip-any-tag-startany-tag-end-event","title":"Skip any-tag-start/any-tag-end event","text":"
parser.skipEvent();\n

When getting a tag-start, or a tag-end event, parser will emitts

  • Start-tag : '+TAG', then '+'
  • End-tag : '-TAG', then '-'

Invoke this medthod under '+TAG', or '-TAG' event to skip '+', or '-' event.

"},{"location":"bracketparser/#status","title":"Status","text":"
  • Is parsing
    var isRunning = parser.isRunning;\n
    • true : Has remainder characters
    • false : After parsing last character
  • Is paused
    var isPaused = parser.isPaused;\n
"},{"location":"bracketparser/#events","title":"Events","text":""},{"location":"bracketparser/#tagscontent","title":"Tags/Content","text":"
  • Get a specific tag-start
    • Start-tag with a single value : '<TAG=value>'
      parser.on('+' + TagName, function(value){ /* ... */ });\n
    • Start-tag with array values, separated via ',' : '<TAG=value0,value1,value2>'
      parser.on('+' + TagName, function(value0, value1, value2){ /* ... */ });\n
  • Get any-tag-start
    • Start-tag with a single value : '<TAG=value>'
      parser.on('+', function(tagName, value){ /* ... */ });\n
    • Start-tag with array values, separated via ',' : '<TAG=value0,value1,value2>'
      parser.on('+', function(tagName, value0, value1, value2){ /* ... */ });\n
  • Get a specific tag-end
    parser.on('-' + TagName, function(){ /* ... */ });\n
  • Get a content
    parser.on('content', function(content){ /* ... */ });\n
    • Previous tag-start : parser.lastTagStart
  • Get any-tag-end
    parser.on('-', function(tagName){ /* ... */ });\n
    • Previous tag-start : parser.lastTagStart
    • Previous Content : parser.lastContent
"},{"location":"bracketparser/#control-flow","title":"Control flow","text":"
  • Parsing start
    parser.on('start', function(){ /* ... */ });\n
  • Parsing end
    parser.on('complete', function(){ /* ... */ });\n
  • On pause
    parser.on('pause', function(){ /* ... */ });\n
  • On resume
    parser.on('resume', function(){ /* ... */ });\n
"},{"location":"bracketparser2/","title":"Bracket parser 2","text":""},{"location":"bracketparser2/#introduction","title":"Introduction","text":"

A lite-weight delimiter parser.

  • Author: Rex
  • Object
"},{"location":"bracketparser2/#live-demoes","title":"Live demoes","text":"
  • Basic
"},{"location":"bracketparser2/#usage","title":"Usage","text":"

Sample code

"},{"location":"bracketparser2/#install-plugin","title":"Install plugin","text":""},{"location":"bracketparser2/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbracketparser2plugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbracketparser2plugin.min.js', true);\n
  • Add parser object
    var parser = scene.plugins.get('rexbracketparser2plugin').add(config);\n
"},{"location":"bracketparser2/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BracketParserPlugin from 'phaser3-rex-plugins/plugins/bracketparser2-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBracketParser',\nplugin: BracketParserPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add parser object
    var parser = scene.plugins.get('rexBracketParser').add(config);\n
"},{"location":"bracketparser2/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import BracketParser from 'phaser3-rex-plugins/plugins/bracketparser2.js';\n
  • Add parser object
    var parser = new BracketParser(config);\n
"},{"location":"bracketparser2/#create-instance","title":"Create instance","text":"
var parser = scene.plugins.get('rexBracketParser').add({\n// delimiters: '<>', // or ['<', '>']\n// valueConvert: true,\n// translateTagNameCallback: undefined,\n});\n
  • delimiters: String of left-delimiter and right-delimiter.
    • A single string with 2 characters. Default value is '<>'.
    • A array with 2 strings
  • valueConvert : A callback to convert values.
    • true : Use defaule value converter. Values will be converted to number (include hex number string like '0xFF'), boolean, null, or string.
    • false, or null : Bypass string value.
    • Function object:
      function(s) {\nreturn s;\n}\n
  • translateTagNameCallback : Callback to translate tag-name
    • undefined : Use original tag-name. Default behavior.
    • A function, return new tag name.
      function(tagName) {\nreturn newTagName;\n}\n
"},{"location":"bracketparser2/#tag-and-content","title":"Tag and content","text":"

Assume that left-delimiter and right-delimiter is '<>'

  • Start-tag : <TAG>
  • Start-tag with payload :
    <TAG param0=value0 param1=value1>\n
    or
    <\n    TAG\n    param0=value0 \n    param1=value1\n>\n
    • payload will be {param0:value0, param1:value1}
    • value : If valueConvert is true,
      • String with '...', or \"...\"
      • JSON array with [...]
      • JSON object with {...}
      • Number
      • Boolean
      • null
      • String
  • End-tag : <\\TAG>
  • End-tag with payload
    <\\TAG param0=value0 param1=value1>\n
    or
    <\n    \\TAG\n    param0=value0 \n    param1=value1\n>\n
    • payload will be {param0:value0, param1:value1}
    • value : If valueConvert is true,
      • String with '...', or \"...\"
      • JSON array with [...]
      • JSON object with {...}
      • Number
      • Boolean
      • null
      • String
  • Content : Any string outside of tag-start, or tag-end.
"},{"location":"bracketparser2/#start-parsing","title":"Start parsing","text":"
parser.start(text);\n

These events will be emitted under this method.

"},{"location":"bracketparser2/#pause","title":"Pause","text":"
  • Pause
    parser.pause();\n
  • Pause until event
    parser.pauseUntilEvent(eventEmitter, eventName);\n
    • Will invoke
      eventEmitter.once(eventName, function() {\nparser.next();\n})\n

Invoke this method during tag-start,tag-end, or content events to suspend parsing.

"},{"location":"bracketparser2/#resume","title":"Resume","text":"
parser.next();\n
"},{"location":"bracketparser2/#skip-any-tag-startany-tag-end-event","title":"Skip any-tag-start/any-tag-end event","text":"
parser.skipEvent();\n

When getting a tag-start, or a tag-end event, parser will emitts

  • Start-tag : '+TAG', then '+'
  • End-tag : '-TAG', then '-'

Invoke this medthod under '+TAG', or '-TAG' event to skip '+', or '-' event.

"},{"location":"bracketparser2/#status","title":"Status","text":"
  • Is parsing
    var isRunning = parser.isRunning;\n
    • true : Has remainder characters
    • false : After parsing last character
  • Is paused
    var isPaused = parser.isPaused;\n
"},{"location":"bracketparser2/#events","title":"Events","text":""},{"location":"bracketparser2/#tagscontent","title":"Tags/Content","text":"
  • Get a specific tag-start
    • Start-tag with payload : '<TAG param0=value0 param1=value1>'
      parser.on('+' + TagName, function(payload){ /* ... */ });\n
      • payload : {param0:value0, param1:value1, ...}
  • Get any-tag-start
    • Start-tag with payload : '<TAG param0=value0 param1=value1>'
      parser.on('+', function(tagName, payload){ /* ... */ });\n
      • payload : {param0:value0, param1:value1, ...}
  • Get a specific tag-end
    • End-tag with payload : '<\\TAG param0=value0 param1=value1>'
      parser.on('-' + TagName, function(payload){ /* ... */ });\n
      • payload : {param0:value0, param1:value1, ...}
  • Get a content
    parser.on('content', function(content){ /* ... */ });\n
    • Previous tag-start : parser.lastTagStart
      {\nname: '',\npayload: {}\n}\n
  • Get any-tag-end
    • End-tag with payload : '<TAG param0=value0 param1=value1>'
      parser.on('-', function(tagName, payload){ /* ... */ });\n
      • payload : {param0:value0, param1:value1, ...}
    • Previous tag-start : parser.lastTagStart
      {\nname: '',\npayload: {}\n}\n
    • Previous Content : parser.lastContent
"},{"location":"bracketparser2/#control-flow","title":"Control flow","text":"
  • Parsing start
    parser.on('start', function(){ /* ... */ });\n
  • Parsing end
    parser.on('complete', function(){ /* ... */ });\n
  • On pause
    parser.on('pause', function(){ /* ... */ });\n
  • On resume
    parser.on('resume', function(){ /* ... */ });\n
"},{"location":"bracketparser2/#compare-with-bracket-parser","title":"Compare with bracket-parser","text":"

Tag format in

  • bracket-parser:
    <TAG=value0,value1>\n
    • Carried parameters is an array, more compactly.
  • bracket-parser2:
    <TAG param0=value0 param1=value1>\n
    or
    <\n  TAG \n    param0=value0 \n    param1=value1\n>\n
    • Carried parameters is a dictionary, more clearly.
"},{"location":"buffdata/","title":"Buff data","text":""},{"location":"buffdata/#introduction","title":"Introduction","text":"

Data manager with buffs, extends from built-in data manager.

  • Author: Rex
  • Member of scene
"},{"location":"buffdata/#usage","title":"Usage","text":"

Sample code

"},{"location":"buffdata/#install-plugin","title":"Install plugin","text":""},{"location":"buffdata/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbuffdataplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbuffdataplugin.min.js', true);\n
  • Add buff data manager object
    var data = scene.plugins.get('rexbuffdataplugin').add(parent);\n
"},{"location":"buffdata/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BuffDataPlugin from 'phaser3-rex-plugins/plugins/buffdata-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBuffData',\nplugin: BuffDataPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add buff data manager object
    var data = scene.plugins.get('rexBuffData').add(parent);\n
"},{"location":"buffdata/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import BuffData from 'phaser3-rex-plugins/plugins/buffdata.js';\n
  • Add buff data manager object
    var data = new BuffData(parent);\n
"},{"location":"buffdata/#create-instance","title":"Create instance","text":"
var data = scene.plugins.get('rexBuffData').add(parent);\n// var data = scene.plugins.get('rexBuffData').add(parent, eventEmitter);\n
  • data : Buff data manager
  • parent : The object (a scene, or a game object) that this DataManager belongs to.
  • eventEmitter : The DataManager's event emitter.
"},{"location":"buffdata/#extend-existing-data-manager","title":"Extend existing data manager","text":"
var data = scene.plugins.get('rexBuffData').extend(data);\n
  • data : Existing data manager
"},{"location":"buffdata/#buff","title":"Buff","text":"

A value is composed of baseValue, and some buffs, clamped by min, max values.

  • Base value

    • Set
      data.setBaseValue(key, value);\n
    • Remove
      data.removeBaseValue(key);\n
    • Get
      var baseValue = data.getBaseValue(key);\n
  • Buffs, each value can have many buffs, or no buff.

    • Add/set a buff
      data.setBuff(key, buffKey, value);\n
      • value :
        • A number
        • A string for percentage like '10%', which means that (baseValue * percentage)
    • Remove a buff of a key
      data.removeBuff(key, buffKey);\n
    • Remove all buffs of a key
      data.removeBuff(key);\n
    • Get a buff value
      var buffValue = data.getBuffValue(key, buffKey);\n
  • Min, max bounds, optional.
    • Set
      data.setMin(key, min);\n
      data.setMax(key, max);\n
      data.setBounds(key, min, max);\n
      • min, max : Clamp buffed result value between min and max value. Set undefined to ignore it.
    • Get
      var min = data.getMinBound(key);\nvar max = data.getMaxBound(key);\n
  • Buffed result
    • Get
      var result = data.get(key);\n
    • Events
"},{"location":"buildarcadeobject/","title":"Build arcade object","text":""},{"location":"buildarcadeobject/#introduction","title":"Introduction","text":"

Create arcade body, and inject arcade object methods.

  • Author: Rex
  • Arcade behavior of game object
"},{"location":"buildarcadeobject/#usage","title":"Usage","text":"

Sample code

"},{"location":"buildarcadeobject/#install-plugin","title":"Install plugin","text":""},{"location":"buildarcadeobject/#load-minify-file","title":"Load minify file","text":"
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbuildarcadeobjectplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbuildarcadeobjectplugin.min.js', true);\n
  • Inject arcade object methods
    var gameObject = scene.plugins.get('rexbuildarcadeobjectplugin').build(gameObject);\n
"},{"location":"buildarcadeobject/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine and install plugin in configuration of game
    import BuildArcadeObjectPlugin from 'phaser3-rex-plugins/plugins/buildarcadeobject-plugin.js';\nvar config = {\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBuildArcadeObject',\nplugin: BuildArcadeObjectPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Inject arcade object methods
    var gameObject = scene.plugins.get('rexBuildArcadeObject').build(gameObject);\n
"},{"location":"buildarcadeobject/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Import class
    import BuildArcadeObject from 'phaser3-rex-plugins/plugins/buildarcadeobject.js';\n
  • Inject arcade object methods
    var gameObject = BuildArcadeObject(gameObject);\n
"},{"location":"buildarcadeobject/#inject-arcade-object-methods","title":"Inject arcade object methods","text":"
  • Inject arcade method to game object
    scene.plugins.get('rexBuildArcadeObject').injectMethods(gameObject);\n// scene.physics.add.existing(gameObject);        // Dynamic arcade body\n// scene.physics.add.existing(gameObject, true);  // Static arcade body\n
  • Inject arcade method to game object class
    scene.plugins.get('rexBuildArcadeObject').injectMethods(GameObjectClass.prototype);\n
  • Inject arcade method to root of all game object class
    scene.plugins.get('rexBuildArcadeObject').injectMethodsToRootClass();\n
  • Create dynamic arcade body
    var gameObject = scene.plugins.get('rexBuildArcadeObject').build(gameObject);\n// var gameObjects = scene.plugins.get('rexBuildArcadeObject').build(gameObjects);\n
  • Create static arcade body
    var gameObject = scene.plugins.get('rexBuildArcadeObject').build(gameObject, true);\n// var gameObjects = scene.plugins.get('rexBuildArcadeObject').build(gameObjects, true);\n
"},{"location":"bullet/","title":"Bullet","text":""},{"location":"bullet/#introduction","title":"Introduction","text":"

Move game object toward current angle of game object, with a constant speed.

  • Author: Rex
  • Arcade behavior of game object
"},{"location":"bullet/#usage","title":"Usage","text":"

Sample code

"},{"location":"bullet/#install-plugin","title":"Install plugin","text":""},{"location":"bullet/#load-minify-file","title":"Load minify file","text":"
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbulletplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbulletplugin.min.js', true);\n
  • Add bullet behavior
    var bullet = scene.plugins.get('rexbulletplugin').add(gameObject, config);\n
"},{"location":"bullet/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine and install plugin in configuration of game
    import BulletPlugin from 'phaser3-rex-plugins/plugins/bullet-plugin.js';\nvar config = {\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBullet',\nplugin: BulletPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add bullet behavior
    var bullet = scene.plugins.get('rexBullet').add(gameObject, config);\n
"},{"location":"bullet/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Import class
    import Bullet from 'phaser3-rex-plugins/plugins/bullet.js';\n
  • Add bullet behavior
    var bullet = new Bullet(gameObject, config);\n
"},{"location":"bullet/#create-instance","title":"Create instance","text":"
var bullet = scene.plugins.get('rexBullet').add(gameObject, {\nspeed: 200,\n// wrap: false,\n// padding: 0,\n// enable: true,\n\n// angle: undefined,\n// rotation: undefined\n});\n
  • speed : moving speed, pixels in second.
  • Wrap
    • wrap : Set true to enable wrap mode. Default value is false.
    • padding
  • enable : set false to disable moving.
  • angle, rotation :
    • undefined : Use angle of game object as angle of bullet. Default value.
    • A number : Angle of bullet, in degrees or radians.
"},{"location":"bullet/#speed","title":"Speed","text":"
  • Set
    bullet.setSpeed(speed);\n// bullet.speed = speed;\n
  • Get
    var speed = bullet.speed;\n
"},{"location":"bullet/#set-wrap-mode","title":"Set wrap mode","text":"
bullet.setWrapMode(wrap, padding);\n
  • wrap : Set true to enable wrap mode.
"},{"location":"bullet/#angle","title":"Angle","text":"
  • Set angle
    bullet.setAngle(degrees);\n// bullet.angle = degrees;\n
    or
    bullet.setRotation(radians);\n// bullet.rotation  = radians;\n
  • Use angle of game object
    bullet.setAngle();\n// bullet.setRotation();\n
"},{"location":"button/","title":"Click/Button","text":""},{"location":"button/#introduction","title":"Introduction","text":"

Fires 'click' event when touch releasd after pressed.

  • Author: Rex
  • Behavior of game object
"},{"location":"button/#usage","title":"Usage","text":"

Sample code

"},{"location":"button/#install-plugin","title":"Install plugin","text":""},{"location":"button/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbuttonplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbuttonplugin.min.js', true);\n
  • Add button behavior
    var button = scene.plugins.get('rexbuttonplugin').add(gameObject, config);\n
"},{"location":"button/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ButtonPlugin from 'phaser3-rex-plugins/plugins/button-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexButton',\nplugin: ButtonPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add button behavior
    var button = scene.plugins.get('rexButtonn').add(gameObject, config);\n
"},{"location":"button/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Button from 'phaser3-rex-plugins/plugins/button.js';\n
  • Add button behavior
    var button = new Button(gameObject, config);\n
"},{"location":"button/#create-instance","title":"Create instance","text":"
var button = scene.plugins.get('rexButton').add(gameObject, {\n// enable: true,\n// mode: 1,              // 0|'press'|1|'release'\n// clickInterval: 100    // ms\n// threshold: undefined\n});\n
  • enable : Clickable.
  • mode :
    • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
    • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
  • clickInterval : Interval between 2 'click' events, in ms.
  • threshold : Cancel clicking detecting when dragging distance is larger then this threshold.
    • undefined : Ignore this feature. Default behavior.
"},{"location":"button/#events","title":"Events","text":"
  • Click
    button.on('click', function (button, gameObject, pointer, event) {\n// ...\n}, scope);\n
    • Cancel remaining touched events : event.stopPropagation()
  • Enable
    button.on('enable', function (button, gameObject) {\n// ...\n}, scope);\n
  • Disable
    button.on('disable', function (button, gameObject) {\n// ...\n}, scope);\n
  • Pointer over
    button.on('over', function (button, gameObject, pointer, event) {\n// ...\n}, scope);\n
  • Pointer out
    button.on('out', function (button, gameObject, pointer, event) {\n// ...\n}, scope);\n
  • Pointer down
    button.on('down', function (button, gameObject, pointer, event) {\n// ...\n}, scope);\n
  • Pointer up
    button.on('up', function (button, gameObject, pointer, event) {\n// ...\n}, scope);\n
"},{"location":"button/#enable","title":"Enable","text":"
  • Get
    var enabled = button.enable;  // enabled: true, or false\n
  • Set
    button.setEnable(enabled);  // enabled: true, or false\n// button.enable = enabled;\n
  • Toggle
    button.toggleEnable();\n
"},{"location":"button/#set-mode","title":"Set mode","text":"
button.setMode(mode);\n
  • mode :
    • 'press', or 0 : Fire 'click' event when touch pressed.
    • 'release', or 1 : Fire 'click' event when touch released after pressed.
"},{"location":"button/#set-click-interval","title":"Set click interval","text":"
button.setClickInterval(interval);  // interval in ms\n
"},{"location":"button/#set-dragging-threshold","title":"Set dragging threshold","text":"
button.setDragThreshold(distance);  // distance in pixels\n
"},{"location":"camera-controller/","title":"Controller","text":""},{"location":"camera-controller/#introduction","title":"Introduction","text":"

Scroll/zoom camera.

  • Author: Richard Davey
"},{"location":"camera-controller/#usage","title":"Usage","text":""},{"location":"camera-controller/#setup","title":"Setup","text":"
  1. Create controllor
    // var cursors = scene.input.keyboard.createCursorKeys();\nvar controls = new Phaser.Cameras.Controls.SmoothedKeyControl({\ncamera: camera,\n\nleft: cursors.left,    // { isDown, isUp }\nright: cursors.right,  // { isDown, isUp }\nup: cursors.up,        // { isDown, isUp }\ndown: cursors.down,    // { isDown, isUp }\nzoomIn: null,          // { isDown, isUp }\nzoomOut: null,         // { isDown, isUp }\n\nzoomSpeed: 0.01,\nminZoom: 0.001,\nmaxZoom: 1000,\n\nacceleration: null,\n// acceleration: {\n//    x: 0,\n//    y: 0\n// }\n\ndrag: null,\n// drag: {\n//    x: 0,\n//    y: 0\n// }\n\nmaxSpeed: null\n// maxSpeed: {\n//    x: 0,\n//    y: 0\n// }\n});\n
    or
    var controls = new Phaser.Cameras.Controls.FixedKeyControl(config);\n
  2. Update
    scene.update = function (time, delta) {\ncontrols.update(delta);\n}\n
"},{"location":"camera-controller/#other-methods","title":"Other methods","text":"
  • Start
    controls.start();\n
  • Stop
    controls.stop();\n
  • Set camera
    controls.setCamera(camera);\n
"},{"location":"camera-effects/","title":"Effects","text":""},{"location":"camera-effects/#introduction","title":"Introduction","text":"

Effects of camera.

  • Author: Richard Davey
"},{"location":"camera-effects/#usage","title":"Usage","text":""},{"location":"camera-effects/#fade","title":"Fade","text":"
  • Fades the Camera in, from the given color over the duration specified.
    camera.fadeIn(duration);   // duration in ms\n// camera.fadeIn(duration, red, green, blue, callback, context);\n// red/green/blue: the value to fade the red/green/blue channel from. A value between 0 and 255.\n
    • callback , context : It will be invoked every frame for the duration of the effect.
      function(camera, progress) {}\n
  • Fades the Camera out, to the given color over the duration specified.
    camera.fadeOut(duration);   // duration in ms\n// camera.fadeOut(duration, red, green, blue, callback, context);\n
    • callback , context : It will be invoked every frame for the duration of the effect.
      function(camera, progress) {}\n
  • Fades the Camera, from the given color to transparent over the duration specified.
    camera.fadeFrom(duration);   // duration in ms\n// camera.fadeFrom(duration, red, green, blue, force, callback, context);\n
    • force : Force the effect to start immediately, even if already running.
    • callback , context : It will be invoked every frame for the duration of the effect.
      function(camera, progress) {}\n
  • Fades the Camera, from transparent to the given color over the duration specified.
    camera.fade(duration);   // duration in ms\n// camera.fade(duration, red, green, blue, force, callback, context);\n
    • force : Force the effect to start immediately, even if already running.
    • callback , context : It will be invoked every frame for the duration of the effect.
      function(camera, progress) {}\n
"},{"location":"camera-effects/#events","title":"Events","text":"
camera.on('camerafadeincomplete', camera, fade);\n
camera.on('camerafadeoutcomplete', camera, fade);\n
"},{"location":"camera-effects/#flash","title":"Flash","text":"
camera.flash(duration);   // duration in ms\n// camera.flash(duration, red, green, blue, force, callback, context);\n
  • callback , context : It will be invoked every frame for the duration of the effect.
    function(camera, progress) {}\n
"},{"location":"camera-effects/#events_1","title":"Events","text":"
camera.on('cameraflashstart', camera, flash, duration, red, green, blue);\n
camera.on('cameraflashcomplete', camera, flash);\n
"},{"location":"camera-effects/#shake","title":"Shake","text":"
camera.shake(duration);   // duration in ms\n// camera.shake(duration, intensity, force, callback, context);  // callback: invoked when completed\n
  • callback , context : It will be invoked every frame for the duration of the effect.
    function(camera, progress) {}\n
"},{"location":"camera-effects/#events_2","title":"Events","text":"
camera.on('camerashakestart', camera, shake, duration, intensity);\n
camera.on('camerashakecomplete', camera, shake);\n
"},{"location":"camera-effects/#pan","title":"Pan","text":"
camera.pan(x, y, duration);   // duration in ms\n// camera.pan(x, y, duration, ease, force, callback, context);\n
  • x, y : The destination x/y coordinate to scroll the center of the Camera viewport to.
  • callback , context : It will be invoked every frame for the duration of the effect.
    function(camera, progress, x, y) {}\n
"},{"location":"camera-effects/#events_3","title":"Events","text":"
camera.on('camerapanstart', camera, pan, duration, x, y);\n
camera.on('camerapancomplete', camera, pan);\n
"},{"location":"camera-effects/#zoom","title":"Zoom","text":"
camera.zoomTo(zoomValue, duration);   // duration in ms\n// camera.zoomTo(zoomValue, duration, ease, force, callback, context);\n
  • callback , context : It will be invoked every frame for the duration of the effect.
    function(camera, progress, zoomValue) {}\n
"},{"location":"camera-effects/#events_4","title":"Events","text":"
camera.on('camerazoomstart', camera, zoom, duration, zoomValue);\n
camera.on('camerazoomcomplete', camera, zoom);\n
"},{"location":"camera-effects/#rotate-to","title":"Rotate to","text":"
camera.rotateTo(radians, shortestPath, duration);   // duration in ms\n// camera.rotateTo(radians, shortestPath, duration, ease, force, callback, context);\n
  • callback , context : It will be invoked every frame for the duration of the effect.
    function(camera, progress, angle) {}\n
"},{"location":"camera-effects/#events_5","title":"Events","text":"
camera.on('camerarotatestart', camera, rotateTo, duration, angle);\n
camera.on('camerarotatecomplete', camera, rorotateTotate);\n
"},{"location":"camera-effects/#mask","title":"Mask","text":"
  • Add mask
    camera.setMask(mask);\n
  • Clear mask
    camera.clearMask();\n

More detail about mask

"},{"location":"camera-shader-effect/","title":"Shader effect","text":""},{"location":"camera-shader-effect/#introduction","title":"Introduction","text":"

Shader effect of camera.

  • Author: Richard Davey
"},{"location":"camera-shader-effect/#usage","title":"Usage","text":""},{"location":"camera-shader-effect/#register-post-fx-pipeline","title":"Register post-fx pipeline","text":"
  • Register post-fx pipeline in game config
    import PostFxClass from 'path';\nvar config = {\n// ...\npipeline: [PostFxClass]\n// ...\n};\nvar game = new Phaser.Game(config);\n

Some post-fx pipelines:

  • Barrel: Barrel post processing filter.
  • Color replace: Replace color post processing filter.
  • Cross-stitching: Cross-stitching post processing filter.
  • CRT: CRT post processing filter.
  • Dissolve: Dissolve transition post processing filter.
  • Fish eye: Fish-eye post processing filter.
  • Glow-filter: Glow post processing filter.
  • Glow-filter: Glow post processing filter, ported from pixi.
  • Gray-scale: Gray scale post processing filter.
  • Hsl-adjust: Adjust color in HSL domain, post processing filter.
  • Horri-fi: 6-in-1 post processing filter.
  • Inverse: Inverse color post processing filter.
  • Kawase-blur: Kawase-blur post processing filter.
  • Pixelation: Pixelation post processing filter.
  • Toonify: Draw outlines and quantize color in HSV domain, post processing filter.
  • Shockwave: Shockwave post processing filter.
  • Split: Split image into 4 parts.
  • Swirl: Swirl post processing filter.
  • Warp: Warp post processing filter.
"},{"location":"camera-shader-effect/#add-post-fx-pipeline","title":"Add post-fx pipeline","text":"
camera.setPostPipeline(PostFxClass);\n
  • PostFxClass : Class of post-fx pipeline.
"},{"location":"camera-shader-effect/#remove-post-fx-pipeline","title":"Remove post-fx pipeline","text":"
  • Remove a kind of post-fx pipeline
    camera.removePostPipeline(PostFxClass);\n
  • Remove all post-fx pipelines
    camera.resetPipeline(true);\n
    or
    camera.postPipelines = [];\ncamera.hasPostPipeline = false;\n
"},{"location":"camera-shader-effect/#get-post-fx-pipeline","title":"Get post-fx pipeline","text":"
var pipelineInstance = camera.getPostPipeline(PostFxClass);\n
  • pipelineInstance :
    • A pipeline instance
    • An array of pipeline instances
"},{"location":"camera-shader-effect/#add-effect-properties","title":"Add effect properties","text":"

See Add effect properties behavior

"},{"location":"camera/","title":"Camera","text":""},{"location":"camera/#introduction","title":"Introduction","text":"

Camera to display game objects, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"camera/#usage","title":"Usage","text":""},{"location":"camera/#get-camera","title":"Get camera","text":"

Each scene has one or more cameras.

  • Main camera
    var camera = scene.cameras.main;\n
  • Get camera by name
    var camera = scene.cameras.getCamera(name);\n
  • Add new camera
    var camera = scene.cameras.add();\n// var camera = scene.cameras.add(x, y, width, height);\n
  • Add new camera with name
    var camera = scene.cameras.add(undefined, undefined, undefined, undefined, false, name);\n// var camera = scene.cameras.add(x, y, width, height, makeMain, name);\n
  • Add existed camera
    scene.cameras.addExisting(camera);\n
"},{"location":"camera/#create-cameras-from-json","title":"Create cameras from JSON","text":"
scene.cameras.fromJSON(config);\n// scene.cameras.fromJSON(configArray);\n
  • config :
    {\nname: '',\nx: 0,\ny: 0,\nwidth: scene.sys.scale.width,\nheight: scene.sys.scale.height,\nzoom: 1,\nrotation: 0,\nscrollX: 0,\nscrollY: 0,\nroundPixels: false,\nvisible: true,\nbackgroundColor: false,\nbounds: null, // {x, y, width, height}\n}\n
"},{"location":"camera/#remove-camera","title":"Remove camera","text":"
scene.cameras.remove(camera);\n
"},{"location":"camera/#destroy-camera","title":"Destroy camera","text":"
camera.destroy();\n
"},{"location":"camera/#view-port","title":"View port","text":"
  • Set
    camera.setViewport(top, left, width, height);\n
    or
    camera.setPosition(top, left);\n// camera.x = top;\n// camera.y = left;\n
    camera.setSize(width, height);\n// camera.width = width;\n// camera.height = height;\n
  • Get
    • Position
      • Top-left
        var top = camera.x;\nvar left = camera.y;\n
      • Center, relative to the top-left of the game canvas.
        var x = camera.centerX;\nvar y = camera.centerY;\n
    • Width & height
      var width = camera.width;\nvar height = camera.height;\n
      var displayWidth = camera.displayWidth;\nvar displayHeight = camera.displayHeight;\n
"},{"location":"camera/#zoom","title":"Zoom","text":"
  • Set
    camera.setZoom(zoomValue);  // The minimum it can be is 0.001.\ncamera.zoom = zoomValue;\n
  • Get
    var zoomValue = camera.zoom;\n
"},{"location":"camera/#rotation","title":"Rotation","text":"
  • Set
    camera.setAngle(angle);  // angle in degree\ncamera.setRotation(angle);  // angle in radians\ncamera.rotation = angle; // angle in radians\n
  • Get
    var angle = camera.rotation;  // angle in radians\n
"},{"location":"camera/#origin","title":"Origin","text":"
  • Set
    camera.setOrigin(x, y);\n// camera.originX = 0.5;\n// camera.originY = 0.5;\n
  • Get
    var originX = camera.originX\nvar originY = camera.originY\n
"},{"location":"camera/#visible","title":"Visible","text":"

A visible camera will render and perform input tests. An invisible camera will not render anything and will skip input tests.

camera.setVisible(value);\n// camera.visible = value\n
var visible = camera.visible;\n
"},{"location":"camera/#alpha","title":"Alpha","text":"
camera.setAlpha(value);\n// camera.alpha = value;\n
var alpha = camera.alpha;\n
"},{"location":"camera/#scroll","title":"Scroll","text":"
camera.setScroll(x, y)\n
camera.scrollX = scrollX;\ncamera.scrollY = scrollY;\n
camera.centerToBounds();\n
camera.centerOn(x, y);  // centered on the given coordinates\n
camera.centerOnX(x);\ncamera.centerOnY(y);\n
camera.centerToSize();\n
"},{"location":"camera/#follow-game-object","title":"Follow game object","text":"
  • Start following
    camera.startFollow(gameObject);\n// camera.startFollow(gameObject, roundPx, lerpX, lerpY, offsetX, offsetY);  // \n
    • roundPx : set true to round the camera position to integers
    • lerpX, lerpY : A value between 0 and 1.
      • 1 : Camera will instantly snap to the target coordinates.
      • 0.1 : Camera will more slowly track the target, giving a smooth transition.
    • offsetX, offsetY : The horizontal/vertical offset from the camera follow target.x position.
  • Stop following
    camera.stopFollow();\n
  • Set follow offset
    camera.setFollowOffset(x, y);\n
  • Set lerp
    camera.setLerp(x, y);\n
    • 1 : Camera will instantly snap to the target coordinates.
    • 0.1 : Camera will more slowly track the target, giving a smooth transition.
  • Deadzone
    camera.setDeadzone(width, height);\n
    If the target moves outside of this area, the camera will begin scrolling in order to follow it.
    • Boundaries
      var left = camera.deadzone.left;\nvar right = camera.deadzone.right;\nvar top = camera.deadzone.top;\nvar bootom = camera.deadzone.bottom;\n
    • Clear deadzone
      camera.setDeadzone();\n
"},{"location":"camera/#events","title":"Events","text":"
  • Follower Update
    camera.on('followupdate', function(camera, gameObject){ })\n
"},{"location":"camera/#scroll-factor","title":"Scroll factor","text":"

See Scroll factor in game object.

"},{"location":"camera/#bounds","title":"Bounds","text":"
  • Set
    camera.setBounds(x, y, width, height)\n
  • Get
    var bounds = camera.getBounds();  // bounds: a rectangle object\n// var out = camera.getBounds(out);\n
"},{"location":"camera/#world-coordinates","title":"World coordinates","text":"
  • World view, a rectangle object
    var worldView = camera.worldView;\nvar x = worldView.x;\nvar y = worldView.y;\nvar width = worldView.width;  // displayWidth\nvar height = worldView.height; // displayHeight\nvar left = worldView.left;  // x\nvar right = worldView.right;  // x + width\nvar top = worldView.top;  // y\nvar bottom = worldView.bottom;  // y + height\nvar centerX = worldView.centerX;\nvar centerY = worldView.centerY;\nvar isInside = worldView.contains(x, y);\nvar randPoint = worldView.getRandomPoint(point); // point: {x, y}\n
  • Middle point
    var x = camera.midPoint.x;\nvar y = camera.midPoint.y;\n
  • Get world position
    var out = camera.getWorldPoint(x, y);\n// var out = camera.getWorldPoint(x, y, out);\n
    • x , y : Position of camera.
    • out : World position {x, y}
"},{"location":"camera/#set-background-color","title":"Set background color","text":"
camera.setBackgroundColor(color);\n
"},{"location":"camera/#ignore-game-object","title":"Ignore game object","text":"

Ignored game objects won't show at that camera.

camera.ignore(gameObject);\n
  • gameObject :
    • A game object
    • An array of game objects
    • A group
"},{"location":"camera/#get-cameras-below-pointer","title":"Get cameras below pointer","text":"
var cameras = scene.cameras.getCamerasBelowPointer(pointer);\n
  • cameras : An array of cameras.
  • pointer : {x, y}
"},{"location":"camera/#pause-resume","title":"Pause, resume","text":"
  • Pause
    camera.renderToTexture = false; // Pause\n
  • Resume
    camera.renderToTexture = true; // Resume\n
"},{"location":"camera/#clear","title":"Clear","text":"
camera.clearRenderToTexture();\n
"},{"location":"camera/#children","title":"Children","text":""},{"location":"camera/#visible-children","title":"Visible children","text":"
  • Filter visible children
    var visible = scene.cameras.getVisibleChildren(children, camera);\n
  • Get all visible children
    var visible = scene.cameras.getVisibleChildren(scene.sys.displayList.list, camera);\n

See also: gameObject.willRender(camera)

"},{"location":"camera/#render-children","title":"Render children","text":"
var children = camera.renderList;\n

Read only.

"},{"location":"canvas-circularprogress/","title":"Circular progres","text":""},{"location":"canvas-circularprogress/#introduction","title":"Introduction","text":"

Circular progress bar on canvas.

  • Author: Rex
  • Game object
"},{"location":"canvas-circularprogress/#live-demos","title":"Live demos","text":"
  • Circular-progress
"},{"location":"canvas-circularprogress/#usage","title":"Usage","text":"

Sample code

"},{"location":"canvas-circularprogress/#install-plugin","title":"Install plugin","text":""},{"location":"canvas-circularprogress/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcircularprogresscanvasplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcircularprogresscanvasplugin.min.js', true);\n
  • Add circular-progress object
    var circularProgress = scene.add.rexCircularProgressCanvas(x, y, radius, color, value, config);\n
"},{"location":"canvas-circularprogress/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CircularProgressCanvasPlugin from 'phaser3-rex-plugins/plugins/circularprogresscanvas-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCircularProgressCanvasPlugin',\nplugin: CircularProgressCanvasPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add circular-progress object
    var circularProgress = scene.add.rexCircularProgressCanvas(x, y, radius, color, value, config);\n
"},{"location":"canvas-circularprogress/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CircularProgressCanvas from 'phaser3-rex-plugins/plugins/circularprogresscanvas.js';\n
  • Add circular-progress object
    var circularProgress = new CircularProgressCanvas(scene, x, y, radius, color, value, config);\nscene.add.existing(image);\n
"},{"location":"canvas-circularprogress/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCircularProgressCanvasPlugin',\nplugin: CircularProgressCanvasPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"canvas-circularprogress/#create-instance","title":"Create instance","text":"
var circularProgress = scene.add.rexCircularProgressCanvas(x, y, radius, barColor, value, {\nbarColor2: undefined,\ntrackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nendAngle: Phaser.Math.DegToRad(270+360),\nanticlockwise: false,\n\ntextColor: undefined,\ntextStrokeColor: undefined,\ntextStrokeThickness: undefined,\n// textFont: ,\ntextSize: '16px',\ntextFamily: 'Courier',\ntextStyle: '',\ntextFormatCallback: undefined,\ntextFormatCallbackScope: undefined,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},\n});\n

or

var circularProgress = scene.add.rexCircularProgressCanvas({\nx: 0,\ny: 0,\nradius: 1,\n\nbarColor: undefined,\nbarColor2: undefined,\ntrackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nendAngle: Phaser.Math.DegToRad(270+360),\nanticlockwise: false,\n\ntextColor: undefined,\ntextStrokeColor: undefined,\ntextStrokeThickness: undefined,\n// textFont: ,\ntextSize: '16px',\ntextFamily: 'Courier',\ntextStyle: '',\ntextFormatCallback: undefined,\ntextFormatCallbackScope: undefined,\n\nvalue: 0,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},\n});\n
  • x, y : Position of this object.
  • radius : Radius of this circle. Size will be (radius*2, radius*2).
  • barColor, barColor2 : Fill color of circular bar, in number or css string value. Assign gradient start color by barColor2.
  • trackColor : Color of circular track, in number or css string value.
  • centerColor : Color of center circle, in number or css string value.
  • thickness : 0 ~ 1, thickness of circular bar. Default value is 0.2 (0.2*radius)
  • startAngle : Start angle of circular bar, in radians. Default value is 270 degrees.
  • endAngle : End angle of circular bar, in radians. Default value is 270+360 degrees.
  • anticlockwise : Set true to put anticlockwise circular bar. Default value is false.
  • textColor : Color of display text. Default is undefined.
  • textStrokeColor, textStrokeThickness : Stroke color, stroke line width of display text. Default is undefined.
  • textSize, textFamily, textStyle : Size, family, style of display text.
  • textFormatCallback, textFormatCallbackScope : Formating callback of display text. ex:
    function(value) {\nreturn Math.floor(value * 100).toString();\n}\n
    Default value is undefined.
  • value : 0 ~ 1, progress value. Default is 0.
  • easeValue : Parameters of easing value.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • valuechangeCallback : callback function when value changed.
    function(newValue, oldValue, circularProgress) {\n}\n

Add circular-progress from JSON

var circularProgress = scene.make.rexCircularProgressCanvas({\nx: 0,\ny: 0,\nradius: 1,\n\nbarColor: undefined,\nbarColor2: undefined,\ntrackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nendAngle: Phaser.Math.DegToRad(270+360),\nanticlockwise: false,\n\ntextColor: undefined,\ntextStrokeColor: undefined,\ntextStrokeThickness: undefined,\ntextSize: '16px',\ntextFamily: 'Courier',\ntextStyle: '',\ntextFormatCallback: undefined,\ntextFormatCallbackScope: undefined,\n\nvalue: 0,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},\n\nadd: true\n});\n
"},{"location":"canvas-circularprogress/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCircularProgressCanvas extends CircularProgressCanvas {\nconstructor(scene, x, y, radius, barColor, value, config) {\nsuper(scene, x, y, radius, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var circularProgress = new MyCircularProgressCanvas(scene, x, y, radius, color, value, config);\n
"},{"location":"canvas-circularprogress/#progress-value","title":"Progress value","text":"
  • Get value
    var value = circularProgress.getValue(min, max); // value : min ~ max\n
    or
    var value = circularProgress.getValue(); // value: 0 ~ 1\n
    or
    var value = circularProgress.value; // value: 0 ~ 1\n
  • Set value
    circularProgress.setValue(value, min, max); // value: min ~ max\n
    or
    circularProgress.setValue(value); // value: 0 ~ 1\n
    or
    circularProgress.value = value; // value: 0 ~ 1\n
  • Increase value
    circularProgress.addValue(inc, min, max); // inc: min ~ max\n
    or
    circularProgress.addValue(inc); // inc: 0 ~ 1\n
    or
    circularProgress.value += inc; // inc: 0 ~ 1\n
"},{"location":"canvas-circularprogress/#ease-progress-value","title":"Ease progress value","text":"
  • Ease value to
    circularProgress.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    circularProgress.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    circularProgress.stopEaseValue();\n
  • Set ease duration
    circularProgress.setEaseValueDuration(duration);\n
  • Set ease function
    circularProgress.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"canvas-circularprogress/#radius","title":"Radius","text":"
  • Get
    var radius = circularProgress.radius;\n
  • Set
    circularProgress.setRadius(radius);\n// circularProgress.radius = radius;\n
    • Also resize this game object to (radius*2, radius*2)
"},{"location":"canvas-circularprogress/#circular-track","title":"Circular track","text":"
  • Color
    • Get
      var trackColor = circularProgress.trackColor;\n
    • Set
      circularProgress.setTrackColor(trackColor);\n// circularProgress.trackColor = trackColor;\n
  • Thickness : radius*thickness
    circularProgress.setThickness(thickness);\n
    • thickness : 0~1.
"},{"location":"canvas-circularprogress/#circular-bar","title":"Circular bar","text":"
  • Color
    • Get
      var barColor = circularProgress.barColor;\n
    • Set
      circularProgress.setBarColor(color);\n// circularProgress.barColor = color;\n
  • Color2
    • Get
      var barColor2 = circularProgress.barColor2;\n
    • Set
      circularProgress.setBarColor2(color);\n// circularProgress.barColor2 = color;\n
  • Thickness : radius*thickness
    circularProgress.setThickness(thickness);\n
    • thickness : 0~1.
  • Start angle
    • Get
      var startAngle = circularProgress.startAngle;\n
    • Set
      circularProgress.setStartAngle(startAngle);\ncircularProgress.startAngle = startAngle;\n
      • startAngle : Start angle of circular bar, in radians.
  • End angle
    • Get
      var endAngle = circularProgress.endAngle;\n
    • Set
      circularProgress.setEndAngle(endAngle);\ncircularProgress.endAngle = endAngle;\n
      • endAngle : End angle of circular bar, in radians.
  • Anticlockwise
    • Get
      var anticlockwise = circularProgress.anticlockwise;\n
    • Set
      circularProgress.setAnticlockwise(anticlockwise);\n// circularProgress.anticlockwise = anticlockwise;\n
"},{"location":"canvas-circularprogress/#center-circle","title":"Center circle","text":"
  • Color
    • Get
      var centerColor = circularProgress.centerColor;\n
    • Set
      circularProgress.setCenterColor(centerColor);\n// circularProgress.centerColor = centerColor;\n
"},{"location":"canvas-circularprogress/#display-text","title":"Display text","text":"
  • Fill color
    circularProgress.setTextColor(color);\n
  • Stroke color
    circularProgress.setTextStrokeColor(color, thickness);\n
  • Font
    circularProgress.setTextFont(fontSize, fontFamily, fontStyle);\n
  • Format callback
    circularProgress.setTextFormatCallback(callback, scope);\n
    • callback :
      function(value) {\nreturn Math.floor(value * 100).toString(); }\n
"},{"location":"canvas-circularprogress/#events","title":"Events","text":"
  • On value changed
    circularProgress.on('valuechange', function(newValue, oldValue, circularProgress){\n//\n}, scope);\n
"},{"location":"canvas-circularprogress/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"canvas-circularprogress/#create-mask","title":"Create mask","text":"
var mask = circularProgress.createBitmapMask();\n

See mask

"},{"location":"canvas-circularprogress/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"canvas-circularprogress/#compare-with-circular-progress-shape","title":"Compare with Circular-progress shape","text":"
  • Circular-progress canvas creates a canvas then draw on that canvas, circular progress shape draw on GRAPHICS pipeline like Shape or Graphics game object.
  • Circular-progress canvas can draw text directly, circular progress shape can't draw any text.
"},{"location":"canvas-data/","title":"Canvas image data","text":""},{"location":"canvas-data/#introduction","title":"Introduction","text":"

Get image data from texture, or text object.

  • Author: Rex
  • Method only
"},{"location":"canvas-data/#live-demos","title":"Live demos","text":"
  • Text to bit-map
  • Texture to color-map
"},{"location":"canvas-data/#usage","title":"Usage","text":"

Sample code

"},{"location":"canvas-data/#install-plugin","title":"Install plugin","text":""},{"location":"canvas-data/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcanvasdataplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcanvasdataplugin.min.js', true);\n
  • Add canvas-data object
    var canvasData = scene.plugins.get('rexcanvasdataplugin').canvasObjectToBitmap(gameObject);\nvar canvasData = scene.plugins.get('rexcanvasdataplugin').textureTColorMap(textureKey, frameName);\n
"},{"location":"canvas-data/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CanvasDataPlugin from 'phaser3-rex-plugins/plugins/canvasdata-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCanvasData',\nplugin: CanvasDataPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add canvas-data object
    var canvasData = scene.plugins.get('rexCanvasData').canvasObjectToBitmap(gameObject);\nvar canvasData = scene.plugins.get('rexCanvasData').textureTColorMap(textureKey, frameName);\n
"},{"location":"canvas-data/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CanvasData from 'phaser3-rex-plugins/plugins/canvasdata.js';\n
  • Add canvas-data object
    var canvasdata = CanvasData.canvasObjectToBitmap(gameObject);\nvar canvasdata = CanvasData.textureTColorMap(textureKey, frameName);\n
"},{"location":"canvas-data/#textcanvas-object-bitmap","title":"Text/canvas object -> Bitmap","text":"
var canvasData = scene.plugins.get('rexCanvasData').canvasObjectToBitmap(gameObject);\n// var out = scene.plugins.get('rexCanvasData').canvasObjectToBitmap(gameObject, out);\n
  • gameObject :
    • Any kind of text object : Text object, bbcode text object, or tag text object.
    • Canvas object
  • For each pixel data
    canvasData.forEach(function(value, x, y, canvasData){\n\n}, scope);\n
    • value : true, or false
"},{"location":"canvas-data/#texture-color-map","title":"Texture -> Color map","text":"
  • Texture -> Color map
    var canvasData = scene.plugins.get('rexCanvasData').textureTColorMap(textureKey, frameName);\n// var out = scene.plugins.get('rexCanvasData').canvasObjectToBitmap(textureKey, frameName, out);\n
  • Texture of game object -> Color map
    var canvasData = scene.plugins.get('rexCanvasData').textureTColorMap(gameObject);\n// var out = scene.plugins.get('rexCanvasData').canvasObjectToBitmap(gameObject, out);\n
  • For each pixel data
    canvasData.forEach(function(value, x, y, canvasData){\n\n}, scope);\n
    • value : Color32 integer = color integer + (alpha << 24)
      • Get color integer (0 ~ 0xffffff)
        var color = value & 0xffffff;\n
        or
        var color = canvasData.color32ToColorInt(value);\n
      • Get alpha (0 ~ 0xff)
        var alpha = value >>> 24;\n
        var alpha = canvasData.color32ToAlpha(value);\n
"},{"location":"canvas-data/#canvas-data","title":"Canvas data","text":""},{"location":"canvas-data/#for-each-pixel","title":"For each pixel","text":"
  • For each pixel data
    canvasData.forEach(callback, scope);\n
    • callback : Callback for each pixel
      function(value, x, y, canvasData) {\n\n}\n
  • For each non zero pixel data
    canvasData.forEachNonZero(callback, scope);\n
"},{"location":"canvas-data/#get-pixel-data","title":"Get pixel data","text":"
var data = canvasData.get(x, y);\n
  • data :
    • true, or false in result of canvasObjectToBitmap method
    • Color32 in result of textureTColorMap method
"},{"location":"canvas-data/#size","title":"Size","text":"
var width = canvasData.width;\nvar height = canvasData.height;\n
"},{"location":"canvas-lineprogress/","title":"Line progres","text":""},{"location":"canvas-lineprogress/#introduction","title":"Introduction","text":"

Horizontal line progress bar filled with gradient color on canvas.

  • Author: Rex
  • Game object
"},{"location":"canvas-lineprogress/#live-demos","title":"Live demos","text":"
  • Line-progress
"},{"location":"canvas-lineprogress/#usage","title":"Usage","text":"

Sample code

"},{"location":"canvas-lineprogress/#install-plugin","title":"Install plugin","text":""},{"location":"canvas-lineprogress/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlineprogresscanvasplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlineprogresscanvasplugin.min.js', true);\n
  • Add line-progress object
    var lineProgress = scene.add.rexLineProgressCanvas(x, y, width, height, barColor, value, config);\n
"},{"location":"canvas-lineprogress/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LineProgressCanvasPlugin from 'phaser3-rex-plugins/plugins/lineprogresscanvas-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLineProgressCanvasPlugin',\nplugin: LineProgressCanvasPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add line-progress object
    var lineProgress = scene.add.rexLineProgressCanvas(x, y, width, height, barColor, value, config);\n
"},{"location":"canvas-lineprogress/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LineProgressCanvas from 'phaser3-rex-plugins/plugins/lineprogresscanvas.js';\n
  • Add line-progress object
    var lineProgress = new LineProgressCanvas(scene, x, y, width, height, barColor, value, config);\nscene.add.existing(image);\n
"},{"location":"canvas-lineprogress/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLineProgressCanvasPlugin',\nplugin: LineProgressCanvasPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"canvas-lineprogress/#create-instance","title":"Create instance","text":"
var lineProgress = scene.add.rexLineProgressCanvas(x, y, width, height, barColor, value, {    barColor2: undefined,\nisHorizontalGradient: true,\ntrackColor: undefined,\ntrackStrokeColor: undefined,\ntrackStrokeThickness: 2,\n\nskewX:0,\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, lineProgress) {\n},\n});\n

or

var lineProgress = scene.add.rexLineProgressCanvas({\nx: 0,\ny: 0,\nwidth: 2,\nheight: 2,\n\nbarColor: undefined,\nbarColor2: undefined,\nisHorizontalGradient: true,\ntrackColor: undefined,\ntrackStrokeColor: undefined,\ntrackStrokeThickness: 2,\n\nskewX:0,\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvalue: 0,\nvaluechangeCallback: function(newValue, oldValue, lineProgress) {\n},\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • barColor, barColor2, isHorizontalGradient : Fill color of line bar, in number or css string value. Assign gradient start color by barColor2.
  • trackColor : Fill color of line track, in number or css string value.
  • trackStrokeColor : Stroke color of track, in number or css string value.
  • trackStrokeThickness : Stroke line width of track.
  • skewX : Horizontal skew of track and bar.
  • rtl :
    • false : Bar starts from left side. Default behavior.
    • true : Bar starts from right side.
  • value : 0 ~ 1, progress value. Default is 0.
  • easeValue : Parameters of easing value.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • valuechangeCallback : callback function when value changed.
    function(newValue, oldValue, lineProgress) {\n}\n

Add line-progress from JSON

var lineProgress = scene.make.rexLineProgressCanvas({\nx: 0,\ny: 0,\nwidth: 2,\nheight: 2,\n\nbarColor: undefined,\nbarColor2: undefined,\nisHorizontalGradient: true,\ntrackColor: undefined,\ntrackStrokeColor: undefined,\ntrackStrokeThickness: 2,\n\nskewX:0,\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvalue: 0,\nvaluechangeCallback: function(newValue, oldValue, lineProgress) {\n},\n\nadd: true\n});\n
"},{"location":"canvas-lineprogress/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLineProgressCanvas extends LineProgressCanvas {\nconstructor(scene, x, y, width, height, barColor, value, config) {\nsuper(scene, x, y, width, height, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var lineProgress = new MyLineProgressCanvas(scene, x, y, width, height, barColor, value, config);\n
"},{"location":"canvas-lineprogress/#progress-value","title":"Progress value","text":"
  • Get value
    var value = lineProgress.getValue(min, max); // value : min ~ max\n
    or
    var value = lineProgress.getValue(); // value: 0 ~ 1\n
    or
    var value = lineProgress.value; // value: 0 ~ 1\n
  • Set value
    lineProgress.setValue(value, min, max); // value: min ~ max\n
    or
    lineProgress.setValue(value); // value: 0 ~ 1\n
    or
    lineProgress.value = value; // value: 0 ~ 1\n
  • Increase value
    lineProgress.addValue(inc, min, max); // inc: min ~ max\n
    or
    lineProgress.addValue(inc); // inc: 0 ~ 1\n
    or
    lineProgress.value += inc; // inc: 0 ~ 1\n
"},{"location":"canvas-lineprogress/#ease-progress-value","title":"Ease progress value","text":"
  • Ease value to
    lineProgress.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    lineProgress.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    lineProgress.stopEaseValue();\n
  • Set ease duration
    lineProgress.setEaseValueDuration(duration);\n
  • Set ease function
    lineProgress.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"canvas-lineprogress/#line-track","title":"Line track","text":"
  • Color
    • Get
      var trackColor = lineProgress.trackColor;\n
    • Set
      lineProgress.setTrackColor(trackColor);\n// lineProgress.trackColor = trackColor;\n
  • Stroke
    • Get
      var trackStrokeColor = lineProgress.trackStrokeColor;\nvar trackStrokeThickness = lineProgress.trackStrokeThickness;\n
    • Set
      lineProgress.setTrackColor(color);\nlineProgress.setTrackStroke(lineWidth, color);\n
"},{"location":"canvas-lineprogress/#line-bar","title":"Line bar","text":"
  • Color
    • Get
      var barColor = lineProgress.barColor;\nvar barColor2 = lineProgress.barColor2;\n
    • Set
      lineProgress.setBarColor(barColor, barColor2);\n// lineProgress.barColor = barColor;\n// lineProgress.barColor2 = barColor2;\n
"},{"location":"canvas-lineprogress/#horizontal-skew","title":"Horizontal skew","text":"
  • Get
    var skewX = lineProgress.skewX;\n
  • Set
    lineProgress.setSkewX(skewX);\n// lineProgress.skewX = skewX;\n
"},{"location":"canvas-lineprogress/#right-to-left","title":"Right-to-left","text":"
  • Get
    var rtl = lineProgress.rtl;\n
  • Set
    lineProgress.setRTL(rtl);\n// lineProgress.rtl = rtl;\n
"},{"location":"canvas-lineprogress/#events","title":"Events","text":"
  • On value changed
    lineProgress.on('valuechange', function(newValue, oldValue, lineProgress){\n//\n}, scope);\n
"},{"location":"canvas-lineprogress/#alpha","title":"Alpha","text":"
  • Get
    var alpha = lineProgress.alpha;\n
  • Set
    lineProgress.setAlpha(alpha);\n// lineProgress.alpha = alpha;\n
"},{"location":"canvas-lineprogress/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"canvas-lineprogress/#create-mask","title":"Create mask","text":"
var mask = lineProgress.createBitmapMask();\n

See mask

"},{"location":"canvas-lineprogress/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"canvas-lineprogress/#compare-with-line-progress-shape","title":"Compare with Line-progress shape","text":"
  • Line-progress canvas creates a canvas then draw on that canvas, line progress shape draw on GRAPHICS pipeline like Shape or Graphics game object.
  • Line-progress canvas can fill gradient color, line progress shape only can fill 1 color.
"},{"location":"canvas-roundrectangle/","title":"Round rectangle","text":""},{"location":"canvas-roundrectangle/#introduction","title":"Introduction","text":"

Round rectangle on canvas.

  • Author: Rex
  • Game object
"},{"location":"canvas-roundrectangle/#live-demos","title":"Live demos","text":"
  • Round rectangle
"},{"location":"canvas-roundrectangle/#usage","title":"Usage","text":"

Sample code

"},{"location":"canvas-roundrectangle/#install-plugin","title":"Install plugin","text":""},{"location":"canvas-roundrectangle/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexroundrectanglecanvasplugin', 'https://raw.githubusercontent.com/rexrainbow/    phaser3-rex-notes/master/dist/rexroundrectanglecanvasplugin.min.js', true);\n
  • Add shape object
    var rect = scene.add.rexRoundRectangleCanvas(x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
"},{"location":"canvas-roundrectangle/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RoundRectanglePlugin from 'phaser3-rex-plugins/plugins/roundrectanglecanvas-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRoundRectangleCanvasPlugin',\nplugin: RoundRectangleCanvasPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add shape object
    var rect = scene.add.rexRoundRectangleCanvas(x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
"},{"location":"canvas-roundrectangle/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RoundRectangleCanvas from 'phaser3-rex-plugins/plugins/roundrectanglecanvas.js';\n
  • Add shape object
    var rect = new RoundRectangleCanvas(scene, x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\nscene.add.existing(rect);\n
"},{"location":"canvas-roundrectangle/#create-shape-object","title":"Create shape object","text":"
var rect = scene.add.rexRoundRectangleCanvas(x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
  • width, height : Size of rectangle.
    • undefined : Set ot undefined to draw a circle.
  • radius : Radius of four corners.
    • 0, or undefined : Disable round corner.
    • Number: 4 corners with the same radius.
    • JSON
      • 4 corners with the same radius X/Y
        {\nx: radiusX,\ny: radiusY\n}\n
      • Eeach radius of corner
        {\ntl: radius,\ntr: radius,\nbl: radius,\nbr: radius\n}\n
        or
        {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n}\n
      • Radius and iteration
        {\nradius: radius,\niteration: 0\n}\n
        or
        {\nradius: {x: radiusX, y: radiusY},\niteration: 0\n}\n
        or
        {\nradius: {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n},\niteration: 0\n}\n
        • radius :
          • 0 : No round corner
          • > 0 : Convex round corner
          • < 0 : Concave round corner
        • iteration : Number of interpolation points in each round corner. Default value is 4.
          • 0 : Draw a straight line instead of arc.
  • fillStyle : Fill color in number or css string value, or a callback
    • Number, or css string value : Color value
    • Callback :
      function(canvas, context) {\n// Radial gradient\nvar grd = context.createRadialGradient(x0, y0, r0, x1, y1, r1);\ngrd.addColorStop(0, color0);\ngrd.addColorStop(1, color1);\nreturn grd;\n}\n
  • strokeStyle : Stroke color in number or css string value.
  • lineWidth : Stroke line width.
  • fillColor2 : Gradient color in number or css string value.
  • isHorizontalGradient :
    • true : Horizontal gradient.
    • false : Vertical gradient.

Note

If radius >= 0, draw convex corner, else draw concave corner

"},{"location":"canvas-roundrectangle/#deform","title":"Deform","text":"
  • Rectangle, set radius of 4 corners to 0.
    var rect = scene.add.rexRoundRectangleCanvas(x, y, width, height, 0, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
  • Circle, set width and height to 2*radius.
    var rect = scene.add.rexRoundRectangleCanvas(x, y, (2*radius), (2*radius), radius, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
  • Ellipse, set width and height to 2*radiusX, 2*radiusY.
    var rect = scene.add.rexRoundRectangleCanvas(x, y, (2*radiusX), (2*radiusX), {x: radiusX, y: radiusY}, fillColor, fillAlpha);\n
  • Rhombus, set width and height to 2*radius, and assign iteration to 0
    var rect = scene.add.rexRoundRectangleCanvas(x, y, (2*radius), (2*radius), {\nradius: radius,\niteration: 0\n}, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
  • Octagon, assign iteration to 0
    var rect = scene.add.rexRoundRectangleCanvas(x, y, width, height, {\nradius: radius,\niteration: 0\n}, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
"},{"location":"canvas-roundrectangle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyRoundRectangleCanvas extends RexPlugins.GameObjects.RoundRectangleCanvas {\nconstructor(scene, x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient) {\nsuper(scene, x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var rect = new MyRoundRectangleCanvas(scene, x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
"},{"location":"canvas-roundrectangle/#color","title":"Color","text":"
  • Fill color
    • Get
      var fillStyle = rect.fillStyle;\nvar fillColor2 = rect.fillColor2;\nvar isHorizontalGradient = rect.isHorizontalGradient;\n
    • Set
      rect.setFillStyle(fillStyle);\n// rect.setFillStyle(fillStyle, fillColor2, isHorizontalGradient);\n
      • fillStyle : Fill color in number or css string value, or a callback
        • Number, or css string value : Color value
        • Callback :
          function(canvas, context) {\n// Radial gradient\nvar grd = context.createRadialGradient(x0, y0, r0, x1, y1, r1);\ngrd.addColorStop(0, color0);\ngrd.addColorStop(1, color1);\nreturn grd;\n}\n
    • Clear
      rect.setFillStyle();\n
  • Stroke color
    • Get
      var strokeStyle = rect.strokeStyle;\nvar lineWidth = rect.lineWidth;\n
    • Set
      rect.setStrokeStyle(strokeStyle, lineWidth);\n
    • Clear
      rect.setStrokeStyle();\n
"},{"location":"canvas-roundrectangle/#size","title":"Size","text":"
  • Get
    var width = rect.width;\nvar height = rect.height;\n
  • Set
    rect.setSize(width, height);\n
    or
    rect.width = width;\nrect.height = height;\n
"},{"location":"canvas-roundrectangle/#radius","title":"Radius","text":"
  • Set
    rect.setRadius(value);\n
    or
    rect.radius = radius;\n
    • radius :
      • Number : 4 corners with the same radius.
        • 0 : No round corner
        • > 0 : Convex round corner
        • < 0 : Concave round corner
      • JSON
        • 4 corners with the same radius X/Y
          {\nx: radiusX,\ny: radiusY\n}\n
        • Eeach radius of corner
          {\ntl: radius,\ntr: radius,\nbl: radius,\nbr: radius\n}\n
          or
          {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n}\n
"},{"location":"canvas-roundrectangle/#iteration","title":"Iteration","text":"
  • Get
    var iteration = rect.iteration;\n
  • Set
    rect.setIteration(value);\n
    or
    rect.iteration = value;\n

Number of interpolation points in each round corner. Default value is 4.

  • 0 : Draw a straight line instead of arc.
"},{"location":"canvas-roundrectangle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"canvas-roundrectangle/#create-mask","title":"Create mask","text":"
var mask = rect.createBitmapMask();\n

See mask

"},{"location":"canvas-roundrectangle/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"canvas-roundrectangle/#compare-with-shape-roundrectangle","title":"Compare with Shape-Roundrectangle","text":"
  • Gradient
    • Canvas-RoundRectangle can fill with gradient color.
    • Shape-Roundrectangle can't fill gradient color.
  • Drawing method
    • Canvas-RoundRectangle draw shape on canvas, then map this canvas to frame buffer.
    • Shape-Roundrectangle draw shape on frame buffer directly without drawing to canvas first.
"},{"location":"canvas-texture/","title":"Canvas texture","text":""},{"location":"canvas-texture/#introduction","title":"Introduction","text":"

Canvas Canvas Texture stored in texture cache, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"canvas-texture/#usage","title":"Usage","text":""},{"location":"canvas-texture/#create-canvas-texture","title":"Create canvas texture","text":"
var texture = scene.textures.createCanvas(key, width, height);\n
"},{"location":"canvas-texture/#get-canvas-element","title":"Get canvas element","text":"
var canvas = texture.getCanvas();\nvar context = texture.getContext();\n

Canvas api

"},{"location":"canvas-texture/#draw-frame","title":"Draw frame","text":"
texture.drawFrame(key, frame, x, y);\n// texture.drawFrame(key, frame, x, y, update);\n
  • update : Update the internal ImageData buffer and arrays. Default value is true.
"},{"location":"canvas-texture/#draw-image","title":"Draw image","text":"
texture.draw(x, y, source);\n// texture.draw(x, y, source, update);\n
  • source : The HTML Image element, or HTML Canvas element to draw to this canvas.
  • update : Update the internal ImageData buffer and arrays. Default value is true.
"},{"location":"canvas-texture/#clear","title":"Clear","text":"
texture.clear();\n
texture.clear(x, y, width, height);\n// // texture.clear(x, y, width, height, update);\n
  • update : Update the internal ImageData buffer and arrays. Default value is true.
"},{"location":"canvas-texture/#refresh-texture","title":"Refresh texture","text":"
texture.refresh();\n
"},{"location":"canvas-texture/#color","title":"Color","text":"
  • Set
    texture.setPixel(x, y, red, green, blue);\n// texture.setPixel(x, y, red, green, blue, alpha);\n
  • Get
    var color = texture.getPixel(x, y);\n// var color = texture.getPixel(x, y, color);\n
    var colors = texture.getPixels(x, y, width, height);\n
    • colors : [{x, y, color, alpha}, ...]
"},{"location":"canvas-texture/#image-data","title":"Image data","text":"
  • Set
    texture.putData(imageData, x, y);\n
  • Get
    var imageData = texture.getData(x, y, width, height);\n
"},{"location":"canvas-texture/#add-frame","title":"Add frame","text":"
texture.add(name, sourceIndex, x, y, width, height);\n
  • name : The name of this Frame. The name is unique within the Texture.
  • sourceIndex : The index of the TextureSource that this Frame is a part of.
  • x : The x coordinate of the top-left of this Frame.
  • y : The y coordinate of the top-left of this Frame.
  • width : The width of this Frame.
  • height : The height of this Frame.
"},{"location":"canvas/","title":"Canvas","text":""},{"location":"canvas/#introduction","title":"Introduction","text":"

Drawing on canvas.

  • Author: Rex
  • Game object
"},{"location":"canvas/#live-demos","title":"Live demos","text":"
  • Kaleidoscope
  • chartjs
  • Resolution
"},{"location":"canvas/#usage","title":"Usage","text":"

Sample code

"},{"location":"canvas/#install-plugin","title":"Install plugin","text":""},{"location":"canvas/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcanvasplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcanvasplugin.min.js', true);\n
  • Add canvas object
    var canvas = scene.add.rexCanvas(x, y, width, height);\n
"},{"location":"canvas/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CanvasPlugin from 'phaser3-rex-plugins/plugins/canvas-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCanvasPlugin',\nplugin: CanvasPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add canvas object
    var canvas = scene.add.rexCanvas(x, y, width, height);\n
"},{"location":"canvas/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Canvas from 'phaser3-rex-plugins/plugins/canvas.js';\n
  • Add canvas object
    var canvas = new Canvas(scene, x, y, width, height);\nscene.add.existing(canvas);\n
"},{"location":"canvas/#create-instance","title":"Create instance","text":"
var canvas = scene.add.rexCanvas(x, y, width, height);\n// var canvas = scene.add.rexCanvas(x, y, width, height, resolution);\n

Add canvas from JSON

var canvas = scene.make.rexCanvas({\nx: 0,\ny: 0,\nwidth: 256,\nheight: 256,\n// resolution: 1,\n\n// origin: {x: 0.5, y: 0.5},\n// fill: null,\n\nadd: true\n});\n
  • resolution : The resolution the content is rendered to its internal canvas at. Default value is 1.
"},{"location":"canvas/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCanvas extends Canvas {\nconstructor(scene, x, y, width, height, resolution) {\nsuper(scene, x, y, width, height, resolution);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var canvas = new MyCanvas(scene, x, y, width, height, resolution);\n
"},{"location":"canvas/#clear-or-fill-canvas","title":"Clear or fill canvas","text":"
  • Clear
    canvas.clear();\n
  • Fill color
    canvas.fill(color);\n
"},{"location":"canvas/#update-canvas","title":"Update canvas","text":"
  1. Get canvas elemet
    var canvasElem = canvas.getCanvas();\nvar context = canvas.getContext();\n
    or
    var canvaesElem = canvas.canvas;\nvar context = canvas.context;\n
  2. Draw on context
"},{"location":"canvas/#update-display-texture","title":"Update display texture","text":"
  • Update texture when rendering
    canvas.needRedraw();\n
    or
    canvas.dirty = true;\n
  • Update texture now
    canvas.updateTexture();\n
    or update canvas and texture
    canvas.updateTexture(function(canvasElem, context) { });\n// canvas.updateTexture(callback, scope);\n
"},{"location":"canvas/#load-or-save-texture","title":"Load or save texture","text":"
  • Save canvas to texuture
    canvas.generateTexture(key);\n// canvas.generateTexture(key, x, y, width, height);\n
  • Copy canvas from texture
    canvas.loadTexture(key, frame);\n
"},{"location":"canvas/#paste-frame","title":"Paste frame","text":"
canvas.drawFrame(key, frame);\n// canvas.drawFrame(key, frame, dx, dy, dWidth, dHeight);\n// canvas.drawFrame(key, frame, dx, dy, dWidth, dHeight, sxOffset, syOffset, sWidth, sHeight);\n
  • dx, dy : Top-left position in this canvas. Default value is 0, 0.
  • dWidth, dHeight : The size to draw the image in this canvas. Default value is origin size of frame.
  • sxOffset, syOffset : Offset position of source frame. Default value is 0, 0
  • sWidth, sHeight : The size of the sub-rectangle of the source frame to draw into this canvas. Default value is origin size of frame.
"},{"location":"canvas/#data-url","title":"Data URL","text":"
  • Load image from URL
    canvas.loadFromURL(url);\n// canvas.loadFromURL(url, callback);\n
    or
    canvas.loadFromURLPromise(url)\n.then(function() {\n\n})\n
    • url : Image url/uri(base64 string)
    • callback : Load complete callback.
  • Get data URL of image
    var dataURL = canvas.getDataURL();\n// var dataURL = canvas.getDataURL(type, encoderOptions);\n
    • dataURL : A base64 string.
    • type : A DOMString indicating the image format. The default format type is image/png.
    • encoderOptions : A Number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp.
"},{"location":"canvas/#file","title":"File","text":"
  • Load image from File object
    canvas.loadFromFile(file);\n// canvas.loadFromFile(file, callback);\n
    or
    canvas.loadFromFilePromise(file)\n.then(function() {\n\n})\n
    • file : File object
    • callback : Load complete callback.
"},{"location":"canvas/#pixel-color","title":"Pixel color","text":"
  • Get color
    var color = canvas.getPixel(x, y);\n
    • color : Color object
      • color.red, color.green, color.blue, color.alpha
  • Set color
    canvas.setPixel(x, y, r, g, b);\n// canvas.setPixel(x, y, r, g, b, a);\n
    or
    canvas.setPixel(x, y, color);\n
    • r, g, b, a : Integer number between 0 ~ 255.
    • color : Color object
"},{"location":"canvas/#size","title":"Size","text":"
canvas.setCanvasSize(width, height);\n

or

canvas.setSize(width, height);\n

or

canvas.resize(width, height);\n
"},{"location":"canvas/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"canvas/#create-mask","title":"Create mask","text":"
var mask = canvas.createBitmapMask();\n

See mask

"},{"location":"canvas/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"canvas/#compare-with-graphics-object","title":"Compare with Graphics object","text":"
  • Drawing method
    • This canvas object draws stuff on canvas in WEBGL or CANVAS render mode.
    • Graphics object draws stuff on webgl render pipeline in WEBGL render mode.
  • Size
    • This canvas object has size (width, height) and origin.
    • Graphics object does not have size and origin.
"},{"location":"canvasinput/","title":"Canvas input","text":""},{"location":"canvasinput/#introduction","title":"Introduction","text":"

An invisible Input DOM element to receive character input and display on DynamicText.

Inspirited from CanvasInput.

  • Author: Rex
  • Game object
"},{"location":"canvasinput/#live-demos","title":"Live demos","text":"
  • Simple
  • Text input
  • Number input
  • With rexui-Label
  • Text area
"},{"location":"canvasinput/#usage","title":"Usage","text":"

Sample code

"},{"location":"canvasinput/#install-plugin","title":"Install plugin","text":""},{"location":"canvasinput/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcanvasinputplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcanvasinputplugin.min.js', true);\n
  • Add canvas-input object
    var txt = scene.add.rexCanvasInput(x, y, width, height, config);\n
"},{"location":"canvasinput/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CanvasInputPlugin from 'phaser3-rex-plugins/plugins/canvasinput-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCanvasInputPlugin',\nplugin: CanvasInputPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add canvas-input object
    var txt = scene.add.rexCanvasInput(x, y, width, height, config);\n
"},{"location":"canvasinput/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CanvasInput from 'phaser3-rex-plugins/plugins/canvasinput.js';\n
  • Add canvas-input object
    var txt = new CanvasInput(textGameObject, x, y, width, height, config);\nscene.add.existing(txt);\n
"},{"location":"canvasinput/#create-instance","title":"Create instance","text":"
var txt = scene.add.rexCanvasInput({\n// Parameters of DynamicText\nx: 0, y: 0,\nwidth: undefined, height: undefined,\nresolution: 1,\n\n// padding: 0,  // {left: 0, right: 0, top: 0, bottom: 0}\n\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null,\n\n// Style when focus\n// 'focus.color': ...\n// 'focus.color2': ...\n// 'focus.stroke': ...\n},\nfocusStyle: undefined,\n\ninnerBounds: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBY: undefined,\noffsetX: 0,\noffsetY: 0,\n\n// Style when cursor move on\n// 'cursor.color': ...\n// 'cursor.backgroundColor': ...\n// 'cursor.xxx': ...\n},\ncursorStyle: undefined,\n\nchildrenInteractive: false,\n\ntext: '',\n\nwrap: {\nlineHeight: undefined,\nuseDefaultLineHeight: true,\nmaxLines: 1,\nwrapWidth: undefined,\nletterSpacing: 0,\nwrapMode: 'char',  // 1|'word'|2|'char'|'character'|3|'mix', for single line text input\nhAlign: 0, // 0|'left'|1|'center'|2|'right'|3|'justify'|'justify-left'|4|'justify-center'|5| justify-right'\nvAlign: 'center',  // For single line text input        \n},\n\ntextArea: false,\n\n// Parameters of hidden-text-editor   \n// inputType: 'text',  // 'text'|'password'|'textarea'|...                \n\n// readOnly: false,\n// maxLength: undefined,\n// minLength: undefined,\n// selectAll: false,\n\n// enterClose: true,\n\n// Callbacks\n// onOpen: function (textObject, hiddenInputText) {\n// },\n\n// onClose: function (textObject, hiddenInputText) {\n// },\n\n// onUpdate: function (text, textObject, hiddenInputText) {\n//     return text;\n// },   \n\n// onAddChar: function(child, index, canvasInput) {\n//    child.modifyStyle({...})\n// },\n\n// onCursorOut: function(child, cursorIndex, canvasInput) {\n//     child.modifyStyle({\n//         \n//     });\n// },\n\n// onCursorIn: function(child, cursorIndex, canvasInput) {\n//     child.modifyStyle({\n//         \n//     });\n// },\n\n// parseTextCallback: function(text) {\n//     return text;\n// }.\n\n});\n
  • textArea :
    • false : Single line text input. Default behavior.
    • true : Multiple lines text input.
  • Parameters of DynamicText...
    • wrap : Some default value in wrap are changed
      • wrap.useDefaultLineHeight : Default value is true
      • wrap.maxLines : Default value is 1
      • wrap.vAlign : Default value is 'center'
  • Parameters of hidden-text-editor
    • inputType : Type of element
      • 'text', 'password', 'textarea', ...
    • enterClose : Set true to close input text when enter-key was pressed. Default value is true.
    • readOnly :
      • true : un-editable.
      • false : Editable. Defaule behavior.
    • maxLength, minLength : Maximun or minimun of input characters
    • selectAll : Set to true to select all characters when focusing.
  • Callbacks
    • onOpen : Callback invoked when focus on this hidden input text.
      function (textObject) {\n// textObject.setInputText(txt);\n}\n
    • onClose : Callback invoked when blur.
      function (textObject) {            }\n
    • onUpdate :
      • A callback invoked in each tick of editing.
        function (text, textObject) {\n// return text;\n}\n
        • Can return a new string for text game object displaying.
      • 'number' : Only output number string.
    • onAddChar : Callback invoked when adding new character child
      function(child, index, canvasInput) {\nchild.modifyStyle({...})\n}\n
      • child : character child
    • onCursorOut : Callback invoked when cursor move out of a character child
      function(child, index, canvasInput) {\nchild.modifyStyle({...})\n}\n
      • child : character child
    • onCursorIn : Callback invoked when cursor move on a character child
      function(child, index, canvasInput) {\nchild.modifyStyle({...})\n}\n
      • child : character child
    • parseTextCallback : Callback of parsing text (txt.text) to value (txt.value)
      • undefined : Bypass text to value. Default behavior.
      • A function object
        function(text) {\nreturn text;\n}\n
  • focusStyle : Will apply this style to background when focusing.
    • undefined : Ignore this behavior.
    • A plain object
      {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null,\n}\n
    • Or add these style settings in background parameter, with prefix 'focus.'.
  • cursorStyle : Will apply this style when cursor move on a character child.
    • undefined : Ignore this behavior.
    • A plain object
      {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBY: undefined,\noffsetX: 0,\noffsetY: 0\n}\n
    • Or add these style settings in style parameter, with prefix 'cursor.'.
"},{"location":"canvasinput/#number-input","title":"Number input","text":"
txt.setNumberInput();\n
"},{"location":"canvasinput/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCanvasInput extends CanvasInput {\nconstructor(textGameObject, x, y, width, height, config)) {\nsuper(textGameObject, x, y, width, height, config)) {\n// ...            \n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyCanvasInput(textGameObject, config);\n
"},{"location":"canvasinput/#open-editor","title":"Open editor","text":"
txt.open();\n

or

txt.open(onCloseCallback);\n
  • onCloseCallback : Callback invoked when closing text-editor
"},{"location":"canvasinput/#close-editor","title":"Close editor","text":"
txt.close();\n
"},{"location":"canvasinput/#is-opened","title":"Is opened","text":"
var isOpened = txt.isOpened;\n
"},{"location":"canvasinput/#text","title":"Text","text":"
  • Display text on dynamic text game object
    • Get
      var text = txt.text;\n
      or
      var text = txt.displayText;\n
    • Set
      txt.setText(text);\n
      or
      txt.setDisplayText(text);\n
  • Input text on hidden text edit behavior
    • Get
      var text = txt.inputText;\n
    • Set
      var text = txt.setInputText(text);\n
"},{"location":"canvasinput/#value","title":"Value","text":"
  • Get. Parse text to value.
    var value = txt.getValue();\n// var value = txt.value;\n
    • Set parseTextCallback
      txt.setParseTextCallback(callback);\n
      • callback :
        • undefined : Bypass text to value. Default behavior.
        • A function object
          function(text) {\nreturn text;\n}\n
  • Set. Conver any type of value to string.
    txt.setValue(value);\n// txt.value = value;\n
"},{"location":"canvasinput/#read-only","title":"Read only","text":"
  • Enable read only
    txt.setReadOnly();\n// txt.setReadOnly(true);\n
    or
    txt.readOnly = true;\n
  • Disable read only
    txt.setReadOnly(false);\n
    or
    txt.readOnly = false;\n
  • Get read only
    var readOnlyEanble = txt.readOnly;\n
"},{"location":"canvasinput/#size","title":"Size","text":"
  • Resize canvas size
    txt.setCanvasSize(width, height)\n
  • Reisze text wrapping size and canvas size.
    txt.setSize(width, height);\n
    or
    txt.setFixedSize(width, height);\n
  • Resize to minimun size to show all visible characters.
    txt.setToMinSize();\n
"},{"location":"canvasinput/#events","title":"Events","text":"
  • On text change
    txt.on('textchange', function(text, txt){\n})\n
  • On character child adding
    txt.on('addchar', function(child, index, canvasInput) {\nchild.modifyStyle({...})\n})\n
    • child : character child
  • On cursor moving out of a character child
    txt.on('cursorout', function(child, index, canvasInput) {\nchild.modifyStyle({...})\n})\n
    • child : character child
  • On cursor moving on a character child
    txt.on('cursorin', function(child, index, canvasInput) {\nchild.modifyStyle({...})\n})\n
    • child : character child
  • On open text-editor
    txt.on('open', function() {\n\n})\n
  • On close text-editor
    txt.on('close', function() {\n\n})\n
  • Close editor by ENTER key down
    txt.on('keydown-ENTER', function(){\n})\n
  • Not a number input
    txt.on('nan', function(text){\n\n})\n
"},{"location":"canvasinput/#select-text","title":"Select text","text":"

This feature does not support.

"},{"location":"canvasinput/#bypass-key-input","title":"Bypass key input","text":"

Registered keyboard events might capture key input.

var keyObj = scene.input.keyboard.addKey('W', enableCapture, emitOnRepeat);\n

Set enableCapture to false to bypass key input to this input-text game objecct.

"},{"location":"canvasinput/#other-properties","title":"Other properties","text":"

See Dynamic text game object game object

"},{"location":"canvasinput/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"canvasinput/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"capitalizes-first/","title":"Capitalizes first","text":""},{"location":"capitalizes-first/#introduction","title":"Introduction","text":"

Capitalizes the first letter of a string, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"capitalizes-first/#usage","title":"Usage","text":"
var result = Phaser.Utils.String.UppercaseFirst(str);\n
"},{"location":"charactercache/","title":"Character cache","text":""},{"location":"charactercache/#introduction","title":"Introduction","text":"

Generate bitmapfont from text game object, or bbcode text game object.

  • Author: Rex
  • Member of scene
"},{"location":"charactercache/#live-demos","title":"Live demos","text":"
  • Set text
  • Textbox
"},{"location":"charactercache/#usage","title":"Usage","text":"

Sample code

"},{"location":"charactercache/#install-plugin","title":"Install plugin","text":""},{"location":"charactercache/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcharactercacheplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcharactercacheplugin.min.js', true);\n
  • Add character-cache object
    var characterCache = scene.plugins.get('rexcharactercacheplugin').add(config);\n
"},{"location":"charactercache/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CharacterCachePlugin from 'phaser3-rex-plugins/plugins/charactercache-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCharacterCache',\nplugin: CharacterCachePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add character-cache object
    var characterCache = scene.plugins.get('rexCharacterCache').add(config);\n
"},{"location":"charactercache/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CharacterCache from 'phaser3-rex-plugins/plugins/charactercache.js';\n
  • Add character-cache object
    var characterCache = new CharacterCache(game, config);\n
    or
    var characterCache = new CharacterCache(scene, config);\n
"},{"location":"charactercache/#create-instance","title":"Create instance","text":"
var characterCache = scene.plugins.get('rexCharacterCache').add({\nkey: '',  cellWidth: 32,\ncellHeight: 32,\nmaxCharacterCount: 4096,\nfreqMode: true,\n\nstyle: textStyle,\n// textObject: textGameOject,\n\n\ncontent: '',\n});\n
  • key : Texture key in texture manager
  • cellWidth, cellHeight : Maximum frame size.
  • maxCharacterCount : Maximun character count.
    • Width of texture = Math.ceil(Math.sqrt(maxCharacterCount)) * cellWidth
    • Height of texture = Math.ceil(Math.sqrt(maxCharacterCount)) * cellHeight
  • freqMode :
    • true : Swap out un-unsed and low-frequence character.
    • false : Swap out any un-unsed character.
  • style : Style of Text game object. Create a text game object by this style setting on systemScene if textObject parameter is not given.
  • textObject : Text game object, or bbcode text game object for drawing character.
  • content : Load these characters into cache.
"},{"location":"charactercache/#create-bitmaptext","title":"Create BitmapText","text":"

Create BitmapText/Dynamci BitmapText game object using this character cache, add this game object into scene's display list

  • BitmapText
    var txt = characterCache.addBitmapText(scene);    // var txt = characterCache.addBitmapText(scene, x, y, text, size, align);\n
  • Dynamci BitmapText
    var txt = characterCache.addDynamicBitmapText(scene);    // var txt = characterCache.addDynamicBitmapText(scene, x, y, text, size, align);\n
"},{"location":"charactercache/#load-characters","title":"Load characters","text":"

Load characters into bitmap font, replace unused characters if no free character space.

characterCache.load(content);\n// characterCache.load(content, lock);\n
  • content : Characters in a string.
  • lock
    • true : Lock these characters, won't be replaced out later.
    • false : Don't lock these characters, can be replaced out later. Default behavior.

Warning

Console.warn messages if no unused character is found.

"},{"location":"charactercache/#events","title":"Events","text":"
  • Add a character
    characterCache.on('add', function(character, textObject) {\n// Can change style of textObject here\n})\n
  • Swap out a character
    characterCache.on('remove', function(character, textObject) {\n})\n
"},{"location":"charactercache/#override-bitmaptext","title":"Override bitmaptext","text":"

Inject characterCache.load(text) into bitmapText.setText(text) method.

characterCache.overrideBitmapText(bitmapText);\n// var bitmapText = characterCache.overrideBitmapText(bitmapText);\n

Now setText method has lock parameter : bitmapText.setText(text, lock).

Or user can override bitmapText.setText by extending Phaser.GameObjects.BitmapText class.

"},{"location":"charactercache/#unlock-all-characters","title":"Unlock all characters","text":"
characterCache.unlock();\n
"},{"location":"charactercache/#get-all-cache-data","title":"Get all cache data","text":"
var cacheData = characterCache.getAllData();\n
  • cacheData : Array of cache data
    {\ncharacter: string,\nfreq: number,\nalive: boolean,\nlock: boolean,\n}\n
"},{"location":"charactercache/#destroy-instance","title":"Destroy instance","text":"
characterCache.destroy();\n
"},{"location":"charactercache/#properties","title":"Properties","text":"
  • characterCache.key : Font key.
  • characterCache.cellWidth, characterCache.cellHeight : Cell size.
  • characterCache.inCacheCount : Amount of characters in cache.
"},{"location":"circlemaskimage/","title":"Circle mask image","text":""},{"location":"circlemaskimage/#introduction","title":"Introduction","text":"

Load a texture, then apply a circle mask. Extended from canvas plugin.

  • Author: Rex
  • Game object
"},{"location":"circlemaskimage/#live-demos","title":"Live demos","text":"
  • Circle-mask-image
"},{"location":"circlemaskimage/#usage","title":"Usage","text":"

Sample code

"},{"location":"circlemaskimage/#install-plugin","title":"Install plugin","text":""},{"location":"circlemaskimage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcirclemaskimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcirclemaskimageplugin.min.js', true);\n
  • Add circle-mask-image object
    var image = scene.add.rexCircleMaskImage(x, y, key, frame, config);\n
"},{"location":"circlemaskimage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CircleMaskImagePlugin from 'phaser3-rex-plugins/plugins/circlemaskimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCircleMaskImagePlugin',\nplugin: CircleMaskImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add circle-mask-image object
    var image = scene.add.rexCircleMaskImage(x, y, key, frame, config);\n
"},{"location":"circlemaskimage/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CircleMaskImage from 'phaser3-rex-plugins/plugins/circlemaskimage.js';\n
  • Add circle-mask-image object
    var image = new CircleMaskImage(scene, x, y, key, frame, config);\nscene.add.existing(image);\n
"},{"location":"circlemaskimage/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCircleMaskImagePlugin',\nplugin: CircleMaskImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"circlemaskimage/#create-instance","title":"Create instance","text":"
var image = scene.add.rexCircleMaskImage(x, y, key, frame, {\nmaskType: 0,\n// radius: undefined,\n\n// backgroundColor: undefined,\n\n// strokeColor: undefined,\n// strokeWidth: 0,\n});\n

or

var image = scene.add.rexCircleMaskImage(x, y, key, {\nmaskType: 0,\n// radius: undefined,\n\n// backgroundColor: undefined,\n\n// strokeColor: undefined,\n// strokeWidth: 0,\n});\n
  • maskType : Type of mask.
    • null : No mask.
    • 'circle', or 0 : Circle mask.
    • 'ellipse', or 1 : Ellipse mask.
    • 'roundRectangle', or 2 : Round rectangle mask.
  • radius : Radius of round rectangle mask.
    • 0 : Disable round corner.
    • Number: 4 corners with the same radius.
    • JSON
      • 4 corners with the same radius X/Y
        {\nx: radiusX,\ny: radiusY\n}\n
      • Eeach radius of corner
        {\ntl: radius,\ntr: radius,\nbl: radius,\nbr: radius\n}\n
        or
        {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n}\n
  • backgroundColor : Fill background with color.
    • undefined, or null : No background filling. Default behavior.
  • strokeColor : Add stroke around masked image.
    • undefined, or null : No stroke line. Default behavior.
  • strokeWidth : Stroke line width.

Add image from JSON

var image = scene.make.rexCircleMaskImage({\nx: 0,\ny: 0,\nkey: key,\nframe: name,\nmaskType: 0,\n// radius: undefined\n// origin: {x: 0.5, y: 0.5},\n\n// backgroundColor: undefined,\n\n// strokeColor: undefined,\n// strokeWidth: 0,\n\nadd: true\n});\n
"},{"location":"circlemaskimage/#custom-class","title":"Custom class","text":"
  • Define class
    class MyImage extends CircleMaskImage {\nconstructor(scene, x, y, key, frame, config) {\nsuper(scene, x, y, key, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyImage(scene, key, frame, config);\n
"},{"location":"circlemaskimage/#set-texture","title":"Set texture","text":"
image.setTexture(key, frame);\n// image.setTexture(key, frame, maskType);\n

or

image.setTexture(key, frame, {\nmaskType: 0,\n// radius: undefined\n});\n
  • maskType : Type of mask
    • null : No mask.
    • 0, or 'circle' : Circle mask. Default value.
    • 1, or 'ellipse' : Ellipse mask.
  • radius : Radius of round rectangle mask.
    • 0 : Disable round corner.
    • Number: 4 corners with the same radius.
    • JSON
      • 4 corners with the same radius X/Y
        {\nx: radiusX,\ny: radiusY\n}\n
      • Eeach radius of corner
        {\ntl: radius,\ntr: radius,\nbl: radius,\nbr: radius\n}\n
        or
        {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n}\n
"},{"location":"circlemaskimage/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"circlemaskimage/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"circlemaskimage/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"clamp/","title":"Clamp","text":""},{"location":"clamp/#introduction","title":"Introduction","text":"

Force a value within the boundaries by clamping it to the range min, max, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"clamp/#usage","title":"Usage","text":"
var result = Phaser.Math.Clamp(value, min, max);\n
  • value : The value to be clamped.
"},{"location":"clickoutside/","title":"Click outside","text":""},{"location":"clickoutside/#introduction","title":"Introduction","text":"

Fires 'clickoutside' event when pointer-down or pointer-up outside of game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"clickoutside/#live-demos","title":"Live demos","text":"
  • Click outside
"},{"location":"clickoutside/#usage","title":"Usage","text":"

Sample code

"},{"location":"clickoutside/#install-plugin","title":"Install plugin","text":""},{"location":"clickoutside/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexclickoutsideplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexclickoutsideplugin.min.js', true);\n
  • Add click-outside behavior
    var clickOutside = scene.plugins.get('rexclickoutsideplugin').add(gameObject, config);\n
"},{"location":"clickoutside/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ClickOutsidePlugin from 'phaser3-rex-plugins/plugins/clickoutside-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexClickOutsiden',\nplugin: ClickOutsidePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add click-outside behavior
    var clickOutside = scene.plugins.get('rexClickOutsiden').add(gameObject, config);\n
"},{"location":"clickoutside/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ClickOutside from 'phaser3-rex-plugins/plugins/clickoutside.js';\n
  • Add clickoutside behavior
    var clickOutside = new ClickOutside(gameObject, config);\n
"},{"location":"clickoutside/#create-instance","title":"Create instance","text":"
var clickOutside = scene.plugins.get('rexClickOutside').add(gameObject, {\n// enable: true,\n// mode: 1,              // 0|'press'|1|'release'\n// clickInterval: 100,   // ms\n// threshold: undefined\n});\n
  • enable : Clickable.
  • mode :
    • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
    • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
  • clickInterval : Interval between 2 'click' events, in ms.
  • threshold : Cancel clicking detecting when dragging distance is larger then this threshold.
    • undefined : Ignore this feature. Default behavior.
"},{"location":"clickoutside/#events","title":"Events","text":"
  • Click-outside
    clickOutside.on('clickoutside', function (clickoutside, gameObject, pointer) {\n// ...\n}, scope);\n
  • Enable
    clickOutside.on('enable', function (clickoutside, gameObject) {\n// ...\n}, scope);\n
  • Disable
    clickOutside.on('disable', function (clickoutside, gameObject) {\n// ...\n}, scope);\n
"},{"location":"clickoutside/#enable","title":"Enable","text":"
  • Get
    var enabled = clickOutside.enable;  // enabled: true, or false\n
  • Set
    clickOutside.setEnable(enabled);  // enabled: true, or false\n// clickOutside.enable = enabled;\n
  • Toggle
    clickOutside.toggleEnable();\n
"},{"location":"clickoutside/#set-mode","title":"Set mode","text":"
clickOutside.setMode(mode);\n
  • mode :
    • 'press', or 0 : Fire 'click' event when touch pressed.
    • 'release', or 1 : Fire 'click' event when touch released after pressed.
"},{"location":"clickoutside/#set-click-interval","title":"Set click interval","text":"
clickOutside.setClickInterval(interval);  // interval in ms\n
"},{"location":"clickoutside/#set-dragging-threshold","title":"Set dragging threshold","text":"
clickOutside.setDragThreshold(distance);  // distance in pixels\n
"},{"location":"clock/","title":"Clock","text":""},{"location":"clock/#introduction","title":"Introduction","text":"

A clock to count elapsed time.

  • Author: Rex
  • Member of scene
"},{"location":"clock/#usage","title":"Usage","text":"

Sample code

"},{"location":"clock/#install-plugin","title":"Install plugin","text":""},{"location":"clock/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexclockplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexclockplugin.min.js', true);\n
  • Add clock object
    var clock = scene.plugins.get('rexclockplugin').add(scene, config);\n
"},{"location":"clock/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ClockPlugin from 'phaser3-rex-plugins/plugins/clock-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexClock',\nplugin: ClockPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add clock object
    var clock = scene.plugins.get('rexClock').add(scene, config);\n
"},{"location":"clock/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Clock from 'phaser3-rex-plugins/plugins/clock.js';\n
  • Add clock object
    var clock = new Clock(scene, config);\n
"},{"location":"clock/#create-instance","title":"Create instance","text":"
var clock = scene.plugins.get('rexClock').add(scene, {\n// timeScale: 1\n});\n
  • timeScale : time-scale for counting elapsed time.
"},{"location":"clock/#start-counting","title":"Start counting","text":"
clock.start();\n// clock.start(startAt);  // start-at time in ms\n
"},{"location":"clock/#force-ticking","title":"Force ticking","text":"
clock.tick(0);\n// clock.tick(delta);\n
"},{"location":"clock/#get-elapsed-time","title":"Get elapsed time","text":"
var now = clock.now;  // Elapsed time in ms\n
"},{"location":"clock/#pause-resume-stop-counting","title":"Pause, Resume, stop counting","text":"
clock.pause();\nclock.resume();\nclock.stop();\n
"},{"location":"clock/#seek-elapsed-time","title":"Seek elapsed time","text":"
clock.seek(time);   // elapsed time in ms\n
"},{"location":"clock/#state-of-counting","title":"State of counting","text":"
var isRunning = clock.isRunning;\n
"},{"location":"clock/#time-scale","title":"Time-scale","text":"
  • Get
    var timeScale = clock.timeScale;\n
  • Set
    clock.setTimeScale(timeScale);\n// clock.timeScale = timeScale;\n
"},{"location":"clock/#events","title":"Events","text":"
  • On ticking
    clock.on('update', function(now, delta){ })\n
    • now : Elapsed time in ms.
    • delta : Delta time in ms.
"},{"location":"color/","title":"Color","text":""},{"location":"color/#introduction","title":"Introduction","text":"

Get color value, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"color/#usage","title":"Usage","text":""},{"location":"color/#get-color-integer","title":"Get color integer","text":"
  • Hex string, or color integer
    var color = Phaser.Display.Color.ValueToColor(input);\n
    • input : Hex string, or color integer
  • RGB to color
    var color = Phaser.Display.Color.GetColor(red, green, blue);\n
    • red, green, blue : 0 ~ 255
  • RGBA to color
    var color = Phaser.Display.Color.GetColor32(red, green, blue, alpha);\n
    • red, green, blue, alpha : 0 ~ 255
  • Hex string to color
    var color = Phaser.Display.Color.HexStringToColor(hex).color;\n
    • hex : #0033ff, #03f, 0x0033ff, or 0x03f
  • RGB string to color
    var color = Phaser.Display.Color.RGBStringToColor(rgb);\n
    • rgb : 'rgb(r,g,b)', or 'rgba(r,g,b,a)'
      • r, g, b : 0 ~ 255
      • a : 0 ~ 1
  • HSV to color
    var color = Phaser.Display.Color.HSVToRGB(h, s, v).color;\n
    • h, s, v : 0 ~ 1
"},{"location":"color/#color-integer-to-rgb","title":"Color integer to RGB","text":"
var rgb = Phaser.Display.Color.IntegerToRGB(color);\n
  • color : Color integer (0xAARRGGBB)
  • rgb : JSON object ({r, g, b, a})
"},{"location":"color/#hsv-color-wheel","title":"HSV color wheel","text":"
  1. Create color array
    var colorArray = Phaser.Display.Color.HSVColorWheel(s, v);\n
  2. Get color
    var color = colorArray[i].color;  // i : 0 ~ 359\n
"},{"location":"color/#color-object","title":"Color object","text":""},{"location":"color/#create-color-object","title":"Create color object","text":"
  • Create via r,g,b,a components
    var color = new Phaser.Display.Color(red, green, blue); // alpha = 255\n// var color = new Phaser.Display.Color(red, green, blue, alpha);\n
    • red, green, blue, alpha: 0 ~ 255
  • Create via color integer
    var color = Phaser.Display.Color.IntegerToColor(colorInteger);\n
    • colorInteger : Color integer (0xAARRGGBB)
"},{"location":"color/#set-color","title":"Set color","text":"
  • Set color
    color.setTo(red, green, blue);  // alpha = 255\n// color.setTo(red, green, blue, alpha);\n
    • red, green, blue, alpha: 0 ~ 255
  • Set color in GL values
    color.setGLTo(red, green, blue);  // alpha = 1\n// color.setTo(red, green, blue, alpha);\n
    • red, green, blue, alpha: 0 ~ 1
  • Set color from color object
    color.setFromRGB(rgba);\n
    • rgba :
      {\nr: 0,\ng: 0,\nb: 0,\n// a: 0\n}\n
  • Set color from HSV
    color.setFromHSV(h, s, v);\n
  • Set to transparent ()
    color.transparent();\n
    • Set (red, green, blue) to 0
  • Set to gray color
    color.gray(value);\n
  • Set to a random color
    color.random();\n
    or
    color.random(min, max);\n
    • min : 0 ~ 255. Default value is 0.
    • max : 0 ~ 255. Default value is 255.
  • Set to random gray
    color.randomGray();\n
    or
    color.randomGray(min, max);\n
  • Set red/green/blue/alpha channel : 0 ~ 255
    color.red = value;\n// color.red += value;\ncolor.green = value;\n// color.green += value;\ncolor.blue = value;\n// color.blue += value;\ncolor.alpha = value;\n// color.alpha += value;\n
  • Set H/S/V channel : 0 ~ 1
    color.h = value;\n// color.h += value;\ncolor.s = value;\n// color.s += value;\ncolor.v = value;\n// color.v += value;\n
  • Set normalized red, green, blue, alpha : 0 ~ 1
    color.redGL = value;\n// color.redGL += value;\ncolor.greenGL = value;\n// color.greenGL += value;\ncolor.blueGL = value;\n// color.blueGL += value;\ncolor.alphaGL = value;\n// color.alphaGL += value;\n
  • Set brighten
    color.brighten(value);\n
    • value : Percentage, 0 ~ 100
  • Saturate : Increase the saturation (S) of this Color by the percentage amount given.
    color.saturate(value);\n
    • value : Percentage, 0 ~ 100
  • Desaturate : Decrease the saturation (S) of this Color by the percentage amount given.
    color.desaturate(value);\n
    • value : Percentage, 0 ~ 100
  • Lighten : Increase the lightness (V) of this Color by the percentage amount given.
    color.lighten(value);\n
    • value : Percentage, 0 ~ 100
  • Darken : Decrease the lightness (V) of this Color by the percentage amount given.
    color.darken(value);\n
    • value : Percentage, 0 ~ 100
"},{"location":"color/#properties","title":"Properties","text":"
  • RGB Color, not including the alpha channel
    var c = color.color;\n
  • RGB Color, including the alpha channel.
    var c = color.color32;\n
  • RGB color string which can be used in CSS color values.
    var c = color.rgba;\n
  • Red, green, blue, alpha : 0 ~ 255
    var r = color.red;\nvar g = color.green;\nvar b = color.blue;\nvar a = color.alpha;\n
  • H, S, V : 0 ~ 1
    var h = color.h;\nvar s = color.s;\nvar v = color.v;\n
  • Normalized red, green, blue, alpha : 0 ~ 1
    var r = color.redGL;\nvar g = color.greenGL;\nvar b = color.blueGL;\nvar a = color.alphaGL;\n
"},{"location":"color/#clone","title":"Clone","text":"
var newColor = color.clone();\n
"},{"location":"color/#to-hex-string","title":"To hex string","text":"
var hexString = Phaser.Display.Color.RGBToString(color.r, color.g, color.b, color.a);\n// var hexString = Phaser.Display.Color.RGBToString(color.r, color.g, color.b, color.a, prefix);\n
"},{"location":"color/#interpolation","title":"Interpolation","text":"

Interpolate between 2 colors.

var colorOut = Phaser.Display.Color.Interpolate.RGBWithRGB(r1, g1, b1, r2, g2, b2, length, index);\nvar colorOut = Phaser.Display.Color.Interpolate.ColorWithColor(color1, color2, length, index);\nvar colorOut = Phaser.Display.Color.Interpolate.ColorWithRGB(color, r, g, b, length, index);\n
  • length, index : t = index/length (0~1)
"},{"location":"conditionstable/","title":"CSV Conditions table","text":""},{"location":"conditionstable/#introduction","title":"Introduction","text":"

Check conditions to find passed tests listed in a csv table.

  • Author: Rex
  • Member of scene
"},{"location":"conditionstable/#usage","title":"Usage","text":"

Sample code

"},{"location":"conditionstable/#install-plugin","title":"Install plugin","text":""},{"location":"conditionstable/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexconditionstableplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexconditionstableplugin.min.js', true);\n
  • Add conditions-table object
    var conditionstable = scene.plugins.get('rexconditionstableplugin').add();\n
"},{"location":"conditionstable/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ConditionsTablePlugin from 'phaser3-rex-plugins/plugins/conditionstable-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexConditionsTable',\nplugin: ConditionsTablePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add conditions-table object
    var conditionstable = scene.plugins.get('rexConditionsTable').add();\n
"},{"location":"conditionstable/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ConditionsTable from 'phaser3-rex-plugins/plugins/conditionstable.js';\n
  • Add conditions-table object
    var conditionstable = new ConditionsTable();\n
"},{"location":"conditionstable/#create-instance","title":"Create instance","text":"
var table = scene.plugins.get('rexConditionsTable').add();\n
"},{"location":"conditionstable/#load-table-from-csv-string","title":"Load table from csv string","text":"
table.loadCSV(csvString, {\n// delimiter: ','\n});\n

For exameple, csv string

name A A B Test1 >= 10 <= 20 Test2 3
,A,A,B\nTest1,>= 10,<= 20,\nTest2,,,3\n

means that:

Test1: (A>=10) && (A<=20)\nTest2: (B==3)\n

Equations will be evaled by new Function.

"},{"location":"conditionstable/#test","title":"Test","text":""},{"location":"conditionstable/#get-test-results","title":"Get test results","text":"
var results = table.getTestResults(context);\n
  • context : Inputs in Key-value pairs
  • results : {name: boolean}, use OR operation to combine result of tests with the same name.
"},{"location":"conditionstable/#get-first-pass-test-name","title":"Get first pass test name","text":"
var testName = table.anyPassTest(context);\n
  • context : Inputs in Key-value pairs
"},{"location":"config-data/","title":"Configuration data","text":""},{"location":"config-data/#introduction","title":"Introduction","text":"

Get parameters from configuration object.

  • Author: Richard Davey
"},{"location":"config-data/#usage","title":"Usage","text":""},{"location":"config-data/#quick-start","title":"Quick start","text":"
const GetValue = Phaser.Utils.Objects.GetValue;\nvar myMethod = function(config) {\nvar x = GetValue(config, 'x', 0);\nvar y = GetValue(config, 'y', 0);\nvar width = GetValue(config, 'width', 0);\nvar height = GetValue(config, 'height', 0);\n// ...\n}\n
"},{"location":"config-data/#get-value","title":"Get value","text":"
  • Retrieves a value from an object.
    var value = Phaser.Utils.Objects.GetValue(source, key, defaultValue);\n
    • source : Configuration object.
    • key : The name of the property to retrieve from the object. For example,
      • Property source.name, key = name
      • Property source.position.x, key = position.x
    • defaultValue : The value to return if the key isn't found in the source object.
  • Finds the key within the top level of the source object, or returns defaultValue.
    var value = Phaser.Utils.Objects.GetFastValue(source, key, defaultValue);\n
    • key : The key for the property on source. Must exist at the top level of the source object.
  • Retrieves a value from an object. Allows for more advanced selection options.
    var value = Phaser.Utils.Objects.GetAdvancedValue(source, key, defaultValue);\n
    • Implicit
      var source = {x: 4};\nvar value = Phaser.Utils.Objects.GetAdvancedValue(source, 'x'); // value = 4\n
    • From function
      var source = {x: function(key){return 4;}};\nvar value = Phaser.Utils.Objects.GetAdvancedValue(source, 'x'); // value = 4\n
      • Pass key to function's 1st parameter, and get return value as final result.
    • Randomly pick one element from the array
      var source = {x: [a, b, c]};\nvar value = Phaser.Utils.Objects.GetAdvancedValue(source, 'x'); // value = random item from array [a, b, c]\n
    • Random integer between min and max
      var source = {x: randInt: [min, max]};\nvar value = Phaser.Utils.Objects.GetAdvancedValue(source, 'x'); // value = random int min~max\n
    • Random float between min and max
      var source = {x: randFloat: [min, max]};\nvar value = Phaser.Utils.Objects.GetAdvancedValue(source, 'x'); // value = random float min~max\n
"},{"location":"config-data/#is-plain-object","title":"Is plain object","text":"
var isPlainObject = Phaser.Utils.Objects.IsPlainObject(object);\n

Plain object:

  • var obj = {};
  • var obj = new Object();
"},{"location":"config-data/#merge-configuration","title":"Merge configuration","text":"
var configOut = Phaser.Utils.Objects.Merge(configIn, defaultConfig);\n
"},{"location":"container/","title":"Container","text":""},{"location":"container/#introduction","title":"Introduction","text":"

Control the position and angle of children game objects, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"container/#usage","title":"Usage","text":""},{"location":"container/#container","title":"Container","text":""},{"location":"container/#add-container-object","title":"Add container object","text":"
var container = scene.add.container(x, y);\n// var container = scene.add.container(x, y, children); // children: an array of game object\n
"},{"location":"container/#custom-class","title":"Custom class","text":"
  • Define class
    class MyContainer extends Phaser.GameObjects.Container {\nconstructor(scene, x, y, children) {\nsuper(scene, x, y, children);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var container = new MyContainer(scene, x, y, children);\n
"},{"location":"container/#destroy","title":"Destroy","text":"
container.destroy();\n

Also destroy all children game objects.

"},{"location":"container/#set-properties","title":"Set properties","text":"

Reference game object, to set position, angle, visible, alpha, etc...

"},{"location":"container/#set-size","title":"Set size","text":"
container.setSize(width, height);\n

Default size is 0x0.

"},{"location":"container/#set-scroll-factor","title":"Set scroll factor","text":"
container.setScrollFactor(x, y);\n

Apply this scrollFactor to all Container children.

container.setScrollFactor(x, y, true);\n
"},{"location":"container/#hit-area","title":"Hit area","text":"
container.setInteractive(new Phaser.Geom.Circle(0, 0, radius), Phaser.Geom.Circle.Contains);\n// container.setInteractive(false); // disable\n

Assign hit area with a circle shape.

"},{"location":"container/#non-exclusive","title":"Non-exclusive","text":"
container.setExclusive(false);\n

Allows a game object added to container many times.

"},{"location":"container/#children","title":"Children","text":""},{"location":"container/#add-child","title":"Add child","text":"
container.add(child);  // child: a game object or an array of game objects\n
container.addAt(child, index);\n
"},{"location":"container/#exist","title":"Exist","text":"
var hasChild = container.exists(child);\n
"},{"location":"container/#get-child","title":"Get child","text":"
var firstChild = container.first;\nvar nextChild = container.next;\nvar prevChild = container.previous;\nvar lastChild = container.last;\n
var child = container.getByName(name);\n
var child = container.getRandom(startIndex, length);\n
var child = container.getFirst(property, value, startIndex, endIndex);\n// value: the value to test the property against. Must pass a strict (`===`) comparison check.\n
var children = container.getAll(property, value, startIndex, endIndex);\n// value: the value to test the property against. Must pass a strict (`===`) comparison check.\n
var amount = container.count(property, value, startIndex, endIndex);\n// value: the value to test the property against. Must pass a strict (`===`) comparison check.\n
"},{"location":"container/#sort-children","title":"Sort children","text":"
container.sort(property);\n
container.sort(property, function(childA, childB){\nreturn 0; // 0, 1, -1\n});\n
"},{"location":"container/#remove-child","title":"Remove child","text":"
container.remove(child);\n// container.remove(child, true);  // remove child object and destroy it\n
container.removeAt(index);\n// container.removeAt(index, true);  // remove child object and destroy it\n
container.removeBetween(startIndex, endIndex);\n// container.removeBetween(startIndex, endIndex, true);  // remove children objects and destroy them\n
container.removeAll();\n// container.removeAll(true);  // remove all children objects and destroy them\n

Removing child from container without destroying will put back into scene's display list.

"},{"location":"container/#order-of-child","title":"Order of child","text":"
container.moveTo(child, index);\n
container.bringToTop(child);\n
container.sendToBack(child);\n
container.moveUp(child);\n
container.moveDown(child);\n
container.moveAbove(child1, child2);  // Move child1 above child2\n
container.moveBelow(child1, child2);  // Move child1 below child2\n
container.swap(child1, child2);\n
container.reverse();\n
container.shuffle();\n
"},{"location":"container/#replace-child","title":"Replace child","text":"
container.replace(oldChild, newChild);\n// container.replace(oldChild, newChild, true);  // destroy oldChild\n
"},{"location":"container/#set-properties_1","title":"Set properties","text":"
container.setAll(property, value, startIndex, endIndex);\n
"},{"location":"container/#for-each-child","title":"For each child","text":"
  • Iterate current children list
    container.iterate(callback);\n// container.iterate(callback, context);\n// container.iterate(callback, context, arg0, arg1, ...);\n
    • callback :
      function(child, arg0, arg1, ...) {\n\n}\n
  • Iterate a copy of current children list
    container.each(callback);\n// container.each(callback, context);\n// container.each(callback, context, arg0, arg1, ...);\n
    • callback :
      function(child, arg0, arg1, ...) {\n\n}\n
"},{"location":"container/#get-world-position-rotation-scale","title":"Get world position, rotation, scale","text":"
var matrix = child.getWorldTransformMatrix();\nvar x = matrix.tx;\nvar y = matrix.ty;\nvar rotation = matrix.rotation;\nvar scaleX = matrix.scaleX;\nvar scaleY = matrix.scaleY;\n
"},{"location":"container/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"container/#create-mask","title":"Create mask","text":"
var mask = container.createBitmapMask();\n

See mask

"},{"location":"container/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"container/#compare-with-group-object","title":"Compare with group object","text":"
  • Container and group objects are all have a children list.
  • Container has position, angle, alpha, visible, ...etc, but group does not have.
  • Container controls properties of children (position, angle, alpha, visible, ...etc), but group won't.
  • A game object could be added to many groups, but it only could be added to one container (exclusive mode).
"},{"location":"containerlite-perspective/","title":"Perspective","text":""},{"location":"containerlite-perspective/#introduction","title":"Introduction","text":"

Snapshot children of containerlite, to a perspective render texture.

  • Author: Rex
  • Behavior of containerlite
"},{"location":"containerlite-perspective/#live-demos","title":"Live demos","text":"
  • Flip ui
"},{"location":"containerlite-perspective/#usage","title":"Usage","text":"

Sample code

"},{"location":"containerlite-perspective/#install-plugin","title":"Install plugin","text":""},{"location":"containerlite-perspective/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add perspective behavior
    // var container = scene.add.rexContainerLite(x, y);\nvar perspective = scene.plugins.get('rexperspectiveimageplugin').addContainerPerspective(container, config);\n
"},{"location":"containerlite-perspective/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add perspective behavior
    // var container = scene.add.rexContainerLite(x, y);\nvar perspective = scene.plugins.get('rexPerspectiveImagePlugin').addContainerPerspective(container, config);\n
"},{"location":"containerlite-perspective/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ContainerPerspective } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add perspective behavior
    // var container = scene.add.rexContainerLite(x, y);\nvar perspective = new ContainerPerspective(container, config);\n
"},{"location":"containerlite-perspective/#create-instance","title":"Create instance","text":"
var perspective = scene.plugins.get('rexPerspectiveImagePlugin').addContainerPerspective(container, {\nuseParentBounds: false,\n// hideCCW: true,\n});\n
  • useParentBounds :
    • true : Use bounds of parent container
    • false : Union all visible children's bounds
  • hideCCW :
    • true : Hide backward facing Faces. Default behavior.
    • false : Show backward facing Faces
"},{"location":"containerlite-perspective/#perspective-mode","title":"Perspective mode","text":""},{"location":"containerlite-perspective/#enter","title":"Enter","text":"
perspective.enter();\n
  1. Snapshot current visible children into perspective render texture
  2. Set current visible children to invisible
  3. Set this perspective render texture to visible
"},{"location":"containerlite-perspective/#exit","title":"Exit","text":"
perspective.exit();\n
  1. Inverse visible of children and perspective render texture
"},{"location":"containerlite-perspective/#is-in-perspective-mode","title":"Is in perspective mode","text":"
var isInPerspectiveMode = perspective.perspectiveState;\n
"},{"location":"containerlite-perspective/#rotation","title":"Rotation","text":"
  • Get rotation angle
    var angleX = perspective.angleX; // Angle in degrees\nvar angleY = perspective.angleY; // Angle in degrees\nvar angleZ = perspective.angleZ; // Angle in degrees\n
    or
    var rotationX = perspective.rotationX; // Angle in radians\nvar rotationY = perspective.rotationY; // Angle in radians\nvar rotationZ = perspective.rotationZ; // Angle in radians\n
  • Set rotation angle
    perspective.angleX = angleX; // Angle in degrees\nperspective.angleY = angleY; // Angle in degrees\nperspective.angleZ = angleZ; // Angle in degrees\n
    or
    perspective.rotationX = rotationX; // Angle in radians\nperspective.rotationY = rotationY; // Angle in radians\nperspective.rotationZ = rotationZ; // Angle in radians\n
"},{"location":"containerlite-perspective/#flip","title":"Flip","text":"
scene.tweens.add({\ntargets: perspective,\nangleY: { start: 0, to: -180}\n})\n
"},{"location":"containerlite-perspective/#other-properties","title":"Other properties","text":"

See Perspective rendertexture game object.

"},{"location":"containerlite-skew/","title":"Skew","text":""},{"location":"containerlite-skew/#introduction","title":"Introduction","text":"

Snapshot children of containerlite, to a skew render texture.

  • Author: Rex
  • Behavior of containerlite
"},{"location":"containerlite-skew/#live-demos","title":"Live demos","text":"
  • Skew ui
"},{"location":"containerlite-skew/#usage","title":"Usage","text":"

Sample code

"},{"location":"containerlite-skew/#install-plugin","title":"Install plugin","text":""},{"location":"containerlite-skew/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquadimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquadimageplugin.min.js', true);\n
  • Add skew behavior
    // var container = scene.add.rexContainerLite(x, y);\nvar skew = scene.plugins.get('rexquadimageplugin').addContainerSkew(container, config);\n
"},{"location":"containerlite-skew/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuadImagePlugin from 'phaser3-rex-plugins/plugins/quadimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuadImagePlugin',\nplugin: QuadImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add skew behavior
    // var container = scene.add.rexContainerLite(x, y);\nvar skew = scene.plugins.get('rexQuadImagePlugin').addContainerSkew(container, config);\n
"},{"location":"containerlite-skew/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ContainerSkew } from 'phaser3-rex-plugins/plugins/quadimage.js';\n
  • Add skew behavior
    // var container = scene.add.rexContainerLite(x, y);\nvar skew = new ContainerSkew(container, config);\n
"},{"location":"containerlite-skew/#create-instance","title":"Create instance","text":"
var quad = scene.plugins.get('rexQuadImagePlugin').addContainerSkew(container, {\nuseParentBounds: false\n});\n
  • useParentBounds :
    • true : Use bounds of parent container
    • false : Union all visible children's bounds
"},{"location":"containerlite-skew/#skew-mode","title":"Skew mode","text":""},{"location":"containerlite-skew/#enter","title":"Enter","text":"
skew.enter();\n
  1. Snapshot current visible children into skew render texture
  2. Set current visible children to invisible
  3. Set this skew render texture to visible
"},{"location":"containerlite-skew/#exit","title":"Exit","text":"
skew.exit();\n
  1. Inverse visible of children and skew render texture
"},{"location":"containerlite-skew/#is-in-skew-mode","title":"Is in skew mode","text":"
var isInSkewMode = skew.skewState;\n
"},{"location":"containerlite-skew/#skew","title":"Skew","text":"
  • Set
    image.setSkewX(skewXRad);\nimage.setSkewXDeg(skewXDeg);\n
    image.setSkewY(skewXRad);\nimage.setSkewYDeg(skewXDeg);\n
    image.setSkew(skewXRad, skewYRad);\nimage.setSkewDeg(skewXDeg, skewYDeg);\n
    image.skewX = skewXRad;\nimage.skewXDeg = skewXDeg;\n
    image.skewY = skewYRad;\nimage.skewYDeg = skewYDeg;\n
  • Get
    var skewXRad = image.skewX;\nvar skewXDeg = image.skewXDeg;\n
    var skewYRad = image.skewY;\nvar skewYDeg = image.skewYDeg;\n
"},{"location":"containerlite-skew/#other-properties","title":"Other properties","text":"

See Skew rendertexture game object.

"},{"location":"containerlite/","title":"Container Lite","text":""},{"location":"containerlite/#introduction","title":"Introduction","text":"

Control the position and angle of children game objects.

It is inspired from Ziao/phaser3-interim-containers.

  • Author: Rex
  • Game object
"},{"location":"containerlite/#live-demos","title":"Live demos","text":"
  • Rotate, alpha
  • Tween child
  • Create tween config
  • Mix timeline
  • Snapshot
  • Destroy:
    • Destroy containerLite
    • Destory scrollablePanel,
  • Add to p3-container
"},{"location":"containerlite/#usage","title":"Usage","text":"

Sample code

"},{"location":"containerlite/#install-plugin","title":"Install plugin","text":""},{"location":"containerlite/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcontainerliteplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcontainerliteplugin.min.js', true);\n
  • Add container object
    var container = scene.add.rexContainerLite(x, y);\n
"},{"location":"containerlite/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ContainerLitePlugin from 'phaser3-rex-plugins/plugins/containerlite-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexContainerLitePlugin',\nplugin: ContainerLitePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add container object
    var container = scene.add.rexContainerLite(x, y);\n
"},{"location":"containerlite/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ContainerLite from 'phaser3-rex-plugins/plugins/containerlite.js';\n
  • Add container object
    var container = new ContainerLite(scene, x, y);\nscene.add.existing(container);\n
"},{"location":"containerlite/#add-container-object","title":"Add container object","text":"
var container = scene.add.rexContainerLite(x, y);  // width = 1, height = 1\n// var container = scene.add.rexContainerLite(x, y, width, height);\n

or

var container = scene.add.rexContainerLite(x, y, children);  // width = 1, height = 1\n// var container = scene.add.rexContainerLite(x, y, width, height, children);\n

Add container from JSON

var container = scene.make.rexContainerLite({\nx: 0,\ny: 0,\nwidth: 1,\nheight: 1,\n\n// angle: 0,\n// alpha: 1,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n});\n
"},{"location":"containerlite/#custom-class","title":"Custom class","text":"
  • Define class
    class MyContainer extends ContainerLite {\nconstructor(scene, x, y, width, height, children) {\nsuper(scene, x, y, width, height, children);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var container = new MyContainer(scene, x, y, width, height, children);\n
"},{"location":"containerlite/#destroy","title":"Destroy","text":"
container.destroy();\n

Also destroy all children.

"},{"location":"containerlite/#other-properties","title":"Other properties","text":"

This container game object inherits from Zone.

"},{"location":"containerlite/#add-child","title":"Add child","text":""},{"location":"containerlite/#pin","title":"Pin","text":"

Add(pin) a game obejct to container

container.add(child);  // child: a game object\n// container.pin(child);\n
  • child : A game object

or

container.pin(child, {\n// syncPosition: true,\n// syncRotation: true,\n// syncScale : true,\n// syncAlpha: true,\n// syncScrollFactor: true,\n// syncCameraFilter: true,\n// syncDisplayList: true\n});\n
  • child : A game object
  • syncPosition :
    • true : Sync position of child, default behavior.
    • false : Don't sync position of child.
  • syncRotation :
    • true : Sync angle of child, default behavior.
    • false : Don't sync angle of child.
  • syncScale :
    • true : Sync scale of child, default behavior.
    • false : Don't sync angle of child.
  • syncAlpha :
    • true : Sync alpha of child, default behavior.
    • false : Don't sync alpha of child.
  • syncScrollFactor :
    • true : Sync scrollFactor of child, default behavior.
    • false : Don't sync scrollFactor of child.
  • syncCameraFilter :
    • true : Sync cameraFilter of child, default behavior.
    • false : Don't sync cameraFilter of child.
  • syncDisplayList :
    • true : Put child into parent's displayList/Layer, default behavior.
      • Child has to belong to any displayList first.
    • false : Don't change child's displayList.

Or add(pin) children

container.addMultiple(children);\n// container.add(children);\n
  • children : An array of game objects

These world properties of children will be changed with container.

  • Position/Angle/Scale
  • Visible
  • Alpha
  • Scroll factor
  • Mask

Note

  • Position of child is the world position, i.e. position of child won't be changed when adding to container initially.
    • For example, container-lite is at (100, 100), and child is at (110, 110), then child will be placed at (110, 110) after adding to container-lite.
  • This behavior is different from official container, which using related position of child when adding to container.
    • For example, official container is at (100, 100), and child is at (10, 10), then child will be placed at (110, 110) after adding to official container.
"},{"location":"containerlite/#add-local","title":"Add local","text":"
container.addLocal(child);\n

or

container.addLocalMultiple(children);\n

or

container.pinLocal(child, {\n// syncPosition: true,\n// syncRotation: true,\n// syncScale : true,\n// syncAlpha: true,\n});\n

Add child to container with related properties, like official container. For example, container-lite is at (100, 100), and child is at (10, 10), then child will be placed at (110, 110) after adding to container-lite.

"},{"location":"containerlite/#remove-child","title":"Remove child","text":"
  • Remove(unpin) a child
    container.remove(child);\n// container.remove(child, destroyChild);\n
    or
    container.unpin(child);\n// container.unpin(child, destroyChild);\n
    • child : Game object
    • destroyChild : Set true to destroy child. Default is false.
  • Remove all children
    container.clear();\n// container.clear(destroyChild);\n
"},{"location":"containerlite/#get-child","title":"Get child","text":"
  • Get first child by name
    var gameObject = container.getByName(name);\n// var gameObject = container.getByName(name, recursive);\n
    • gameObject : A child, or null if not found.
    • recursive : Set true to search all children recursively.
  • Get a random child
    var gameObject = container.getRandom();\n// var gameObject = container.getRandom(startIndex, length);\n
  • Get children in this container-lite
    • Internal children array
      var gameObjects = container.getChildren();\n
    • Copy of children array
      var gameObjects = container.getChildren([]);\n// var gameObjects = container.getChildren(out);\n
  • Get all children under this container-lite recursively
    var gameObjects = container.getAllChildren();\n
    • Put container itself and all children into Layer
      layer.add(container.getAllChildren([container]));\n
    • Draw on render texture
      rt.draw(container.getAllChildren());\n
    • Ignored in camera
      camera.ignore(container.getAllChildren());\n
"},{"location":"containerlite/#traversal","title":"Traversal","text":"
  • Depth-First Search
    container.dfs(function(current) {\n// return true;  // Discard children traveraling\n})\n
    • Return true to discard children traveraling
  • Breadth-First Search
    container.bfs(function(current) {\n// return true;  // Discard children traveraling\n})\n
    • Return true to discard children traveraling
"},{"location":"containerlite/#exist","title":"Exist","text":"

Return true if child is under this container-lite (nested).

var hasChild = container.contains(child);\n
"},{"location":"containerlite/#children","title":"Children","text":"
var children = container.children;\n
  • children : Array of child game objects.
"},{"location":"containerlite/#get-parent","title":"Get parent","text":"
var parentContainer = scene.plugins.get('rexContainerLitePlugin').getParent(child);\n

or

var parentContainer = Container.GetParent(child); // Static method\n
"},{"location":"containerlite/#set-properties-of-child","title":"Set properties of child","text":""},{"location":"containerlite/#position","title":"Position","text":"
container.setChildPosition(child, x, y);\n
"},{"location":"containerlite/#rotation","title":"Rotation","text":"
container.setChildRotation(child, rotation);\n
  • rotation : Angle in radians.
"},{"location":"containerlite/#scale","title":"Scale","text":"
container.setChildScale(child, scaleX, scaleY);\n

or

container.setChildDisplaySize(child, width, height);\n
"},{"location":"containerlite/#visible","title":"Visible","text":"
container.setChildVisible(child, visible);\n
"},{"location":"containerlite/#alpha","title":"Alpha","text":"
container.setChildAlpha(child, alpha);\n
"},{"location":"containerlite/#local-state-of-child","title":"Local state of child","text":"

Get local state

var localState = container.getLocalState(child);\n

or

var localState = child.rexContainer;\n
  • Properties of localState
    • x, y
    • rotation
    • scaleX, scaleY
    • visible
    • alpha
"},{"location":"containerlite/#change-local-state-of-child","title":"Change local state of child","text":"
  • Local position
    container.setChildLocalPosition(child, x, y);\n
  • Local scale
    container.setChildLocalScale(child, scaleX, scaleY);\n
  • Local alpha
    container.setChildLocalAlpha(child, alpha);\n
  • Local visible
    container.setChildLocalVisible(child, visible);\n
"},{"location":"containerlite/#reset-local-state-of-child","title":"Reset local state of child","text":"

Reset local state of child according to current properties of children

  • Reset local state of all properties
    container.resetChildState(child);\n
  • Reset local state of position
    container.resetChildPositionState(child);\n
  • Reset local state of rotation
    container.resetChildRotationState(child);\n
  • Reset local state of scale
    container.resetChildScaleState(child);\n
  • Reset local state of alpha
    container.resetChildAlphaState(child);\n
  • Reset local state of visible
    container.resetChildVisibleState(child);\n
  • Reset local state of active
    container.resetChildActiveState(child);\n
"},{"location":"containerlite/#tween-local-state","title":"Tween local state","text":"
var tweenObj = container.tweenChild({\ntargets: child,\n// x: '+=100',\n// y: '+=100',\n// repeat: -1,\n// yoyo: true\n})\n
  • targets : A game object, or an array of game object.
    • A containerLite child, can tween its local state.

Paramters of configuration is the same as tween task.

Supported properties :

  • x, y,
  • angle, rotation
  • scaleX, scaleY, displayWidth, displayHeight
  • alpha
"},{"location":"containerlite/#tween-local-state-of-a-containerlite-child","title":"Tween local state of a containerlite child","text":"
var tweenObj = containerLiteChild.tweenSelf({    // x: '+=100',\n// y: '+=100',\n// repeat: -1,\n// yoyo: true\n})\n

Equal to

containerLiteChild.tweenChild({\ntargets: containerLiteChild,\n// x: '+=100',\n// y: '+=100',\n// repeat: -1,\n// yoyo: true\n})\n
"},{"location":"containerlite/#create-tween-config","title":"Create tween config","text":"
var tweenConfig = container.createTweenChildConfig({\ntargets: child,\n// x: '+=100',\n// y: '+=100',\n// repeat: -1,\n// yoyo: true\n});\nscene.tweens.add(tweenConfig);\n
  • Input of targets is/are game object(s), will be replaced by local state of game object(S)
  • Wrap onUpdate callback, to update properties of child according to local state.
"},{"location":"containerlite/#depth","title":"Depth","text":"
  • Get depth of container
    var depth = container.depth;\n
  • Set depth of container
    container.setDepth(value, true);\n// container.depth = depth;\n
  • Set depth of container and all children
    container.setDepth(value);\n
  • Bring this container and its children to top
    container.bringMeToTop();\n// container.bringToTop();\n
  • Send this container and its children to back
    container.sendMeToBack();\n// container.sendToBack();\n
  • Swap depth with another container
    containerA.swapDepth(containerB);\n
  • Increase of container and all children
    container.incDepth(value);\n
  • Move game object below this container and all children
    container.moveMyDepthBelow(gameObject);\n// container.moveDepthBelow(gameObject);\n
  • Move game object above this container and all children
    container.moveMyDepthAbove(gameObject);\n// container.moveDepthAbove(gameObject);\n
  • Bring a child of container to top of this container
    container.bringChildToTop(gameObject);\n
  • Send a child of container to bottom of this container
    container.sendChildToBack(gameObject);\n
"},{"location":"containerlite/#render-layer","title":"Render layer","text":"

A containerLite can have a layer. Current children and new children will draw on this layer, instead of display list of scene.

  • Enable layer. Do nothing if layer is existed.
    container.enableLayer();\n
  • Get layer game object. Will enable layer if layer is not existed.
    var layer = container.getLayer();\n
  • Get layer game object, without enable layer.
    var layer = container.privateRenderLayer;\n
  • Has layer game object
    var hasLayer = container.hasLayer();\n
"},{"location":"containerlite/#mask","title":"Mask","text":"
  • Assign mask object to children
    container.setMask(mask);  // container.mask = mask;\n
  • Remove mask object of children
    container.clearMask();\n
  • Remove mask object of children, and destroy mask object
    container.clearMask(true);\n
"},{"location":"containerlite/#shader-effects","title":"Shader effects","text":"

Apply post-fx pipeline on layer of containerLite.

"},{"location":"containerlite/#snapshot","title":"Snapshot","text":"
  • Draw all visible children on a render-texture.
    var renderTexture = container.snapshot({\nrenderTexture: undefined,\npadding: 0\n});\n
    • renderTexture : Draw on this render-texture
      • undefined : Create a new render-texture
    • padding :
      • 0 : No extra padding space. Default value.
      • A number : Add extra padding space around this render-texture.
  • Draw all visible children on a dynamic-texture
    container.snapshot({\npadding: 0,\nsaveTexture: textureKey\n});\n
    • saveTexture : Save render result to texture manager.
"},{"location":"containerlite/#draw-bounds","title":"Draw bounds","text":"
  • Draw bounds of shown game object on a graphics game object
    container.drawBounds(graphics);\n// container.drawBounds(graphics, color);\n
    or
    container.drawBounds(graphics, {\n// color: 0xffffff,\n// lineWidth: 1,\n// padding: 0,\n// drawContainer: true,\n// children: undefined,\n});\n
    • graphics : Graphics game object
    • color : Default value is 0xffffff.
    • lineWidth : Default value is 1.
    • padding : Extra space around bounds. Default value is 0.
    • drawContainer :
      • true : Draw all children game objects included containerLite. Default behavior.
      • false : Draw all children game objects excluded containerLite
    • children :
      • Array of game objects : Only draw bounds of these children
      • undefined : Draw bounds of all children
"},{"location":"containerlite/#scroll-factor","title":"Scroll factor","text":"
  • Set scroll factor to children
    container.setScrollFactor(x, y);\n
"},{"location":"containerlite/#change-origin","title":"Change origin","text":"
container.changeOrigin(originX, originY);\n

This method also will reset all local state of children.

"},{"location":"containerlite/#add-to-container","title":"Add to container","text":"
  • Add to built-in container
    containerLite.addToContainer(p3Container);\n
    or
    p3Container.add(containerLite);\n
    • p3Container : Container game object.
  • Add to Layer
    container.addToLayer(layer);\n
    • layer : Layer game object.
"},{"location":"containerlite/#remove-from-container","title":"Remove from container","text":"
  • Remove from built-in container
    containerLite.removeFromContainer(p3Container);\n
    or
    p3Container.remove(containerLite);\n
    • p3Container : Container game object.
  • Remove from Layer
    container.removeFromLayer(layer);\n
    • layer : Layer game object.
"},{"location":"containerlite/#other-properties_1","title":"Other properties","text":"

See game object

"},{"location":"containerlite/#compare-with-official-container","title":"Compare with Official Container","text":"
  • Position/anlge/scale of a child object :
    • Container : Local position/anlge/scale, responding to parent container, not a world position/anlge/scale.
    • Container-Lite : World position/anlge/scale.
  • Updating period
    • Container : Re-calculate position/anlge/scale of each child every render.
    • Container-Lite: Re-calculate position/anlge/scale of each child when parent container changes position/anlge/scale.
  • Mask
    • Container : It has mask property, and it could become a mask object.
    • Container-Lite : It has mask property, but it could not become a mask object.
  • DOM game object
    • Container : Only 1 level parent container will affect DOM game object. Therefore position of DOM game object in nested container might be incorrect.
    • Container-Lite : DOM game object can work with nested Container-Lite.
"},{"location":"create-number-array/","title":"Number array","text":""},{"location":"create-number-array/#introduction","title":"Introduction","text":"

Create an array representing the range of numbers, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"create-number-array/#usage","title":"Usage","text":""},{"location":"create-number-array/#create-number-array","title":"Create number array","text":"

Create an array representing the range of numbers (usually integers), between, and inclusive of, the given start and end arguments.

var arr = Phaser.Utils.Array.NumberArray(start, end);\n

For example,

var arr = Phaser.Utils.Array.NumberArray(2, 4);\n// arr = [2, 3, 4]\n

"},{"location":"create-number-array/#create-number-array-with-step","title":"Create number array with step","text":"

Create an array of numbers (positive and/or negative) progressing from start up to but not including end by advancing by step.

var arr = Phaser.Utils.Array.NumberArray(start, end, step);\n

For example,

var arr = Phaser.Utils.Array.NumberArrayStep(0, 20, 5);\n// arr =  [0, 5, 10, 15]\n

"},{"location":"create-number-array/#create-prefix-number-suffix-string-array","title":"Create prefix-number-suffix string array","text":"
var arr = Phaser.Utils.Array.NumberArray(start, end, prefix, suffix);\n

For example,

var arr = Phaser.Utils.Array.NumberArray(5, 7, 'HD-', '.png');\n// arr = ['HD-5.png', 'HD-6.png', 'HD-7.png']\n

"},{"location":"csvscenario/","title":"CSV scenario","text":""},{"location":"csvscenario/#introduction","title":"Introduction","text":"

Run script in csv format. Csv could be edited by excel or google document.

  • Author: Rex
  • Member of scene
"},{"location":"csvscenario/#live-demos","title":"Live demos","text":"
  • CSV-scenario
  • With TextPlayer
"},{"location":"csvscenario/#usage","title":"Usage","text":"

Sample code

"},{"location":"csvscenario/#install-plugin","title":"Install plugin","text":""},{"location":"csvscenario/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcsvscenarioplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcsvscenarioplugin.min.js', true);\n
  • Add csv-scenario object
    var scenario = scene.plugins.get('rexcsvscenarioplugin').add(scene);\n
"},{"location":"csvscenario/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CsvScenarioPlugin from 'phaser3-rex-plugins/plugins/csvscenario-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCsvScenario',\nplugin: CsvScenarioPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add csv-scenario object
    var scenario = scene.plugins.get('rexCsvScenario').add(scene);\n
"},{"location":"csvscenario/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CsvScenario from 'phaser3-rex-plugins/plugins/csvscenario.js';\n
  • Add csv-scenario object
    var scenario = new CsvScenario(scene);\n
"},{"location":"csvscenario/#create-instance","title":"Create instance","text":"
var scenario = scene.plugins.get('rexCSVScenario').add(scene, {\n// timeUnit: 0,        // 'ms'|0|'s'|'sec'|1\n// prefix: /^#([a-zA-Z]+)/\n// argsConvert: true,\n// argsConvertScope: undefined,\n// delimiter: ','\n// translateCommandNameCallback: undefined,\n});\n
  • csvString : Commands in csv-string.
  • scope : Running commands via methods in this scope object.
    • Get scope : var scope = scenario.scope
  • timeUnit: time-unit of dt, for delay-execution
    • 'ms', or 0 : dt in millisecond
    • 's', 'sec', or 1 : dt in second
  • prefix: regex of picking control instructions
  • argsConvert: A callback to convert parameters of run-custom-function
    • true : Use defaule value converter. Values will be converted to number (include hex number string like '0xFF'), boolean, null, or string.
    • Function object:
      function(s) {\nreturn s;\n}\n
  • argsConvertScope: scope of argsConvert
  • delimiter : Delimiter of CSV string.
  • translateCommandNameCallback : Callback to translate custom command name
    • undefined : Use original custom command name. Default behavior.
    • A function, return new custom command name.
      function(commandName) {\nreturn newCommandName;\n}\n
"},{"location":"csvscenario/#load-csv-script","title":"Load csv script","text":"
scenario.load(csvString, scope, {\n// timeUnit: 0,        // 'ms'|0|'s'|'sec'|1\n// prefix: /^#([a-zA-Z]+)/\n// argsConvert: true,\n// argsConvertScope: undefined,\n// delimiter: ',',\n// translateCommandNameCallback: undefined,\n})\n
  • csvString : Commands in csv-string.
  • scope : Running commands via methods in this scope object.
    • Get scope : var scope = scenario.scope
  • timeUnit: time-unit of dt, for delay-execution
    • 'ms', or 0 : dt in millisecond
    • 's', 'sec', or 1 : dt in second
  • prefix: regex of picking control instructions
  • argsConvert: A callback to convert parameters of run-custom-function
    • true : Use defaule value converter. Values will be converted to number (include hex number string like '0xFF'), boolean, null, or string.
    • Function object:
      function(s) {\nreturn s;\n}\n
  • argsConvertScope: scope of argsConvert
  • delimiter : Delimiter of CSV string.
"},{"location":"csvscenario/#append-csv-script","title":"Append csv script","text":"
scenario.append(csvString);\n
"},{"location":"csvscenario/#start-running-instructions","title":"Start running instructions","text":"

scenario.start({\n// label: '',\n// offset: 0\n})\n
scenario.play({\n// label: '',\n// offset: 0\n})\n

  • label : Go to the label and execute. '' label is starting from 1st instruction
  • offset : Offset time

or

scenario.playPromise({\n// label: '',\n// offset: 0\n})\n.then(function(){\n// On complete\n})\n
"},{"location":"csvscenario/#events","title":"Events","text":"
  • Complete
    scenario.on('complete', function(scope, scenario){ });\n
  • Wait event
    scenario.on('wait.' + eventName, function(scenario){ });\n
    scenario.on('wait', function(eventName, scenario){ });\n
  • Label has changed
    scenario.on('labelchange', function(lastLabel, prevLabel, scope, scenario){ });\n
  • Dump execution log
    scenario.on('log', function(msg, scope, scenario){ });\n
  • Notify error
    scenario.on('error', function(msg, scope, scenario){ });\n
"},{"location":"csvscenario/#types-of-instructions","title":"Types of instructions","text":"

Each row in csv table is an instruction.

"},{"location":"csvscenario/#run-custom-function","title":"Run custom function","text":"

Run custom function of scope, which passed from scenario.load(...)

Format:

-,fnName,param0,param1,...\n
  • 1st column of instruction: -
  • Parameters will be converted to number, boolean, null, or string by default.
  • Method name of last custom command :
    var methodName = scenario.lastCustomCommandName;\n
  • An error event will be fired if fnName is invalid in scope.
"},{"location":"csvscenario/#delay-execution","title":"Delay execution","text":"

Run custom function after a delay.

Format:

time,fnName,param0,param1,...\n
  • 1st column of instruction: a number
  • time-unit of delay is set from scenario.load(...)
  • Parameters will be converted to number, boolean, null, or string by default.
"},{"location":"csvscenario/#wait-then-execution","title":"Wait then execution","text":"

Run custom function until scenario.continue(eventName)

Format:

eventName,fnName,param0,param1,...\n
  • 1st column of instruction: not a number, not a string start from #
  • Execution will be hang until scenario.continue(eventName) is called
  • Parameters will be converted to number, boolean, null, or string by default.
"},{"location":"csvscenario/#skip-waiting","title":"Skip waiting","text":"
scenario.continue(true);\n
"},{"location":"csvscenario/#task","title":"Task","text":"

Sample code

Scenario will be paused if custom function return an event emitter, resumed when that evnt emitter fires complete event.

See also: Sequence

"},{"location":"csvscenario/#label","title":"Label","text":"

Sample code

A label for #GOTO or #IF instructions.

Format:

#LABEL,label\n
  • 1st column of instruction: #LABEL, case insensitive.
  • Label '' is reserved, don't use '' for label name.

Example: A label named 'AA'

#LABEL,AA\n
  • Last label :
    var label = scenario.lastLabel;\n
  • Previous label :
    var previousLabel = scenario.previousLabel;\n
"},{"location":"csvscenario/#exit","title":"Exit","text":"

Exit current execution.

Format:

#EXIT\n
  • 1st column of instruction: #EXIT, case insensitive.
"},{"location":"csvscenario/#goto","title":"Goto","text":"

Sample code

Go to label and execute.

Format:

#GOTO,label\n
  • 1st column of instruction: #GOTO, case insensitive.
  • An error event will be fired if label is not found.

Example: Goto label 'AA'

#GOTO,AA\n
"},{"location":"csvscenario/#if-goto","title":"If-goto","text":"

Sample code

Go to trueLabel if condition is true, otherwise go to falseLabel.

Format:

#IF,condition,trueLabel,falseLabel\n
  • 1st column of instruction: #IF, case insensitive.
  • conditon: boolean equation
    • this is the scope passed from scenario.load(...)
  • trueLabel/falseLabel: go to this label if condition is true/false
    • run next instruction if label is ''
    • An error event will be fired if label is not found.

Example: Goto label 'AA' if (this.coin > 100), else run next instruction

#IF,this.coin > 100,AA\n
"},{"location":"csvscenario/#wait","title":"Wait","text":"

Run next instruction after a delay time, or scenario.continue(eventName).

Format:

#WAIT,time\n
#WAIT,eventName\n
  • 1st column of instruction: #WAIT, case insensitive.
  • 2nd colume of instruction:
    • a number: a delay time
      • time-unit of delay is set from scenario.load(...)
    • a string: an event name for scenario.continue(eventName)

Example:

  • Wait 1 time-unit
    #WAIT,1\n
  • Wait until 'click'
    #WAIT,click\n
    scenario.continue('click');\n
"},{"location":"csvscenario/#pause","title":"Pause","text":"
scenario.pause();\n
"},{"location":"csvscenario/#resume","title":"Resume","text":"
scenario.resume();\n
"},{"location":"csvscenario/#time-scale","title":"Time-scale","text":"
  • Get
    var timeScale = scenario.timeScale;\n
  • Set
    scenario.setTimeScale(timeScale);\n// scenario.timeScale = timeScale;\n
"},{"location":"csvscenario/#clear","title":"Clear","text":"

Stop running and clear instructions.

scenario.clear();\n
"},{"location":"csvscenario/#states","title":"States","text":"
  • Is running
    var isRunning = scenario.isRunning;\n
  • Is paused
    var isPaused = scenario.isPaused;\n
"},{"location":"csvtoarray/","title":"CSV to array","text":""},{"location":"csvtoarray/#introduction","title":"Introduction","text":"

Generate array from csv string.

  • Reference: Papa Parse
  • Method only
"},{"location":"csvtoarray/#usage","title":"Usage","text":"

Sample code

"},{"location":"csvtoarray/#import-class","title":"Import class","text":"
import rexCSVToArray from './plugins/csvtoarray.js';\n
"},{"location":"csvtoarray/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CSVToArrayPlugin from 'phaser3-rex-plugins/plugins/csvtoarray-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCSVToArray',\nplugin: CSVToArrayPlugin,\nstart: true\n}\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Convert csv
    var arr = scene.plugins.get('rexCSVToArray').convert(csvString, config);\n
"},{"location":"csvtoarray/#convert-csv","title":"Convert csv","text":"
var arr = scene.plugins.get('rexCSVToArray').convert(csvString, {\n// delimiter: ',',\n// convert: true\n});\n

Values will be converted to number (include hex number string like '0xFF'), boolean, null, or string, if convert is true.

"},{"location":"csvtohashtable/","title":"CSV to hash table","text":""},{"location":"csvtohashtable/#introduction","title":"Introduction","text":"

Hash table indexed by (col-key, row-key) from csv string.

  • Author: Rex
  • Member of scene
"},{"location":"csvtohashtable/#usage","title":"Usage","text":"

Sample code

"},{"location":"csvtohashtable/#install-plugin","title":"Install plugin","text":""},{"location":"csvtohashtable/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcsvtohashtableplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcsvtohashtableplugin.min.js', true);\n
  • Add hash-table object
    var table = scene.plugins.get('rexcsvtohashtableplugin').add();\n
"},{"location":"csvtohashtable/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CsvToHashTablePlugin from 'phaser3-rex-plugins/plugins/csvtohashtable-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCsvToHashTable',\nplugin: CsvToHashTablePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add hash-table object
    var table = scene.plugins.get('rexCsvToHashTable').add();\n
"},{"location":"csvtohashtable/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CsvToHashTable from 'phaser3-rex-plugins/plugins/csvtohashtable.js';\n
  • Add hash-table object
    var table = new CsvToHashTable();\n
"},{"location":"csvtohashtable/#create-instance","title":"Create instance","text":"
var table = scene.plugins.get('rexCsvToHashTable').add();\n
"},{"location":"csvtohashtable/#append-rows-from-csv-string","title":"Append rows from csv string","text":"
table.loadCSV(csvString, {\n// delimiter: ',',\n// convert: true\n// convertScope: undefined\n});\n

For exameple, csv string

name hp mp Rex 100 20 Alice 300 40
name,hp,mp\nRex,100,20\nAlice,300,40\n

will be converted to

{\n\"Alice\": {\n\"name\": \"Alice\",\n\"hp\": 300,\n\"mp\": 40\n},\n\"Rex\": {\n\"name\": \"Rex\",\n\"hp\": 100,\n\"mp\": 20\n}\n}\n

Then get value by

var value = table.get('Rex', 'hp');\n
"},{"location":"csvtohashtable/#convert-value-type","title":"Convert value type","text":"

Values will be converted to number (include hex number string like '0xFF'), boolean, null, or string, if convert is true, or assign your convert function by convert and convertScope when loading table (table.loadCSV(...)).

var convertCallback = function(table, rowKey, colKey, value) {\n// value = ...\nreturn value;\n};\n

Or uses these metheds to convert columns or rows.

  • convert values in column
    table.convertCol(colKey);  // colKey: a colKey, or an array of colKeys\n// table.convertCol(colKey, convertCallback, convertCallbackScope);\n
  • convert values in row
    table.convertRow(rowKey);  // rowKey: a rowKey, or an array of rowKeys\n// table.convertRow(rowKey, convertCallback, convertCallbackScope);\n
"},{"location":"csvtohashtable/#get-value","title":"Get value","text":"
var val = table.get(rowKey, colKey);\n
  • rowKey : Row key string, or row index number.
  • colKey : Column key string, or column index number.
"},{"location":"csvtohashtable/#set-value","title":"Set value","text":"
table.set(rowKey, colKey, value);\n
table.add(rowKey, colKey, value);\n// equal to table.set(rowKey, colKey, table.get(rowKey, colKey) + value);\n
  • rowKey : Row key string, or row index number.
  • colKey : Column key string, or column index number.
"},{"location":"csvtohashtable/#has-columnrow-key","title":"Has column/row key","text":"
var hasRow = table.hasRowKey(rowKey);\n
var hasCol = table.hasColKey(colKey);\n
var hasCell = table.hasKey(rowKey, colKey);\n
  • rowKey : Row key string, or row index number.
  • colKey : Column key string, or column index number.
"},{"location":"csvtohashtable/#value-in-column-or-row","title":"Value in column or row","text":"
var existed = table.isValueInRol(rowKey, value);\n
var existed = table.isValueInCol(colKey, value);\n
  • rowKey : Row key string, or row index number.
  • colKey : Column key string, or column index number.
"},{"location":"csvtohashtable/#create-table","title":"Create table","text":""},{"location":"csvtohashtable/#clear-table","title":"Clear table","text":"
table.clear();\n
"},{"location":"csvtohashtable/#append-a-column","title":"Append a column","text":"
table.appendCol(colKey, initValue);\n// table.appendCol(colKey, callback, scope);  // get initValue from callback\n

Callback

var callback = function (table, rowKey, colKey) { // value = ...\nreturn value;\n};\n
  • colKey : Column key string, or column index number.
"},{"location":"csvtohashtable/#append-a-row","title":"Append a row","text":"
table.appendRow(rowKey, initValue);\n// table.appendRow(rowKey, callback, scope);  // get initValue from callback\n

Callback

var callback = function (table, rowKey, colKey) { // value = ...\nreturn value;\n};\n
  • rowKey : Row key string, or row index number.
"},{"location":"csvtohashtable/#remove-a-column","title":"Remove a column","text":"
table.removeCol(colKey);\n
  • colKey : Column key string, or column index number.
"},{"location":"csvtohashtable/#remove-a-row","title":"Remove a row","text":"
table.removeRol(rowKey);\n
  • rowKey : Row key string, or row index number.
"},{"location":"csvtohashtable/#sort-column-or-row","title":"Sort column or row","text":"
table.sortCol(colKey, mode);\n// table.sortCol(callback, scope);  // sort columns by callback\n
table.sortRow(rowKey, mode);\n// table.sortRow(callback, scope);  // sort rows by callback\n
  • rowKey : Row key string, or row index number.
  • colKey : Column key string, or column index number.

Mode:

  • 'ascending', or 0
  • 'descending', or 1
  • 'logical ascending', or 2
  • 'logical descending', or 3

Sorting callback

var callback = function(rowKeyA, rowKeyB) {\nreturn result; // 1, -1, or 0\n};\n
"},{"location":"csvtohashtable/#retrieve-columns-or-rows","title":"Retrieve columns or rows","text":"
table.eachCol(rowKey, callback, scope);\n
table.eachRow(colKey, callback, scope);\n
  • rowKey : Row key string, or row index number.
  • colKey : Column key string, or column index number.

Callback

var callback = function(table, rowKey, colKey, value) {\n// ...\n};\n
"},{"location":"csvtohashtable/#json","title":"JSON","text":"
  • Table to json
    var jsonData = table.toJSON();\n
  • Reset table by JSON
    table.resetFromJSON(jsonData);\n
"},{"location":"cursor/","title":"Cursor","text":""},{"location":"cursor/#introduction","title":"Introduction","text":"

Custom cursor, built-in feature of phaser.

  • Author: Richard Davey
"},{"location":"cursor/#usage","title":"Usage","text":"

References:

  • Cursor
  • Using URL values for the cursor property
"},{"location":"cursor/#set-default-cursor","title":"Set default cursor","text":"
scene.input.setDefaultCursor(CSSString);\n// CSSString: 'url(assets/input/cursors/sword.cur), pointer'\n
"},{"location":"cursor/#set-cursor-of-a-game-object","title":"Set cursor of a Game Object","text":"

Change cursor image when cursor is over that Game Object.

gameObject.setInteractive({\ncursor: CSSString\n});\n// CSSString: 'url(assets/input/cursors/sword.cur), pointer'\n

Set cursor image directly after gameObject.setInteractive().

gameObject.input.cursor = CSSString;\n// CSSString: 'url(assets/input/cursors/sword.cur), pointer'\n

Use pointer (hand cursor).

gameObject.setInteractive({\nuseHandCursor: true\n});\n
"},{"location":"cursor/#change-current-cursor","title":"Change current cursor","text":"
scene.input.canvas.style.cursor = cursor;\n
  • cursor : CSSString

or

scene.input.setCursor(gameObject.input);\n
"},{"location":"cursor/#reset-to-default-cursor","title":"Reset to default cursor","text":"
scene.input.resetCursor(null, true);\n
"},{"location":"cursoratbounds/","title":"Cursor at bounds","text":""},{"location":"cursoratbounds/#introduction","title":"Introduction","text":"

Map cursor-at-(left/right/top/botttom-)bound to (left/right/up/down) cursor key state.

  • Author: Rex
  • Member of scene
"},{"location":"cursoratbounds/#live-demos","title":"Live demos","text":"
  • Custom bounds
  • Camera scrolling
"},{"location":"cursoratbounds/#usage","title":"Usage","text":"

Sample code

"},{"location":"cursoratbounds/#install-plugin","title":"Install plugin","text":""},{"location":"cursoratbounds/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcursoratboundsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcursoratboundsplugin.min.js', true);\n
  • Add cursor-at-bound object
    var cursorAtBound = scene.plugins.get('rexcursoratboundsplugin').add(scene, config);\n
"},{"location":"cursoratbounds/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CursorAtBoundsPlugin from 'phaser3-rex-plugins/plugins/cursoratboundss-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCursorAtBounds',\nplugin: CursorAtBoundsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add cursor-at-bound object
    var cursorAtBound = scene.plugins.get('rexCursorAtBounds').add(scene, config);\n
"},{"location":"cursoratbounds/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CursorAtBounds from 'phaser3-rex-plugins/plugins/cursoratboundss.js';\n
  • Add cursor-at-bound object
    var cursorAtBound = new CursorAtBounds(scene, config);\n
"},{"location":"cursoratbounds/#create-instance","title":"Create instance","text":"
var cursorAtBound = scene.plugins.get('rexCursorAtBounds').add(scene, {\n// enable: true,\n// bounds: undefined,\n// sensitiveDistance: 20,\n// pointerOutGameRelease: true,\n// pointerOutBoundsRelease: false,\n});\n
  • bounds : A rectangle object for detecting the position of cursor.
    • undefined : Current viewport. Will update bounds when window resizing.
  • sensitiveDistance : A sensitive distance in pixels.
  • pointerOutGameRelease :
    • true : All cursor keys are released when pointer is out of game window. Default behavior.
    • false : Don't change status of cursor keys when pointer is out of game window.
  • pointerOutBoundsRelease
    • true : All cursor keys are released when pointer is out of bounds.
    • false : Continue cursor key detection when pointer is out of bounds. Default behavior.

Map position of cursor to state of cursor key

  • left cursor key is pressed :
    • Position x is between left bound and left bound + sensitive distance
    • Position x at left side of left bound, if pointerOutBoundsRelease is false
  • Right cursor key is pressed :
    • Position x is between right bound and right bound - sensitive distance
    • Position x at right side of right bound, if pointerOutBoundsRelease is false
  • Up cursor key is pressed :
    • Position y is between top bound and top bound + sensitive distance
    • Position y at up side of top bound, if pointerOutBoundsRelease is false
  • Down cursor key is pressed :
    • Position y is between bottom bound and bottom bound - sensitive distance
    • Position y at down side of bottom bound, if pointerOutBoundsRelease is false
"},{"location":"cursoratbounds/#state-of-cursor-keys","title":"State of cursor keys","text":"
var cursorKeys = cursorAtBound.createCursorKeys();\n\nvar leftKeyDown = cursorKeys.left.isDown;\nvar rightKeyDown = cursorKeys.right.isDown;\nvar upKeyDown = cursorKeys.up.isDown;\nvar downKeyDown = cursorKeys.down.isDown;\n

Or

var leftKeyDown = cursorAtBound.left;\nvar rightKeyDown = cursorAtBound.right;\nvar upKeyDown = cursorAtBound.up;\nvar downKeyDown = cursorAtBound.down;\nvar noKeyDown = cursorAtBound.noKey;\n
"},{"location":"cursoratbounds/#destroy","title":"Destroy","text":"
cursorAtBound.destroy();\n
"},{"location":"cursoratbounds/#enable","title":"Enable","text":"
  • Get
    var enable = joystick.enable;\n
  • Set
    joystick.setEnable(enable);  // enable: true, or false\n//joystick.enable = enable;\n
  • Toggle
    joystick.toggleEnable();\n
"},{"location":"cursoratbounds/#bounds","title":"Bounds","text":"
  • Get
    var bounds = cursorAtBound.bounds;\n
    • bounds : A rectangle object
  • Set
    cursorAtBound.setBounds(bounds);\n
    or
    cursorAtBound.bounds = bounds;;\n
    • bounds : A rectangle object
"},{"location":"cursoratbounds/#sensitive-distance","title":"Sensitive distance","text":"
  • Get
    var distance = cursorAtBound.sensitiveDistance;\n
  • Set
    cursorAtBound.setSensitiveDistance(distance);\n
    or
    cursorAtBound.sensitiveDistance = distance;\n
"},{"location":"curve-spiral/","title":"Spiral curve","text":""},{"location":"curve-spiral/#introduction","title":"Introduction","text":"

Spiral curve.

  • Author: Rex
  • Curve object
"},{"location":"curve-spiral/#live-demos","title":"Live demos","text":"
  • Spiral curve
  • Particles along spiral curve
"},{"location":"curve-spiral/#usage","title":"Usage","text":"

Sample code

"},{"location":"curve-spiral/#install-plugin","title":"Install plugin","text":""},{"location":"curve-spiral/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexspiralcurveplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexspiralcurveplugin.min.js', true);\n
  • Add spiral curve object
    var spiral = scene.plugins.get('rexspiralcurveplugin').add(config);\n
"},{"location":"curve-spiral/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SpiralCurvePlugin from 'phaser3-rex-plugins/plugins/spiralcurve-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexSpiralCurve',\nplugin: SpiralCurvePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add spiral curve object
    var spiral = scene.plugins.get('rexSpiralCurve').add(config);\n
"},{"location":"curve-spiral/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import SpiralCurve from 'phaser3-rex-plugins/plugins/spiralcurve.js';\n
  • Add spiral curve object
    var spiral = new SpiralCurve(config);\n
"},{"location":"curve-spiral/#create-shape","title":"Create shape","text":"
  • All properties
    var spiral = scene.plugins.get('rexSpiralCurve').add({\n// Origin point\n// Ease origin point\n// startX:0, endX: 0, easeX: 'Linear',\n// startY:0, endY: 0, easeY: 'Linear',\n// Fixed point\n// x, y,\n\n// x-radius\n// startXRadius: 0, endXRadius, easeXRadius: 'Linear',\n// y-radius\n// startYRadius: 0, endYRadius, easeYRadius: 'Linear',\n// start-end radius\n// startRadius, endRadiux\n\n// angle\n// startAngle: 0, endAngle: 360, easeAngle: 'Linear',\n\n// rotation: 0\n});\n
    • Origin point
      • startX, endX, easeX, startY, endY, easeY : Ease origin point.
        • easeX, easeY : Ease equation, default value is 'Linear'.
      • x, y : Fixed origin point, i.e. start point is equal to end point.
    • Radius
      • startXRadius, endXRadius, easeXRadius : Ease x-radius.
        • easeXRadius : Ease equation, default value is 'Linear'.
      • startYRadius, endYRadius, easeYRadius : Ease y-radius.
        • easeYRadius : Ease equation, default value is 'Linear'.
      • startRadius, endRadiux :
        • Set startXRadius, and startYRadius to startRadius.
        • Set endXRadius, and endYRadius to endRadius.
    • Angle
      • startAngle, endAngle, easeAngle : Ease angle, in degrees.
        • easeAngle : Ease equation, default value is 'Linear'.
    • rotation : Rotate curve.
  • Simple spiral curve
    var spiral = scene.plugins.get('rexSpiralCurve').add(x, y, startRadius, endRadius, startAngle, endAngle, rotation);\n
    • x : Set startX, endX to x, and easeX to 'Linear'.
    • y : Set startY, endY to y, and easeY to 'Linear'.
    • startRadius : Set startXRadius, startYRadius to startRadius
    • endRadius : Set endXRadius, endYRadius to endRadius, and easeXRadius, easeYRadius to Linear.
    • Set easeAngle to 'Linear'
"},{"location":"curve-spiral/#properties","title":"Properties","text":"
  • Origin point
    • Get
      var startX = spiral.startX;\nvar startY = spiral.startY;\nvar endX = spiral.endX;\nvar endY = spiral.endY;\n
      or
      var startPoint = spiral.p0; // {x, y}\nvar endPoint = spiral.p1; // {x, y}\n
    • Set
      spiral.setStartX(x);\nspiral.setStartY(y);\nspiral.setEndX(x);\nspiral.setEndY(y);\n
      or
      spiral.startX = x;\nspiral.startY = y;\nspiral.endX = x;\nspiral.endY = y;\n
  • Radius
    • Get
      var startXRadius = spiral.startXRadius;\nvar startYRadius = spiral.startYRadius;\nvar endXRadius = spiral.endXRadius;\nvar endYRadius = spiral.endYRadius;\n
    • Set
      spiral.setStartXRadius(startXRadius);\nspiral.setStartYRadius(startYRadius);\nspiral.setEndXRadius(endXRadius);\nspiral.setEndYRadius(endYRadius);\n
      or
      spiral.startXRadius = startXRadius;\nspiral.startYRadius = startYRadius;\nspiral.endXRadius = endXRadius;\nspiral.endYRadius = endYRadius;\n
  • Angle, in degrees.
    • Get
      var startAnlge = spiral.startAngle;\nvar endAnlge = spiral.endAngle;\n
    • Set
      spiral.setStartAngle(startAnlge);\nspiral.setEndAngle(endAnlge);\n
      spiral.startAngle = startAnlge;\nspiral.endAngle = endAnlge;\n
"},{"location":"curve-spiral/#other-methods","title":"Other methods","text":"

See path

"},{"location":"cutjigsawimage/","title":"Cut Jigsaw Image","text":""},{"location":"cutjigsawimage/#introduction","title":"Introduction","text":"

Cut image into pieces for jigsaw application.

  • Author: Rex
  • Method only
"},{"location":"cutjigsawimage/#live-demos","title":"Live demos","text":"
  • Create pieces
  • Custom piece shape
  • Drag drop with pixelPerfect
"},{"location":"cutjigsawimage/#usage","title":"Usage","text":"

Sample code

"},{"location":"cutjigsawimage/#install-plugin","title":"Install plugin","text":""},{"location":"cutjigsawimage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcutjigsawimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcutjigsawimageplugin.min.js', true);\n
  • Cut image into pieces
    var pieces = scene.plugins.get('rexcutjigsawimageplugin').gridCut(gameObject, config);\n
"},{"location":"cutjigsawimage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CutJigsawImagePlugin from 'phaser3-rex-plugins/plugins/cutjigsawimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCutJigsawImage',\nplugin: CutJigsawImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Cut image into pieces
    var pieces = scene.plugins.get('rexCutJigsawImage').gridCut(gameObjects, config);\n
"},{"location":"cutjigsawimage/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import CutJigsawImage from 'phaser3-rex-plugins/plugins/cutjigsawimage.js';\n
  • Cut image into pieces
    var images = CutJigsawImage(gameObjects, config);\n
"},{"location":"cutjigsawimage/#create-pieces","title":"Create pieces","text":"
var pieces = scene.plugins.get('rexCutJigsawImage').gridCut(gameObject, {\npiecesKey: ,\ncolumns: , rows: ,\nedgeWidth: , edgeHeight: ,\nuseDynamicTexture: true,\n\n// drawShapeCallback: undefined,\n// edges: undefined,    \n\n// createImageCallback: undefined,\n// ImageClass: Phaser.GameObjects.Image,\n\n// originX: 0.5,\n// originY: 0.5,\n// add: true,\n// align: true,\n// objectPool: undefined\n});\n
  • gameObjects : Target game object which has a texture, ex Image, RenderTexture.
  • piecesKey : Store frame of each piece in this dynamic texture.
    • undefined : Use 'gameObjects.texture.key' + '_pieces' as texture key.
  • columns, rows : Cut texture in columns x rows grids
  • edgeWidth, edgeHeight : Padding around piece.
  • useDynamicTexture : Generate frame of pieces on dynamic texture or canvas texture.
    • true : Generate frame of pieces on dynamic texture. Default value.
    • false : Generate frame of pieces on canvas texture.
  • drawShapeCallback : Callback of creating piece shape
    • undefined : Use default piece shape.
    • A function object
      function(graphics, width, height, edgeWidth, edgeHeight, edgeMode) {\n}\n
      • graphics : Graphics game object, or canvas.
        • Draw piece shape on a Graphics game object, if useDynamicTexture is set to true
        • Draw piece shape on canvas, if useDynamicTexture is set to false
      • width, height : Frame size of this piece
      • edgeWidth, edgeHeigh : Padding around piece.
      • edgeMode :
        {\nleft: 0,   // 0|1|2\nright: 0,  // 0|1|2\ntop: 0,    // 0|1|2\nbottom: 0  // 0|1|2\n}\n
        • left, right, top, bottom
          • 0 : Flat edge
          • 1 : Convex edge
          • 2 : Concave edge
  • edges : edgeMode in a 2d array for each piece
    • undefined : Create random edges for each piece.
  • createImageCallback : Custom callback to return an image game object, optional.
    function(scene, texture, frame) {\nreturn gameObject;\n}\n
    • texture : A texture object.
    • frame : Frame name.
  • ImageClass : Create image game object from this class. Default value is built-in Image class. Used when createImageCallback is undefined.
  • originX, originY : Origin of created image game objects
  • add :
    • true : Add these created image game objects to scene. Default value.
    • false : Don't add created image game objects to scene.
  • align :
    • true : Align position of created image game objects to target game object (gameObjects). Default value when add is set to true.
    • false : Don't set position of created image game objects. Default value when add is set to false.
  • objectPool : An array of image game objects, will reuse image game objects from this pool. Optional.
  • pieces : Return piece game objects.
    • Size of any piece game object (frame size) :
      • width : (gameObjects.width / columns) + (2 * edgeWidth)
      • height : (gameObjects.height / rows) + (2 * edgeHeigh)
    • Frame name of a piece game object : columnIndex + ',' + rowIndex
"},{"location":"datamanager/","title":"Built-in data","text":""},{"location":"datamanager/#introduction","title":"Introduction","text":"

Store data in key-value pairs, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"datamanager/#usage","title":"Usage","text":""},{"location":"datamanager/#write","title":"Write","text":""},{"location":"datamanager/#set-value","title":"Set value","text":"
  • Set value
    parent.data.set(key, value);\n
    or
    parent.data.values[key] = value;\n
    • key : Key string.
  • Increase number value. If the key doesn't already exist in the Data Manager then it is increased from 0.
    parent.data.inc(key, data);\n
    or
    parent.data.values[key] += value;\n
    • data : The value to increase.
  • Toggle boolean value. If the key doesn't already exist in the Data Manager then it is toggled from false.
    parent.data.toggle(key);\n
    or
    parent.data.values[key] = !parent.data.values[key];\n
"},{"location":"datamanager/#set-values","title":"Set values","text":"
parent.data.set(data);    // data: {key:value, ...}\n
"},{"location":"datamanager/#merge-values","title":"Merge values","text":"
parent.data.merge(data);  // data: {key:value, ...}\nparent.data.merge(data, false);  // won't overwrite existed keys\n
"},{"location":"datamanager/#events","title":"Events","text":"

Fires setdata event when a value is first set.

parent.data.events.on('setdata', function(parent, key, value){ /* ... */ });\n

Fires changedata, and changedata- + key events when a value is set that already exists.

parent.data.events.on('changedata', function(parent, key, value, previousValue){ /* ... */ });\n
parent.data.events.on('changedata-' + key, function(parent, value, previousValue){ /* ... */ });\n
"},{"location":"datamanager/#read","title":"Read","text":""},{"location":"datamanager/#get-value","title":"Get value","text":"

var value = parent.data.get(key);\n
or
var value = parent.data.values[key];\n

"},{"location":"datamanager/#get-values","title":"Get values","text":"
var values = parent.data.get(keys); // values: [value, value, ...], keys: [key, key, ...]\n
"},{"location":"datamanager/#get-all-values","title":"Get all values","text":"
var allValues = parent.data.getAll();  // return a copy of data\n
"},{"location":"datamanager/#query","title":"Query","text":"

Using string.match() to pick matched keys.

var result = parent.data.query(rgExp);\n
"},{"location":"datamanager/#remove","title":"Remove","text":""},{"location":"datamanager/#remove-key","title":"Remove key","text":"
parent.data.remove(key);\n
"},{"location":"datamanager/#remove-keys","title":"Remove keys","text":"
parent.data.remove(keys);  // keys: [key, key, ...]\n
"},{"location":"datamanager/#pop-key","title":"Pop key","text":"
var value = parent.data.pop(key);\n

Get and remove that key.

"},{"location":"datamanager/#delet-all-keys","title":"Delet all keys","text":"

Delete all data in this Data Manager and unfreeze it.

parent.data.reset();\n
"},{"location":"datamanager/#events_1","title":"Events","text":"

Fires removedata event when a key is removed.

parent.data.events.on('removedata', function(parent, key, value){ /* ... */ });\n
"},{"location":"datamanager/#freeze","title":"Freeze","text":"
var isFrozen = parent.data.freeze;\nparent.data.freeze = true;\n

No changes can be written to it.

"},{"location":"datamanager/#has-key","title":"Has key","text":"
var hasKey = parent.data.has(key);\n
"},{"location":"datamanager/#for-each-key","title":"For each key","text":"
parent.data.each(function(parent, key, value){\n/* ... */\n}, scope);\n
"},{"location":"datamanager/#count-of-data","title":"Count of data","text":"
var cnt = parent.data.count;\n
"},{"location":"datamanager/#reset","title":"Reset","text":"

Reset status and clear all keys.

parent.data.reset()\n
"},{"location":"date/","title":"Date","text":""},{"location":"date/#introduction","title":"Introduction","text":"

Get current date or unix-timestamp.

  • Author: Built-in javascript function
"},{"location":"date/#usage","title":"Usage","text":"

Reference

"},{"location":"date/#create-instance","title":"Create instance","text":"
var d = new Date();\nvar d = new Date(timestamp);\nvar d = new Date(dateString);\nvar d = new Date(year, month, day, hours, minutes, seconds, milliseconds);\n
"},{"location":"date/#get-date","title":"Get date","text":"
var year = d.getFullYear();    // returns the year\nvar month = d.getMonth();      // returns the month (0-11)\nvar date = d.getDate();        // returns the day of the month (1-31)\nvar day = d.getDay();          // returns the day of the week\nvar hour = d.getHours();       // returns the hour (0-23)\nvar min = d.getMinutes();      // returns the minutes (0-59)\nvar sec = d.getSeconds();      // returns the seconds (0-59)\nvar ms = d.getMilliseconds();  // returns the milliseconds (0-999)\n
"},{"location":"date/#get-unix-timestamp","title":"Get unix-timestamp","text":"
var timestamp = d.getTime();;   // unix-timestamp in milliseconds\n

or

var timestamp = Date.now();;    // unix-timestamp in milliseconds\n
"},{"location":"date/#to-string","title":"To string","text":"
var s = d.toLocaleString();   // locale conventions\nvar iso = d.toISOString();    // ISO standard\n
"},{"location":"device/","title":"Device","text":""},{"location":"device/#introduction","title":"Introduction","text":"

Get information of device, built-in properties of phaser.

  • Author: Richard Davey
"},{"location":"device/#usage","title":"Usage","text":""},{"location":"device/#os","title":"OS","text":"
  • Platform
    scene.sys.game.device.os.android      // Is running on android?\nscene.sys.game.device.os.chromeOS     // Is running on chromeOS?\nscene.sys.game.device.os.cordova      // Is the game running under Apache Cordova?\nscene.sys.game.device.os.crosswalk    // Is the game running under the Intel Crosswalk XDK?\nscene.sys.game.device.os.desktop      // Is running on a desktop?\nscene.sys.game.device.os.ejecta       // Is the game running under Ejecta?\nscene.sys.game.device.os.electron     // Is the game running under GitHub Electron?\nscene.sys.game.device.os.iOS          // Is running on iOS?\nscene.sys.game.device.os.iPad         // Is running on iPad?\nscene.sys.game.device.os.iPhone       // Is running on iPhone?\nscene.sys.game.device.os.kindle       // Is running on an Amazon Kindle?\nscene.sys.game.device.os.linux        // Is running on linux?\nscene.sys.game.device.os.macOS        // Is running on macOS?\nscene.sys.game.device.os.node         // Is the game running under Node.js?\nscene.sys.game.device.os.nodeWebkit   // Is the game running under Node-/Webkit?\nscene.sys.game.device.os.webApp       // Set to true if running as a WebApp, i.e. within a WebView\nscene.sys.game.device.os.windows      // Is running on windows?\nscene.sys.game.device.os.windowsPhone // Is running on a Windows Phone?\n
  • Major version number of ios
    var version = scene.sys.game.device.os.iOSVersion;\n
  • Pixel-ratio of the host device
    var pixelRatio = scene.sys.game.device.os.pixelRatio;\n
"},{"location":"device/#browser","title":"Browser","text":"
  • Platform
    scene.sys.game.device.browser.chrome       // Is running in Chrome?\nscene.sys.game.device.browser.edge         // Is running in Microsoft Edge browser?\nscene.sys.game.device.browser.firefox      // Is running in Firefox?\nscene.sys.game.device.browser.ie           // Is running in Internet Explorer 11 or less (not Edge)?\nscene.sys.game.device.browser.mobileSafari // Is running in Mobile Safari?\nscene.sys.game.device.browser.opera        // Is running in Opera?\nscene.sys.game.device.browser.safari       // Is running in Safari?\nscene.sys.game.device.browser.silk         // Is running in the Silk browser (as used on the Amazon Kindle)?\nscene.sys.game.device.browser.trident       // Is running a Trident version of Internet Explorer (IE11+)?\n
  • Version
    var version = scene.sys.game.device.browser.chromeVersion;\nvar version = scene.sys.game.device.browser.firefoxVersion;\nvar version = scene.sys.game.device.browser.ieVersion;\nvar version = scene.sys.game.device.browser.safariVersion;\nvar version = scene.sys.game.device.browser.tridentVersion;\n
"},{"location":"device/#audio","title":"Audio","text":"
var flac = scene.sys.game.device.audio.flac;\nvar aac = scene.sys.game.device.audio.aac;\nvar dolby = scene.sys.game.device.audio.dolby;\nvar m4a = scene.sys.game.device.audio.m4a;\nvar mp3 = scene.sys.game.device.audio.mp3;\nvar ogg = scene.sys.game.device.audio.ogg;\nvar opus = scene.sys.game.device.audio.opus;\nvar wav = scene.sys.game.device.audio.wav;\nvar webm = scene.sys.game.device.audio.webm;\nvar webAudio = scene.sys.game.device.audio.webAudio;\nvar audioData = scene.sys.game.device.audio.audioData;\n
"},{"location":"device/#video","title":"Video","text":"
var h264Video = scene.sys.game.device.video.h264;  // Can this device play h264 mp4 video files?\nvar hlsVideo = scene.sys.game.device.video.hls;    // Can this device play hls video files?\nvar mp4Video = scene.sys.game.device.video.mp4;    // Can this device play h264 mp4 video files?\nvar m4vVideo = scene.sys.game.device.video.m4v;    // Can this device play m4v (typically mp4) video files?\nvar oggVideo = scene.sys.game.device.video.ogg;    // Can this device play ogg video files?\nvar vp9Video = scene.sys.game.device.video.vp9;    // Can this device play vp9 video files?\nvar webmVideo = scene.sys.game.device.video.webm;  // Can this device play webm video files?\n
"},{"location":"dialog-quest/","title":"Dialog-quest","text":""},{"location":"dialog-quest/#introduction","title":"Introduction","text":"

Flow control of question manager with a dialog.

  • Author: Rex
  • Template
"},{"location":"dialog-quest/#live-demos","title":"Live demos","text":"
  • Branch
  • Shuffle
"},{"location":"dialog-quest/#usage","title":"Usage","text":"

Sample code

"},{"location":"dialog-quest/#install-plugin","title":"Install plugin","text":""},{"location":"dialog-quest/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');    scene.load.script('rexdialogquest', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdialogquest.min.js');\n
  • Add dialog and quest object
    var dialog = scene.rexUI.add.dialog(config); var quest = new rexdialogquest({\ndialog: dialog,\n// ...\n});\n
"},{"location":"dialog-quest/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nimport DialogQuest from 'phaser3-rex-plugins/templates/dialog-quest/DialogQuest.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add dialog and quest object
    var dialog = scene.rexUI.add.dialog(config); var quest = new DialogQuest({\ndialog: dialog,\n// ...\n});\n
"},{"location":"dialog-quest/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Dialog } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\nimport DialogQuest from 'phaser3-rex-plugins/templates/dialog-quest/DialogQuest.js';\n
  • Add dialog object
    var dialog = new Dialog(scene, config);\nscene.add.existing(dialog);\nvar quest = new DialogQuest({\ndialog: dialog,\n// ...\n});\n
"},{"location":"dialog-quest/#create-dialog-quest-object","title":"Create dialog-quest object","text":"
var quest = new DialogQuest({\ndialog: dialog,\n\nquestions: undefined,\n// format: undefined,\n// delimiter: ',',\n// types: {\n//     question: 'q',\n//     option: '',\n// },\n// convert: true,\n\nquest: true,\n// quest: {\n//     shuffleQuestions: false,\n//     shuffleOptions: false,\n// }\n});\n
  • dialog : A dialog game object.
    • UI plugin does not included in this template, install it before creating a dialog game object.
    • Reuse/update dialog game object for each question.
    • The number of choice buttons should be equal or larger than the maximun number of options.
  • Other parameters : See quest
"},{"location":"dialog-quest/#flow-chart","title":"Flow chart","text":"
graph TB\n\nStart[\"quest.start()\"] --> EventUpdateChoice[\"quest.emit('update-choice', choice, option, quest)<br>----<br>Update each choice button via question.option[i]\"]\n\nEventUpdateChoice --> EventUpdateDialog[\"quest.emit('update-dialog', dialog, question, quest)<br>----<br>Update dialog, action button via question\"]\n\nEventUpdateDialog --> EventClickChoice[\"quest.emit('click-choice', choice, dialog, quest)<br>----<br>Click any choice button\"]\n\nEventClickChoice --> EventClickAction[\"quest.emit('click-action', action, dialog, quest)<br>----<br>Click any action button\"]\n\nEventClickAction --> IsLast{\"quest.isLast()\"}\nEventClickChoice --> IsLast\n\nIsLast --> |No| Next[\"quest.next()\"]\nIsLast --> |Yes| Complete(\"Complete\")\n\nNext --> EventUpdateChoice
"},{"location":"dialog-quest/#events","title":"Events","text":"
  • Update dialog events
    • Update each choice button via question.option[i]
      quest.on('update-choice', function(choice, option, quest){\n}, scope);\n
      • choice : Choice button game object.
        • Unused choice button game object will be hideen.
      • option : Option object.
      • quest : Quest object.
    • Update dialog, action buttos via question
      quest.on('update-dialog', function(dialog, question, quest){\n}, scope);\n
      • dialog : Dialog game object.
        • Call dialog.layout() if needs.
      • question : Question object.
      • quest : Quest object.
  • Button clicking events
    • Click choice button
      quest.on('click-choice', function(choice, dialog, quest) {\n\n}, scope);\n
      • choice : Clicked choice button game object.
      • dialog : Dialog game object.
      • quest : Quest object.
    • Click choice button
      quest.on('click-action', function(action, dialog, quest) {\n\n}, scope);\n
      • choice : Clicked action button game object.
      • dialog : Dialog game object.
      • quest : Quest object.
"},{"location":"dialog-quest/#quest-methods","title":"Quest methods","text":"
  • Start quest
    quest.start();\n
  • Next quest
    quest.next();\n
    or
    quest.next(key);\n
  • Is last question
    var isLast = quest.isLast();\n
  • Remove all questions
    quest.removeAll();\n
  • Add questions
    quest.add(questions, config);\n
    • questions : An array of question objects, or a csv string. See questions section in Create question manager instance section.
    • config :
      • delimiter : Delimiter of csv string. Default value is ','
      • types : Define value of row type.
        • types.question : Define value of question row. Default value is q.
        • types.option : Define value of option row. Default value is '' (empty string).
      • convert : Convert string values to other types.
        • Default type converting : Convert string to number, boolean, null, or string
          • '0', '1', ... (number string) -> number
          • 'true', or 'false' -> true or false
          • '' (empty string) -> null
          • Others : string.
        • Set false to ignore types converting, i.e. all values are string.
        • A custom type converting function :
          function(stringValue, key) {\n// return value;\n}\n
"},{"location":"dialog-quest/#private-data-methods","title":"Private data methods","text":"
  • Get data
    var value = quest.getData(key, defaultValue);\n
  • Get all data
    var data = quest.getData();\n
  • Set value
    quest.setData(key, value);\n
  • Increase value
    quest.incData(key, inc, defaultValue);\n
  • Multiple value
    quest.mulData(key, mul, defaultValue);\n
  • Clear all data
    quest.clearData();\n
"},{"location":"distance/","title":"Distance","text":""},{"location":"distance/#introduction","title":"Introduction","text":"

Get distance, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"distance/#usage","title":"Usage","text":""},{"location":"distance/#distance","title":"Distance","text":"
  • Get distance between 2 points
    var d = Phaser.Math.Distance.Between(x1, y1, x2, y2);\n
    or
    var d = Phaser.Math.Distance.BetweenPoints(a, b); // a, b: {x, y}\n
  • Get squared distance
    var d = Phaser.Math.Distance.BetweenPointsSquared(a, b); // a, b: {x, y}\n
  • Get Chebyshev distance (the maximum of the horizontal and vertical distances)
    var d = Phaser.Math.Distance.Chebyshev(x1, y1, x2, y2);\n
  • Get snake distance(i.e. rectilinear distance, Manhattan distance, the sum of the horizontal and vertical distance)
    var d = Phaser.Math.Distance.Snake(x1, y1, x2, y2);\n
  • Get power distance (the sum of the horizontal power distance and vertical power distance)
    var d = Phaser.Math.Distance.Power(x1, y1, x2, y2);\n
"},{"location":"distance/#speed","title":"Speed","text":"
  • Get speed
    var d = Phaser.Math.GetSpeed(distance, time);\n
    • distance : The distance to travel in pixels.
    • time : The time, in ms, to cover the distance in.
"},{"location":"domelement/","title":"DOM element","text":""},{"location":"domelement/#introduction","title":"Introduction","text":"

Carry DOM element, built-in game object of phaser.

Limitations

Dom elements appear above or below your game canvas. You cannot blend them into the display list, meaning you cannot have a DOM Element, then a Sprite, then another DOM Element behind it.

  • Author: Richard Davey
"},{"location":"domelement/#usage","title":"Usage","text":""},{"location":"domelement/#configuration","title":"Configuration","text":"
  • Set parent to divId
  • Set dom.createContainer to true.
var config = {\n// ...\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n}\nvar game = new Phaser.Game(config);\n
"},{"location":"domelement/#add-dom-element-object","title":"Add DOM element object","text":""},{"location":"domelement/#add-html-string","title":"Add html string","text":"
  1. Load html string in preload stage
    scene.load.html(key, url);\n
    Reference: load html
  2. Add DOM element object with html string from cache
    var domElement = scene.add.dom(x, y).createFromCache(key);  // elementType = 'div'\n// var domElement = scene.add.dom(x, y).createFromCache(key, elementType);\n
    • Add DOM element object with html string
      var domElement = scene.add.dom(x, y).createFromHTML(htmlString);  // elementType = 'div'\n// var domElement = scene.add.dom(x, y).createFromHTML(htmlString, elementType);\n
      • `elementType : The tag name of the element into which all of the html will be inserted. Defaults to a plain div tag.
"},{"location":"domelement/#create-element","title":"Create element","text":"
scene.add.dom(x, y).createElement(tagName);\n// scene.add.dom(x, y).createElement(tagName, style, innerText);\n
  • tagName : A string that specifies the type of element to be created. For example, 'div'
  • style : Either a DOMString that holds the CSS styles to be applied to the created element, or an object the styles will be readyfrom. Optional.
  • innerText : A DOMString that holds the text that will be set as the innerText of the created element. Optional.
"},{"location":"domelement/#add-existing-dom","title":"Add existing DOM","text":"
  1. Create DOM element
    var el = document.createElement('div');\n// el.style = '...';\n// el.innerText = '...';\n
  2. Add to scene
    var domElement = scene.add.dom(x, y, el);\n// var domElement = scene.add.dom(x, y, el, style, innerText);\n
"},{"location":"domelement/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDOMElement extends Phaser.GameObjects.DOMElement {\nconstructor(scene, x, y, element, style, innerText) {\nsuper(scene, x, y, element, style, innerText);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var domElement = new MyDOMElement(scene, x, y, element);\n
"},{"location":"domelement/#event-of-dom-element","title":"Event of DOM element","text":"
  • Add listener
    domElement.addListener(eventName);\n
    • eventName : Event name
      • Single string. ex. 'click'
      • Event name joined with ' '
  • Add event handler
    var callback = function(event) {\n// event.target.name\n};\ndomElement.on(eventName, callback, scope);\n// domElement.once(eventName, callback, scope);\n
    Reference: event emitter
  • Remove listener
    domElement.removeListener(eventName);\n
    • eventName : Event name
      • Single string. ex. 'click'
      • Event name joined with ' '
"},{"location":"domelement/#get-child","title":"Get child","text":"
  • Get child by name
    var child = domElement.getChildByName(name)\n
  • Get child by id
    var child = domElement.getChildByID(id)\n
  • Get child by property
    var child = domElement.getChildByProperty(property, value)\n
"},{"location":"domelement/#set-inner-html-string","title":"Set inner html string","text":"
scene.setHTML(html);\n

or

scene.setText(html);\n
"},{"location":"domelement/#dom-element","title":"DOM Element","text":"

Each DOM element object has 1 DOM element.

  • Set
    domElement.setElement(el);\n// domElement.setElement(el, style, innerText);\n
  • Get
    var el = domElement.node;\n
"},{"location":"domelement/#depth","title":"Depth","text":"
domElement.setDepth(value);\n
"},{"location":"domelement/#set-size","title":"Set size","text":"
var style = domElement.node.style;\nstyle.width = width + 'px';\nstyle.height = height + 'px';\ndomElement.updateSize();\n
"},{"location":"domelement/#skew","title":"Skew","text":"
domElement.setSkew(x, y);\n

or

domElement.skewX = x;\ndomElement.skewY = y;\n
"},{"location":"domelement/#rotate-3d","title":"Rotate 3d","text":"

The rotate3d() CSS function defines a transformation that rotates an element around a fixed axis in 3D space, without deforming it.

domElement.rotate3d.set(x, y, z, a);\n

or

domElement.rotate3d.x = x;\ndomElement.rotate3d.y = y;\ndomElement.rotate3d.z = z;\ndomElement.rotate3d.w = a;\n

Reference

"},{"location":"domelement/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"
  1. DOM game object always put above game canvas, i.e. DOM game object will render above any other kind of game object.
  2. DOM game object will receive touch event even if it is not the first touched game object.
  3. P3's 'pointerdown', 'pointerup' events will be fired above/under DOM game object.
  4. P3's 'pointermove' event won't be fired above/under DOM game object, except
    • Setting DOM game object to be invisilbe.
    • Assign input.mouse.target parameter of game config.
  5. DOM game object only can be displayed by main camera. i.e. dom game object can't add to other camera.
"},{"location":"domelement/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"drag/","title":"Drag","text":""},{"location":"drag/#introduction","title":"Introduction","text":"

Drag game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"drag/#live-demos","title":"Live demos","text":"
  • Try dragging
"},{"location":"drag/#usage","title":"Usage","text":"

Sample code

"},{"location":"drag/#install-plugin","title":"Install plugin","text":""},{"location":"drag/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexdragplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdragplugin.min.js', true);\n
  • Add drag behavior
    var drag = scene.plugins.get('rexdragplugin').add(gameObject, config);\n
"},{"location":"drag/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import DragPlugin from 'phaser3-rex-plugins/plugins/drag-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexDrag',\nplugin: DragPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add drag behavior
    var drag = scene.plugins.get('rexDrag').add(gameObject, config);\n
"},{"location":"drag/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Drag from 'phaser3-rex-plugins/plugins/drag.js';\n
  • Add drag behavior
    var drag = new Drag(gameObject, config);\n
"},{"location":"drag/#create-instance","title":"Create instance","text":"
var drag = scene.plugins.get('rexDrag').add(gameObject, {\n// enable: true,\n// axis: 0,      //0|'both'|'h&v'|1|'horizontal'|'h'|2|'vertical'|'v'\n// rotation: Phaser.Math.DegToRad(45)  // axis rotation in rad\n});\n
  • enable : Set false to disable input events.
  • axis :
    • 'both','h&v', 'x&y', or 0 : Dragging on all directions.
    • 'horizontal','h', 'x', or 1 : Dragging on horizontal/x axis.
    • 'vertical','v', 'y', or 2 : Dragging on vertical/y axis.
  • rotation : Axis rotation in rad, available in horizontal or vertical axis mode.
"},{"location":"drag/#events","title":"Events","text":"

Built-in dragging events

gameObject.on('dragstart', function(pointer, dragX, dragY){ /*...*/ });\ngameObject.on('drag', function(pointer, dragX, dragY){ /*...*/ });\ngameObject.on('dragend', function(pointer, dragX, dragY, dropped){ /*...*/ });\n
"},{"location":"drag/#enable","title":"Enable","text":"
  • Get
    var enable = drag.enable;  // enable: true, or false\n
  • Set
    drag.setEnable(enable);  // enable: true, or false\n// drag.enable = enable;\n
  • Toggle
    drag.toggleEnable();\n
"},{"location":"drag/#get-dragging-state","title":"Get dragging state","text":"
var isDragging = drag.isDragging;\n
"},{"location":"drag/#set-rotation-of-axis","title":"Set rotation of axis","text":"
drag.setAxisRotation(rad);\n// drag.axisRotation = rad;\n
"},{"location":"drag/#set-axis-mode","title":"Set axis mode","text":"
drag.setAxisMode(axis);\n
  • axis :
    • 'both','h&v', 'x&y', or 0 : Dragging on all directions.
    • 'horizontal','h', 'x', or 1 : Dragging on horizontal/x axis.
    • 'vertical','v', 'y', or 2 : Dragging on vertical/y axis.
"},{"location":"drag/#try-drag","title":"Try drag","text":"

Game object will be dragged if there is any point above it.

drag.drag();\n
"},{"location":"drag/#drop","title":"Drop","text":"

Game object will be dropped(dragend) manually.

drag.dragend();\n
"},{"location":"dragrotate/","title":"Drag rotate","text":""},{"location":"dragrotate/#introduction","title":"Introduction","text":"

Get dragging angle around a specific point.

  • Author: Rex
  • Member of scene
"},{"location":"dragrotate/#live-demos","title":"Live demos","text":"
  • Spin-button
  • Origin game object
"},{"location":"dragrotate/#usage","title":"Usage","text":"

Sample code

"},{"location":"dragrotate/#install-plugin","title":"Install plugin","text":""},{"location":"dragrotate/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexdragrotateplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdragrotateplugin.min.js', true);\n
  • Add drag-rotate input
    var dragRotate = scene.plugins.get('rexdragrotateplugin').add(scene, config);\n
"},{"location":"dragrotate/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import DragRotatePlugin from 'phaser3-rex-plugins/plugins/dragrotate-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexDragRotate',\nplugin: DragRotatePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add drag-rotate input
    var dragRotate = scene.plugins.get('rexDragRotate').add(scene, config);\n
"},{"location":"dragrotate/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import DragRotate from 'phaser3-rex-plugins/plugins/dragrotate.js';\n
  • Add drag-rotate input
    var dragRotate = new DragRotate(scene, config);\n
"},{"location":"dragrotate/#create-instance","title":"Create instance","text":"
var dragRotate = scene.plugins.get('rexDragRotate').add(scene, {\norigin: undefined,\nx: 0,\ny: 0,\n\nmaxRadius: undefined\nminRadius: 0,\n\n// enable: true,\n});\n
  • origin : Use game object's position as origin point.
    • undefined : Use fixed origin position.
  • x, y : Fixed orgin point, in world position.
  • maxRadius, minRadius : Dragging is valid when distance between touch pointer and origin position is larger then minRadius and less then maxRadius.
  • enable : Set false to disable input events.
"},{"location":"dragrotate/#enable","title":"Enable","text":"
  • Get
    var enable = dragRotate.enable;  // enable: true, or false\n
  • Set
    dragRotate.setEnable(enable);  // enable: true, or false\n// dragRotate.enable = enable;\n
  • Toggle
    dragRotate.toggleEnable();\n
"},{"location":"dragrotate/#origin-point","title":"Origin point","text":"
  • Use game object's position as origin point.
    dragRotate.setOrigin(gameObject);\n
  • Fixed orgin point
    • Get
      var x = dragRotate.x;\nvar y = dragRotate.y;\n
    • Set
      dragRotate.setOrigin(x, y);\n
      or
      dragRotate.setOrigin(pointer); // pointer: {x, y}\n

Note

Parameter (x,y) is world position, not camera position.

"},{"location":"dragrotate/#radius","title":"Radius","text":"
  • Get
    var maxRadius = dragRotate.maxRadius;\nvar minRadius = dragRotate.minRadius;\n
  • Set
    dragRotate.setRadius(maxRadius, minRadius);\n
"},{"location":"dragrotate/#get-dragging-state","title":"Get dragging state","text":"
var state = dragRotate.state;\n
  • 0 : No touch pointer
  • 1 : Catch touch pointer
    • Fire 'dragstart' event when catching touch pointers.
    • Fire 'drag' event when any catched touch pointer moved.
    • Fire 'dragend' event when releasing catched touch pointer.
"},{"location":"dragrotate/#is-drag","title":"Is drag","text":"
var isDrag = dragRotate.isDrag;\n

Return true if (dragRotate.state === 1) and catched touch pointer just moved.

"},{"location":"dragrotate/#drag-cancel","title":"Drag cancel","text":"
dragRotate.dragCancel();\n
"},{"location":"dragrotate/#events","title":"Events","text":""},{"location":"dragrotate/#on-dragging","title":"On dragging","text":"
  • On dragging
    dragRotate.on('drag', function(dragRotate) {\n// gameObject.rotation += dragRotate.deltaRotation;\n}, scope);\n
    • dragRotate.deltaRotation : Dragging angle around origin position, in radians.
      • Add to gameObject.rotation to spin target game object.
        gameObject.rotation += dragRotate.deltaRotation;\n
    • dragRotate.deltaAngle : Dragging angle around origin position, in degrees.
      • Add to gameObject.angle to spin target game object.
        gameObject.angle += dragRotate.deltAangle;\n
    • dragRotate.cw : Return true if dragging is dragrotate-wise.
    • dragRotate.ccw : Return true if dragging is counter-dragrotate-wise.
"},{"location":"dragrotate/#on-drag-start-on-drag-end","title":"On drag start, on drag end","text":"
  • On drag touch pointer start, fired when catching touch pointer.
    dragRotate.on('dragstart', function(dragRotate) {\n\n}, scope);\n
  • On drag touch pointer end, fired when releasing the catched touch pointer.
    dragRotate.on('dragend', function(dragRotate) {\n\n}, scope);\n
"},{"location":"dragrotate/#catched-touch-pointer","title":"Catched touch pointer","text":"
  • Pointer, available when state is 1
    var pointer = dragRotate.pointer;\n
    • World position of pointer
      var x = pointer.worldX;\nvar y = pointer.worldY;\n
"},{"location":"dropdown/","title":"Drop down","text":""},{"location":"dropdown/#introduction","title":"Introduction","text":"

Drop down game object below another target game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"dropdown/#live-demos","title":"Live demos","text":"
  • Drop-down
"},{"location":"dropdown/#usage","title":"Usage","text":"

Sample code

"},{"location":"dropdown/#install-plugin","title":"Install plugin","text":""},{"location":"dropdown/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexdropdownplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdropdownplugin.min.js', true);\n
  • Add drop-down behavior
    var dropDown = scene.plugins.get('rexdropdownplugin').add(gameObject, config);\n
"},{"location":"dropdown/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add drop-down behavior
    var dropDown = scene.plugins.get('rexDropDown').add(gameObject, config);\n
"},{"location":"dropdown/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import DropDownBehavior from 'phaser3-rex-plugins/plugins/dropdown.js';\n
  • Add drop-down behavior
    var dropDown = new DropDownBehavior(gameObject, config);\n
"},{"location":"dropdown/#create-instance","title":"Create instance","text":"
var dropDown = scene.plugins.get('rexDropDown').add(gameObject, {        // expandDirection: 0,\n// alignTargetX: \n// alignTargetY: \n// alignOffsetX: \n// alignOffsetY: \n// bounds:\n\n// When to close dropdown dialog?\n// touchOutsideClose: false,\n// anyTouchClose: false,\n\n// duration: {\n//     in: 200,\n//     out: 200\n// }\n\n// transitIn: undefined,\n// transitOut: undefined,\n\n// destroy: true\n});\n
  • expandDirection : Expand direction
    • 0, 'down' : Expand game object down. i.e. game object will put below target game object. Defatut behavior.
    • 1, 'up' : Expand game object up. i.e. game object will put above target game object.
  • alignTargetX : Align left side game object to left side of target game object
  • alignTargetY : Required parameter
    • Align top side game object to bottom side of target game object, if expandDirection is 0('down').
    • Align bottom side game object to top side of target game object, if expandDirection is 1('up').
  • alignOffsetX, alignOffsetY : Extra position offset. Default value ares 0, 0.
  • bounds : Put game object below target game object if bottom of game object is inside bounds (Rectangle)
    • undefined : Use viewport as bounds
    • Rectangle
  • touchOutsideClose : Set to true to close dropdown dialog when clicking out side of gameObject.
    • Default value is false. Will be set to false if anyTouchClose is set to true.
  • anyTouchClose : Set to true to close dropdown dialog when any clicking.
    • Default value is false.
  • duration : Duration of transition-in, hold, trantion-out.
    • duration.in : Duration of transition-in (open dialog).
      • 0 : No transition, open dialog immediately.
    • duration.out : Duration of transition-out (close dialog).
      • 0 : No transition, close dialog immediately.
  • transitIn : Tween behavior of opening dialog. Default behavior is scale up the height of game object.
    • Custom callback
      function(gameObject, duration) {\n\n}\n
  • transitOut : Tween behavior of closing dialog. Default behavior is scale down the height of game
    • Custom callback
      function(gameObject, duration) {\n\n}\n
  • destroy
    • true : Destroy dialog when closing completed. Default behavior.
    • fasle : Don't destroy dialog.
"},{"location":"dropdown/#close","title":"Close","text":"
dropDown.requestClose();\n// dropDown.requestClose();\n
"},{"location":"dropdown/#events","title":"Events","text":"
  • On opened dialog
    dropDown.on('open', function(gameObject, dropdown) {\n})\n
  • On closed dialog
    dropDown.on('close', function(closeEventData) {\n})\n
"},{"location":"dynamic-texture/","title":"Dynamic texture","text":""},{"location":"dynamic-texture/#introduction","title":"Introduction","text":"

Canvas Dynamic Texture stored in texture cache, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"dynamic-texture/#usage","title":"Usage","text":""},{"location":"dynamic-texture/#create-dynamic-texture","title":"Create dynamic texture","text":"
var texture = scene.textures.addDynamicTexture(key, width, height);\n

Disable texture.isSpriteTexture if this texture is not a base texture for Sprite Game Objects.

texture.setIsSpriteTexture(false);\n// texture.isSpriteTexture = false;\n
"},{"location":"dynamic-texture/#set-size","title":"Set size","text":"
texture.setSize(width, height);\n
"},{"location":"dynamic-texture/#fill-color","title":"Fill color","text":"
texture.fill(rgb);\n// texture.fill(rgb, alpha, x, y, width, height);\n
  • rgb : The number color to fill this Dynamic Texture with.
  • alpha : The alpha value used by the fill. Default value is 1.
  • x, y, width, height : The area of the fill rectangle. Default behavior is filling whole size.
"},{"location":"dynamic-texture/#clear","title":"Clear","text":"
texture.clear();\n
texture.clear(x, y, width, height);\n
"},{"location":"dynamic-texture/#draw-game-object","title":"Draw game object","text":"
texture.draw(entries);\n// texture.draw(entries,x, y);\n// texture.draw(entries, x, y, alpha, tint);\n
  • entries :
    • Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
    • Tilemap Layers.
    • A Group. The contents of which will be iterated and drawn in turn.
    • A Container. The contents of which will be iterated fully, and drawn in turn.
    • A Scene Display List. Pass in Scene.children to draw the whole list.
    • Another Dynamic Texture, or a Render Texture.
    • A Texture Frame instance.
    • A string. This is used to look-up the texture from the Texture Manager.
  • x, y : The x/y position to draw the Frame at, or the offset applied to the object.
    • If the object is a Group, Container or Display List, the coordinates are added to the positions of the children.
    • For all other types of object, the coordinates are exact.
  • alpha, tint : Only used by Texture Frames.
    • Game Objects use their own alpha and tint values when being drawn.
"},{"location":"dynamic-texture/#erase","title":"Erase","text":"
texture.erase(entries);\n// texture.erase(entries, x, y);\n
  • entries :
    • Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
    • Tilemap Layers.
    • A Group. The contents of which will be iterated and drawn in turn.
    • A Container. The contents of which will be iterated fully, and drawn in turn.
    • A Scene Display List. Pass in Scene.children to draw the whole list.
    • Another Dynamic Texture, or a Render Texture.
    • A Texture Frame instance.
    • A string. This is used to look-up the texture from the Texture Manager.
  • x, y : The x/y position to draw the Frame at, or the offset applied to the object.
    • If the object is a Group, Container or Display List, the coordinates are added to the positions of the children.
    • For all other types of object, the coordinates are exact.
"},{"location":"dynamic-texture/#draw-frame","title":"Draw frame","text":"
texture.stamp(key, frame, x, y, {\nalpha: 1,\ntint: 0xffffff,\nangle: 0,\nrotation: 0,\nscale: 1,\nscaleX: 1,\nscaleY: 1,\noriginX: 0.5,\noriginY: 0.5,\nblendMode: 0,\nerase: false,\nskipBatch: false\n})\n

or

texture.drawFrame(key, frame, x, y);\n// texture.drawFrame(key, frame, x, y, alpha, tint);\n
  • x, y : Top-left position
"},{"location":"dynamic-texture/#draw-repeat-frames","title":"Draw repeat frames","text":"
  • Repeat frames full of size
    texture.repeat(key, frame);\n
  • Repeat in an area
    texture.repeat(key, frame, x, y, width, height);\n// texture.repeat(key, frame, x, y, width, height, alpha, tint, skipBatch);\n
"},{"location":"dynamic-texture/#add-frame","title":"Add frame","text":"
texture.add(name, sourceIndex, x, y, width, height);\n
  • name : The name of this Frame. The name is unique within the Texture.
  • sourceIndex : The index of the TextureSource that this Frame is a part of.
  • x : The x coordinate of the top-left of this Frame.
  • y : The y coordinate of the top-left of this Frame.
  • width : The width of this Frame.
  • height : The height of this Frame.
"},{"location":"dynamic-texture/#batch-draw","title":"Batch draw","text":"
  1. Begin
    texture.beginDraw();\n
  2. Draw
    • Draw game object
      texture.batchDraw(entries, x, y, alpha, tint);\n
      • entries :
        • Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
        • Tilemap Layers.
        • A Group. The contents of which will be iterated and drawn in turn.
        • A Container. The contents of which will be iterated fully, and drawn in turn.
        • A Scene Display List. Pass in Scene.children to draw the whole list.
        • Another Dynamic Texture, or a Render Texture.
        • A Texture Frame instance.
        • A string. This is used to look-up the texture from the Texture Manager.
    • Draw frame
      texture.batchDrawFrame(key, frame, x, y, alpha, tint);\n
    • Draw image
      texture.stamp(key, frame, x, y, {\n// ...\nskipBatch: true\n})\n
    • Draw repeat images
      texture.repeat(key, frame, x, y, width, height, alpha, tint, true);\n
  3. End
    texture.endDraw();\n
"},{"location":"dynamic-texture/#internal-camera","title":"Internal camera","text":"

Internal camera texture.camera

  • Scroll (offset)
    texture.camera.setScroll(x, y);\n
  • Zoom (scale)
    texture.camera.setZoom(zoom);\n
  • Rotate
    texture.camera.setAngle(angle);  // angle in degrees\n
"},{"location":"dynamic-texture/#snapshot","title":"Snapshot","text":""},{"location":"dynamic-texture/#snapshot-area","title":"Snapshot area","text":"
texture.snapshot(callback);\n// texture.snapshot(callback, type, encoderOptions);\n

or

texture.snapshotArea(x, y, width, height, callback, type, encoderOptions);\n
  • callback : The Function to invoke after the snapshot image is created.
    function(imageElement) {\n}\n
    • imageElement : HTMLImageElement.
  • type : The format of the image to create, usually 'image/png' or 'image/jpeg'. Default value is 'image/png'.
  • encoderOptions : The image quality, between 0 and 1. Used for image formats with lossy compression, such as 'image/jpeg'. Default value is 0.92.
  • x, y, width, height : Snapshot area.
"},{"location":"dynamic-texture/#get-color-of-a-pixel","title":"Get color of a pixel","text":"
texture.snapshotPixel(x, y, callback);\n
  • x, y : The x/y coordinate of the pixel to get.
  • callback : The Function to invoke after the snapshot image is created.
    function(color) {        }\n
    • color : Color object.
"},{"location":"dynamicbitmaptext/","title":"Dynamic bitmap text","text":""},{"location":"dynamicbitmaptext/#introduction","title":"Introduction","text":"

Drawing text by texture with a callback for each character triggered at every tick, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"dynamicbitmaptext/#usage","title":"Usage","text":""},{"location":"dynamicbitmaptext/#load-bitmap-font","title":"Load bitmap font","text":"

Reference: load bitmap font

"},{"location":"dynamicbitmaptext/#add-bitmap-text-object","title":"Add bitmap text object","text":"
var txt = scene.add.dynamicBitmapText(x, y, key, text);\n// var txt = scene.add.dynamicBitmapText(x, y, key, text, size, align);\n
  • size : The size of the font
  • align : The alignment of the text in a multi-line BitmapText object.
    • 0 : Left aligned (default)
    • 1 : Middle aligned
    • 2 : Right aligned

Add text from JSON

var txt = scene.make.dynamicBitmapText({\nx: 0,\ny: 0,\ntext: 'Text\\nGame Object\\nCreated from config',\nfont: '',\nsize: false,\nalign: 0,\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
"},{"location":"dynamicbitmaptext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyText extends Phaser.GameObjects.DynamicBitmapText {\nconstructor(scene, x, y, key, text, size, align) {\nsuper(scene, x, y, key, text, size, align);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyText(scene, x, y, key, text);\n
"},{"location":"dynamicbitmaptext/#set-callback","title":"Set callback","text":"
var callback = function(data) {\n// input\n// data.index, data.charCode\n// data.x, data.y, data.scale, data.rotation\n// data.data\n// data.tint.topLeft, data.tint.topRight, data.tint.bottomLeft, data.tint.bottomRight    \n\n// modify input `data` then return it\n// ...\n// offset: data.y += 2\n// set tint: data.color = tint\nreturn data;\n}\ntxt.setDisplayCallback(callback);\n
"},{"location":"dynamicbitmaptext/#set-text","title":"Set text","text":"
txt.setText('...');\n

or

txt.text = '...';\n
"},{"location":"dynamicbitmaptext/#crop","title":"Crop","text":"
  • Set size
    txt.setSize(width, height);\n
    or
    txt.cropWidth = width;\ntxt.cropHeight = height;\n
  • Set offset
    txt.setScrollX(scrollX);\ntxt.setScrollY(scrollY);\n
    or
    this.scrollX = scrollX;\nthis.scrollY = scrollY;\n
"},{"location":"dynamicbitmaptext/#other-properties","title":"Other properties","text":"

See bitmap text, game object

"},{"location":"dynamicbitmaptext/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"dynamicbitmaptext/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"dynamictext/","title":"Dynamic text","text":""},{"location":"dynamictext/#introduction","title":"Introduction","text":"

Control position, angle of each character drawn on a canvas.

  • Author: Rex
  • Game object
"},{"location":"dynamictext/#live-demos","title":"Live demos","text":"
  • Wrap
    • Wrap modes
    • Horizontal alignment modes
  • Page typing
  • Align, rotation, drawBelowCallback
  • Vertical wrap
  • Character's world position
  • Child input event
"},{"location":"dynamictext/#usage","title":"Usage","text":"

Sample code

"},{"location":"dynamictext/#install-plugin","title":"Install plugin","text":""},{"location":"dynamictext/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexdynamictextplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdynamictextplugin.min.js', true);\n
  • Add dynamic-text object
    var txt = scene.add.rexDynamicText(x, y, width, height, config);\n
"},{"location":"dynamictext/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import DynamicTextPlugin from 'phaser3-rex-plugins/plugins/dynamictext-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexDynamicTextPlugin',\nplugin: DynamicTextPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add dynamic-text object
    var txt = scene.add.rexDynamicText(x, y, width, height, config);\n
"},{"location":"dynamictext/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import DynamicText from 'phaser3-rex-plugins/plugins/dynamictext.js';\n
  • Add dynamic-text object
    var txt = new DynamicText(scene, x, y, width, height, config);\nscene.add.existing(txt);\n
"},{"location":"dynamictext/#create-instance","title":"Create instance","text":"
var txt = scene.add.rexDynamicText({\nx: 0, y: 0,\nwidth: undefined, height: undefined,\nresolution: 1,\n\npadding: 0,  // {left: 0, right: 0, top: 0, bottom: 0}\n\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\n\ninnerBounds: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\n\nchildrenInteractive: false,\n\ntext: '',\n\nwrap: undefined,\n\ntestString: '|M\u00c9qgy',\n});\n
  • x, y : Position of this dynamic-text game object.
  • width : Fixed width.
    • A number : Width of this dynamic-text game object.
      • Wrap-width is width - padding.left - padding.right.
    • undefined : Width of this dynamic-text game object will be set after invoked runWordWrap method.
  • height : Fixed height.
    • A number : Height of this dynamic-text game object.
    • undefined : Height of this dynamic-text game object will be set after invoked runWordWrap method.
  • resolution : The resolution the content is rendered to its internal canvas at. Default value is 1.
  • padding : Padding of bounds.
    • A number
    • padding.left, padding.right, padding.top, padding.bottom
  • background : Properties of background round-rectangle.
    • background.color : Fill color, number or string.
      • null : No filling.
    • background.color2 : Gradient fill color, number or string.
      • null : No gradient filling.
    • background.horizontalGradient : Horizontal or vertical gradient filling.
      • true : Horizontal gradient filling.
      • false : Vertical gradient filling.
    • background.stroke : Stroke color, number or string.
      • null : No stroke.
    • background.strokeThickness : Line width of stroke.
    • background.cornerRadius : Corner-radius of round rectangle.
    • background.cornerIteration : Iteration of corner-radius.
      • null : Draw corner-radius via arc directly.
      • A number : Draw corner-radius via lines
  • innerBounds : Properties of inner-bounds.
    • innerBounds.color : Fill color, number or string.
      • null : No filling.
    • innerBounds.color2 : Gradient fill color, number or string.
      • null : No gradient filling.
    • innerBounds.horizontalGradient : Horizontal or vertical gradient filling.
      • true : Horizontal gradient filling.
      • false : Vertical gradient filling.
    • innerBounds.stroke : Stroke color, number or string.
      • null : No stroke.
    • innerBounds.strokeThickness : Line width of stroke.
  • style : Initial text-style.
    • style.bold : Bold
    • style.italic : Italic
    • style.fontSize : Font size, number or string.
    • style.fontFamily : Font family
    • style.color : Fill color, number or string.
    • style.stroke : Stroke color, number or string.
    • style.strokeThickness : Line width of stroke.
    • style.shadowColor : Shadow color, number or string.
      • null : No shadow.
    • style.shadowOffsetX : OffsetX of shadow.
    • style.shadowOffsetY : OffsetY of shadow.
    • style.shadowBlur : Blur of shadow.
    • style.backgroundColor : Background color of a character.
    • style.backgroundHeight, style.backgroundBottomY : Background position and height of a character.
      • undefined, or null : Use height of character as background height. Default behavior.
    • style.offsetX : OffsetX.
    • style.offsetY : OffsetY.
    • style.align : Override default line-alignment setting.
      • 0, 'left', 'top' : Align remainder lines to left/top.
      • 1, 'center' : Align remainder lines to center.
      • 2, 'right', 'bottom' : Align remainder lines to right/bottom.
      • undefined : Use default line-alignment setting.
  • childrenInteractive :
    • true : Fire input events ('child.pointerdown', 'child.pointerup', 'child.pointerover', 'child.pointerout') of any child after text.setInteractive().
    • false : Won't fire any input events of child. Default behavior.
  • text : Content of text.
  • wrap : Default configuration Horizontal/Vertical wrapping.
  • testString : Test string to get text ascent and text height with default text style.

or

var txt = scene.add.rexDynamicText(x, y, width, height, config);\n

or

var txt = scene.add.rexDynamicText(x, y, config);\n

Add dynamictext from JSON

var txt = scene.make.rexDynamicText({\nx: 0,\ny: 0,\n\n// origin: {x: 0.5, y: 0.5},\n// fill: null,\n\nadd: true\n});\n
"},{"location":"dynamictext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDynamicText extends DynamicText {\nconstructor(scene, x, y, width, height, config)) {\nsuper(scene, x, y, width, height, config));\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyDynamicText(scene, x, y, config);\n
"},{"location":"dynamictext/#clear-content","title":"Clear content","text":"
txt.clearContent();\n
"},{"location":"dynamictext/#text","title":"Text","text":""},{"location":"dynamictext/#append-text","title":"Append text","text":"
txt.appendText(text);\n

or

txt.appendText(text, {\n// bold: false,\n// italic: false,\n// fontSize: '16px',\n// fontFamily: 'Courier',\n// color: '#fff',\n// stroke: '#fff',\n// strokeThickness: 0,\n// shadowColor: null,\n// shadowOffsetX: 0,\n// shadowOffsetY: 0,\n// shadowBlur: 0,\n// backgroundColor: null,\n// backgroundHeight: undefined,\n// backgroundBottomY: undefined,\n// offsetY: 0,\n// offsetY: 0,\n// align: undefined\n}\n);\n

To overwrite some properties of text-style.

Each character will be placed at position (0,0), without rotation. Uses word-wrap method to rearrange position of characters.

"},{"location":"dynamictext/#set-text","title":"Set text","text":"
txt.setText(text);\n

or

txt.setText(text, {\n// bold: false,\n// italic: false,\n// fontSize: '16px',\n// fontFamily: 'Courier',\n// color: '#fff',\n// stroke: '#fff',\n// strokeThickness: 0,\n// shadowColor: null,\n// shadowOffsetX: 0,\n// shadowOffsetY: 0,\n// shadowBlur: 0,\n// backgroundColor: null,\n// backgroundHeight: undefined,\n// backgroundBottomY: undefined,\n// offsetY: 0,\n// offsetY: 0,\n// align: undefined\n}\n);\n
"},{"location":"dynamictext/#insert-text","title":"Insert text","text":"

txt.insertText(index, text);\n
or

txt.insertText(index, text, {\n// bold: false,\n// italic: false,\n// fontSize: '16px',\n// fontFamily: 'Courier',\n// color: '#fff',\n// stroke: '#fff',\n// strokeThickness: 0,\n// shadowColor: null,\n// shadowOffsetX: 0,\n// shadowOffsetY: 0,\n// shadowBlur: 0,\n// backgroundColor: null,\n// backgroundHeight: undefined,\n// backgroundBottomY: undefined,\n// offsetY: 0,\n// offsetY: 0,\n// align: undefined\n}\n);\n
"},{"location":"dynamictext/#remove-text","title":"Remove text","text":"
txt.removeText(index);\n
"},{"location":"dynamictext/#get-text","title":"Get text","text":"
  • Get active characters
    var text = txt.text;\n
    or
    var text = txt.getText();\n
  • Get all characters
    var text = txt.getText(false);\n
"},{"location":"dynamictext/#image","title":"Image","text":""},{"location":"dynamictext/#append-image","title":"Append image","text":"
txt.appendImage(key, frame, {\n// width: ,\n// height: ,\n// scaleX: ,\n// scaleY: ,\n// color: ,\n})\n
  • width : Scaled-width. Aspect-ratio will be kept if no height, or scaleY is set.
  • height : Scaled-height. Aspect-ratio will be kept if no width, or scaleX is set.
  • color : Tint-fill color. Default is undefined.
"},{"location":"dynamictext/#background","title":"Background","text":"
  • Fill style
    txt.setBackgroundColor(color);\n// txt.setBackgroundColor(color, color2, isHorizontalGradient);\n
  • Stroke style
    txt.setBackgroundStroke(color, lineWidth);\n
  • Corner radius
    txt.setBackgroundCornerRadius(radius);\n// txt.setBackgroundCornerRadius(radius, iteration)\n
"},{"location":"dynamictext/#inner-bounds","title":"Inner bounds","text":"
  • Fill style
    txt.setInnerBoundsColor(color);\n// txt.setInnerBoundsColor(color, color2, isHorizontalGradient);\n
  • Stroke style
    txt.setInnerBoundsStroke(color, lineWidth);\n
"},{"location":"dynamictext/#wrap","title":"Wrap","text":"

Control characters :

  • '\\n' : New line
  • '\\f' : Page break
"},{"location":"dynamictext/#horizontal-wrap","title":"Horizontal wrap","text":"
var result = txt.runWordWrap({\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n},\nascent: undefined,\nlineHeight: undefined,\nuseDefaultTextHeight: false,\nmaxLines: undefined,\nwrapWidth: undefined,\nwrapMode: 'word',  // 1|'word'|2|'char'|'character'|3|'mix'\nletterSpacing: 0,\nhAlign: 0,\nvAlign: 0,\n\n\n});\n
  • padding :
    • padding.top, padding.bottom, padding.left, padding.right : Extra space around lines.
  • ascent, lineHeight : Height of first line and remainder lines
    • ascent will set to lineHeight if ascent is undefined but lineHeight is not undefined (backward compatible)
    • Get ascent, lineHeight from default text style and test string, if ascent, lineHeight are both undefined
  • useDefaultTextHeight : If parameter lineHeight is not given,
    • false : Set line height to (total line height / maxLines), if parameter maxLines is larger than 0. Default behavior.
    • true : Set line height to default text height.
  • maxLines : Lines number of this page.
    • 0 : Wrapping whole content.
    • undefined : It will be set if lineHeight and height is given
  • wrapWidth : Width of wrapping. Use inner width if this parameter is undefined.
  • wrapMode :
    • No wrapping if wrapWidth, or inner width is not given.
    • 1, or 'word' : Word wrapping. Default behavior.
    • 2, or 'char', or 'character' : Character wrapping.
    • 3, or 'mix' : Word wrapping for ASCII word, Character wrapping for other (unicode) word.
  • letterSpacing : Space between each character.
  • hAlign : Horizontal alignment.
    • 0, or 'left' : Align to left bound.
    • 1, or 'center' : Align to center.
    • 2, or 'right' : Align to right bound.
    • 3, 'justify', 'justify-left' : If remainder space is less or equal than 25%, then justify children. Else align children to left/top side.
    • 4, 'justify-right' : If remainder space is less or equal than 25%, then justify children. Else align children to right/bottom side.
    • 5, 'justify-cneter' : If remainder space is less or equal than 25%, then justify children. Else align children to center.
  • vAlign : Vertical alignment.
    • 0, or 'top' : Align to top bound.
    • 1, or 'center' : Align to center.
    • 2, or 'bottom' : Align to bottom bound.
"},{"location":"dynamictext/#align","title":"Align","text":"
  • Set vertical align mode
    txt.setVAlign(vAlign);\n
    • vAlign : Vertical alignment.
      • 0, or 'top' : Align to top bound.
      • 1, or 'center' : Align to center.
      • 2, or 'bottom' : Align to bottom bound.
  • Set horizontal align mode
    txt.setHAlign(hAlign);\n
    • hAlign : Horizontal alignment.
      • 0, or 'left' : Align to left bound.
      • 1, or 'center' : Align to center.
      • 2, or 'right' : Align to right bound.
"},{"location":"dynamictext/#test-string","title":"Test string","text":"
txt.setTestString(text);\n
"},{"location":"dynamictext/#vertical-wrap","title":"Vertical wrap","text":"
var result = txt.runVerticalWrap({\npadding: {\ntop: 0,\nleft: 0,\nright: 0,\nbottom: 0\n},\nlineWidth: undefined,\nmaxLines: undefined,\nfixedChildHeight: undefined,\ncharPerLine: undefined,\nwrapHeight: undefined,\nletterSpacing: 0,\nrtl: true,\nhAlign: 0,\nvAlign: 0,\n});\n
  • padding :
    • padding.top, padding.bottom, padding.left, padding.right : Extra space around lines.
  • lineWidth : Line width.
    • undefined : It will be set if maxLines and fixedWidth is given.
  • maxLines : Lines number of this page.
    • 0 : Wrapping whole content.
    • undefined : It will be set if lineWidth and fixedWidth is given.
  • fixedChildHeight : Each character has the same fixed height.
    • undefined : Get fixedChildHeight according to charPerLine parameter. Or use height of each character if fixedChildHeight and charPerLine parameters are undefined.
  • charPerLine : Amount of characters in each line, to get fixedChildHeight.
  • wrapHeight : Height of wrapping
  • letterSpacing : Space between each character.
  • rtl :
    • true : Place lines from right to left.
    • false : Place lines from left to right.
  • hAlign : Horizontal alignment.
    • 0, or 'left' : Align to left bound. Default value if rtl is set to false.
    • 1, or 'center' : Align to center.
    • 2, or 'right' : Align to right bound. Default value if rtl is set to true.
  • vAlign : Vertical alignment.
    • 0, or 'top' : Align to top bound.
    • 1, or 'center' : Align to center.
    • 2, or 'bottom' : Align to bottom bound.
"},{"location":"dynamictext/#result","title":"Result","text":"
{\nchildren: [],\nlines: [],\nisLastPage: false\n}\n
  • children : Character/Image data in this page.
  • lines : Array of line data. A line data contains
    {\nchildren: [],\nwidth: 0,     // Horizontal-wrapping\nheight: 0,    // Vertical-wrapping.        \n}\n
    • children : Character/Image data in this line.
    • width : Width of this line, in result of horizontal-wrapping.
    • height : Height of this line, in result of vertical-wrapping.
  • isLastPage :
    • false : Run txt.runWordWrap(result)/txt.runVerticalWrap(result) to get next page of word-wrapping result.
    • true : No remainder of characters.
"},{"location":"dynamictext/#wrap-next-page","title":"Wrap next page","text":"
var result = txt.runWordWrap(prevResult);\n
  • prevResult : Result of previous word-wraping.
  • result : Current result of word-wraping.
"},{"location":"dynamictext/#default-configuration-of-wrapping","title":"Default configuration of wrapping","text":"
txt.setWrapConfig(config);\n
  • config : Default configuration Horizontal/Vertical wrapping.
"},{"location":"dynamictext/#scroll-content","title":"Scroll content","text":"

Scroll content by setting textOX, textOY members

  • Set
    txt.setTextOXY(x, y).updateTexture();    // txt.setTextOX(x).updateTexture();\n// txt.setTextOY(x).updateTexture(); \n
    or
    txt.addTextOXY(incX, incY).updateTexture(); // txt.addTextOX(incX).updateTexture(); \n// txt.addTextOY(incY).updateTexture(); \n
    or
    txt.textOX = x;\ntxt.textOY = y;\ntxt.updateTexture();\n
  • Get
    var ox = txt.textOX;\nvar oy = txt.textOY;\n
"},{"location":"dynamictext/#child","title":"Child","text":""},{"location":"dynamictext/#general-properties","title":"General properties","text":"
  • Visible :
    • Get
      var visible = child.visible;\n
    • Set
      child.setVisible();\n// child.visible = true;\n
      or
      child.setVisible(false);  // Set to invisible\n// child.visible = false;\n
  • Alpha
    • Get
      var alpha = child.alpha;\n
    • Set
      child.setAlpha(alpha);\n// child.alpha = alpha;\n
  • Position :
    • Get
      var x = child.x;\nvar y = child.y;\n
    • Set
      child.setPosition(x, y);\n// child.x = x;\n// child.y = y;\n
  • Angle :
    • Get
      var degrees = child.angle;\n// var radians = child.rotation;\n
    • Set
      child.setAngle(degrees);\nchild.setRotation(radians);\n// child.angle = degrees;\n// child.rotation = radians;\n
  • Scale
    • Get
      var scaleX = child.scaleX;\nvar scaleY = child.scaleY;\n
    • Set
      child.setScale(scaleX, scaleY);\n// child.scaleX = scaleX;\n// child.scaleY = scaleY;\n
  • Draw callbacks
    • Set
      child.setDrawBelowCallback(callback);\nchild.setDrawAboveCallback(callback);\n
      • callback :
        function(child) {\nvar text = child.text;                var context = child.context;\n// ...\n}\n
  • World position
    var worldXY = child.getWorldPosition();\n// out = child.getWorldPosition(out);\n
    or
    var worldXY = txt.getCharWorldPosition(char);\n// out = txt.getCharWorldPosition(char, out);\n
"},{"location":"dynamictext/#character","title":"Character","text":""},{"location":"dynamictext/#text-style","title":"Text-style","text":"
  • Get
    var bold = char.style.bold;\nvar italic = char.style.italic;\nvar fontSize = char.style.fontSize;\nvar fontFamily = char.style.fontFamily;\nvar color = char.style.color;\nvar stroke = char.style.stroke;\nvar strokeThickness = char.style.strokeThickness;\nvar shaodwColor = char.style.shadowColor;\nvar shadowBlur = char.style.shadowBlur;\nvar shadowOffsetX = char.style.shadowOffsetX;\nvar shadowOffsetY = char.style.shadowOffsetY;\nvar backgroundColor = char.style.backgroundColor;\nvar backgroundHeight = char.style.backgroundHeight;\nvar backgroundBottomY = char.style.backgroundBottomY;\nvar xOffset = char.style.x;\nvar yOffset = char.style.y;\n
  • Set
    char.modifyStyle({\n// bold: false,\n// italic: false,\n// fontSize: '16px',\n// fontFamily: 'Courier',\n// color: '#fff',\n// stroke: '#fff',\n// strokeThickness: 0,\n// shaodwColor: null,\n// shadowBlur: 0,\n// shadowOffsetX: 0,\n// shadowOffsetY: 0,\n// backgroundColor: null,\n// backgroundHeight: undefined,\n// backgroundBottomY: undefined,\n// offsetX: 0,\n// offsetY: 0\n})\n
    or
    char.setBold();\n// char.setBold(false);\n
    char.setItalic();\n// char.setItalic(false);\n
    char.setFontSize(fontSize); // number, string\n
    char.setFontFamily(fontFamily);\n
    char.setColor(color); // number, string\n// char.setColor(); // No filling color\n
    char.setStrokeStyle(color, thickness);\n// char.setStrokeStyle();  // No stroke\n
    char.setShadowColor(color);\n// char.setShadowColor();  // No shadow\n
    char.setShadowOffset(offsetX, offsetY);\n
    char.setShadowBlur(blur);\n
    char.setBackgroundColor(color);\n// char.setBackgroundColor();  // No shadow\n
    char.setOffsetX(offsetX);\nchar.setOffsetY(offsetY);\n
"},{"location":"dynamictext/#image_1","title":"Image","text":"
  • Size
    • Get
      var width = image.width;\nvar height = image.height;\n
    • Set
      image.setWidth(width);\n// image.setWidth(width, true);  // Resize and keep aspect- ratio\nimage.setHeight(height);\n// image.setHeight(height, true);  // Resize and keep aspect- ratio\n
"},{"location":"dynamictext/#for-each-child","title":"For each child","text":"
  • Any child
    • For each active child
      txt.forEachChild(function(child, childIndex){\n}, scope)\n
    • For each character child
      txt.forEachChild(function(child, childIndex){\n}, scope, false);\n
  • Renderable child
    • For each active renderable child
      txt.forEachRenderableChild(function(child, charIndex){\n}, scope)\n
    • For each renderable child
      txt.forEachRenderableChild(function(child, charIndex){\n}, scope, false);\n
  • Character child
    • For each active character child
      txt.forEachCharChild(function(child, charIndex){\n}, scope)\n
    • For each character child
      txt.forEachCharChild(function(child, charIndex){\n}, scope, false);\n
"},{"location":"dynamictext/#get-children","title":"Get children","text":"
  • Get all children
    var children = txt.getChildren();\n
  • Get last appended children
    var children = txt.getLastAppendedChildren();\n
  • Get active children, after wrapping
    var children = txt.getActiveChildren();\n
"},{"location":"dynamictext/#get-character-children","title":"Get character children","text":"
  • Get active character children
    var children = txt.getCharChildren();\n
  • Get all character children
    var children = txt.getCharChildren(false);\n
  • Get character child by character index
    var child = txt.getCharChild(charIndex);\n
"},{"location":"dynamictext/#move-child","title":"Move child","text":"
  • Move child to fist
    txt.moveChildToFist(child);\n
  • Move child to last
    txt.moveChildToLast(child);\n
  • Move child up
    txt.movechildUp(child);\n
  • Move child to down
    txt.movechildDown(child);\n
  • Move child above another child
    txt.movechildAbove(child, baseChild);\n
  • Move child below another child
    txt.movechildBelow(child, baseChild);\n
"},{"location":"dynamictext/#size","title":"Size","text":"
  • Resize canvas size
    txt.setCanvasSize(width, height)\n
  • Reisze text wrapping size and canvas size.
    txt.setSize(width, height);\n
    or
    txt.setFixedSize(width, height);\n
  • Resize to minimun size to show all visible characters.
    txt.setToMinSize();\n
"},{"location":"dynamictext/#input-events-of-child","title":"Input events of child","text":"
  • Enable input events of child on config of constructor, or via method
    txt.setChildrenInteractiveEnable();\n
  • Pointer down/up on child
    txt.on('child.pointerdown', function(child, pointer, localX, localY, event) {        })\n
    txt.on('child.pointerup', function(child, pointer, localX, localY, event) {        })\n
    • child : Any Character or Image child
  • Pointer over/out on child
    txt.on('child.pointerover', function(child, pointer, localX, localY, event) {        })\n
    txt.on('child.pointerout', function(child, pointer, localX, localY, event) {        })\n
    • child : Any Character or Image child
"},{"location":"dynamictext/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"dynamictext/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"dynamictext/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"dynamictext/#compare-with-other-kinds-of-text-game-object","title":"Compare with other kinds of text game object","text":"
  • Built-in text:
    • Single color per game object.
    • Draw content line by line.
    • Best render performance.
  • BBCode text:
    • Multiple colors, multiple font size per gaem object.
    • Draw content segment by segment.
    • Slower than built-in text game object.
  • Dynamic text:
    • Multiple colors, multiple font size per gaem object.
    • Draw content character by character.
    • Slower than bbcode text game object.
"},{"location":"ease-function/","title":"Ease","text":""},{"location":"ease-function/#introduction","title":"Introduction","text":"

Ease functions, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"ease-function/#usage","title":"Usage","text":""},{"location":"ease-function/#ease-functions","title":"Ease functions","text":"
  • Linear : Phaser.Math.Easing.Linear
  • Quadratic, Power1
    • Quadratic ease-out : Phaser.Math.Easing.Quadratic.Out
    • Quadratic ease-in : Phaser.Math.Easing.Quadratic.In
    • Quadratic ease-in/out : Phaser.Math.Easing.Quadratic.InOut
  • Cubic, Power2
    • Cubic ease-out : Phaser.Math.Easing.Cubic.Out
    • Cubic ease-in : Phaser.Math.Easing.Cubic.In
    • Cubic ease-in/out : Phaser.Math.Easing.Cubic.InOut
  • Quartic, Power3
    • Quartic ease-out : Phaser.Math.Easing.Quartic.Out
    • Quartic ease-in : Phaser.Math.Easing.Quartic.In
    • Quartic ease-in/out : Phaser.Math.Easing.Quartic.InOut
  • Quintic, Power4
    • Quintic ease-out : Phaser.Math.Easing.Quintic.Out
    • Quintic ease-in : Phaser.Math.Easing.Quintic.In
    • Quintic ease-in/out : Phaser.Math.Easing.Quintic.InOut
  • Sinusoidal
    • Sinusoidal ease-out : Phaser.Math.Easing.Sine.Out
    • Sinusoidal ease-in : Phaser.Math.Easing.Sine.In
    • Sinusoidal ease-in/out : Phaser.Math.Easing.Sine.InOut
  • Exponential
    • Exponential ease-out : Phaser.Math.Easing.Expo.Out
    • Exponential ease-in : Phaser.Math.Easing.Expo.In
    • Exponential ease-in/out : Phaser.Math.Easing.Expo.InOut
  • Circular
    • Circular ease-out : Phaser.Math.Easing.Circular.Out
    • Circular ease-in : Phaser.Math.Easing.Circular.In
    • Circular ease-in/out : Phaser.Math.Easing.Circular.InOut
  • Elastic
    • Elastic ease-out : Phaser.Math.Easing.Elastic.Out
    • Elastic ease-in : Phaser.Math.Easing.Elastic.In
    • Elastic ease-in/out : Phaser.Math.Easing.Elastic.InOut
  • Bounce
    • Bounce ease-out : Phaser.Math.Easing.Bounce.Out
    • Bounce ease-in : Phaser.Math.Easing.Bounce.In
    • Bounce ease-in/out : Phaser.Math.Easing.Bounce.InOut
  • Back
    • Back ease-out : Phaser.Math.Easing.Back.Out
    • Back ease-in : Phaser.Math.Easing.Back.In
    • Back ease-in/out : Phaser.Math.Easing.Back.InOut
  • Stepped : Phaser.Math.Easing.Stepped(v, step)
"},{"location":"ease-function/#get-ease-function-via-string","title":"Get ease function via string","text":"
var easeFunction = Phaser.Tweens.Builders.GetEaseFunction(ease);\n// var easeFunction = Phaser.Tweens.Builders.GetEaseFunction(ease, easeParams);\n
  • ease :
    • A string :
      • Power0 : Linear
      • Power1 : Quadratic.Out
      • Power2 : Cubic.Out
      • Power3 : Quartic.Out
      • Power4 : Quintic.Out
      • Linear
      • Quad : Quadratic.Out
      • Cubic : Cubic.Out
      • Quart : Quartic.Out
      • Quint : Quintic.Out
      • Sine : Sine.Out
      • Expo : Expo.Out
      • Circ : Circular.Out
      • Elastic : Elastic.Out
      • Back : Back.Out
      • Bounce : Bounce.Out
      • Stepped
      • Quad.easeIn
      • Cubic.easeIn
      • Quart.easeIn
      • Quint.easeIn
      • Sine.easeIn
      • Expo.easeIn
      • Circ.easeIn
      • Back.easeIn
      • Bounce.easeIn
      • Quad.easeOut
      • Cubic.easeOut
      • Quart.easeOut
      • Quint.easeOut
      • Sine.easeOut
      • Expo.easeOut
      • Circ.easeOut
      • Back.easeOut
      • Bounce.easeOut
      • Quad.easeInOut
      • Cubic.easeInOut
      • Quart.easeInOut
      • Quint.easeInOut
      • Sine.easeInOut
      • Expo.easeInOut
      • Circ.easeInOut
      • Back.easeInOut
      • Bounce.easeInOut
    • A custom function
      function(v) {\nreturn v;\n}\n
      function(v, param0, param1, ...) {\nreturn v;\n}\n
      • v : 0 ~ 1
"},{"location":"ease-function/#get-result","title":"Get result","text":"
var result = easeFunction(t);\n
  • t : 0 ~ 1
"},{"location":"easedata/","title":"Ease-data","text":""},{"location":"easedata/#introduction","title":"Introduction","text":"

Easing data value of game object's data-manager.

  • Author: Rex
  • Method only
"},{"location":"easedata/#usage","title":"Usage","text":"

Sample code

"},{"location":"easedata/#install-plugin","title":"Install plugin","text":""},{"location":"easedata/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexeasedataplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexeasedataplugin.min.js', true);\n
  • Add ease-data behavior
    var easedata = scene.plugins.get('rexeasedataplugin').add(gameObject);\n
"},{"location":"easedata/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import EaseDataPlugin from 'phaser3-rex-plugins/plugins/easedata-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexEaseData',\nplugin: EaseDataPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add ease-data behavior
    var easedata = scene.plugins.get('rexEaseData').add(gameObject);\n
"},{"location":"easedata/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import { EaseData } from 'phaser3-rex-plugins/plugins/easedata.js';\n
  • EaseData-out-destroy
    var easedata = new EaseData(gameObject);\n
"},{"location":"easedata/#create-instance","title":"Create instance","text":"
var easedata = scene.plugins.get('rexEaseData').add(gameObject);\n
"},{"location":"easedata/#ease-data","title":"Ease data","text":"
  • Start
    easedata.easeTo(key, value, duration);\n// easedata.easeTo(key, value, duration, ease);\n
    or
    easedata.easeTo({\nkey:key,\nvalue:value,\nduration:1000,\nease:'Linear'\n});\n
    or
    easedata.easeTo({\nkey:key,\nvalue:value,\nspeed: 10,    // value changing rate, per second\nease:'Linear'\n});\n
  • Stop
    easedata.stopEase(key);           // Set to end value\n// easedata.stopEase(key, false); // Stop at current value\n
    or
    easedata.stopAll();           // Set to end value\n// easedata.stopAll(false);   // Stop at current value\n
"},{"location":"easedata/#events","title":"Events","text":"
  • Easing complete
    easedata.on('complete-' + key, function(gameObject, easedata){\n\n}, scope);\n
    easedata.on('complete', function(key, gameObject, easedata){\n\n}, scope);\n
"},{"location":"easemove/","title":"Ease-move","text":""},{"location":"easemove/#introduction","title":"Introduction","text":"

Ease-move game object.

  • Author: Rex
  • Method only
"},{"location":"easemove/#usage","title":"Usage","text":"

Sample code

"},{"location":"easemove/#install-plugin","title":"Install plugin","text":""},{"location":"easemove/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexeasemoveplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexeasemoveplugin.min.js', true);\n
  • Ease-move to/from
    var easemove = scene.plugins.get('rexeasemoveplugin').moveTo(gameObject, duration, x, y, ease);\nvar easemove = scene.plugins.get('rexeasemoveplugin').moveFrom(gameObject, duration, x, y, ease);\n
"},{"location":"easemove/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import EaseMovePlugin from 'phaser3-rex-plugins/plugins/easemove-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexEaseMove',\nplugin: EaseMovePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Ease-move to/from
    var easemove = scene.plugins.get('rexEaseMove').moveTo(gameObject, duration, x, y, ease);\nvar easemove = scene.plugins.get('rexEaseMove').moveFrom(gameObject, duration, x, y, ease);\n
"},{"location":"easemove/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import { EaseMoveTo, EaseMoveFrom } from 'phaser3-rex-plugins/plugins/easemove.js';\n
  • EaseMove-out-destroy
    var easemove = EaseMoveTo(gameObject, duration, x, y, ease);\nvar easemove = EaseMoveFrom(gameObject, duration, x, y, ease);\n
"},{"location":"easemove/#move-to","title":"Move to","text":"
var easemove = scene.plugins.get('rexEaseMove').moveTo(gameObject, duration, x, y);\n// var easemove = scene.plugins.get('rexEaseMove').moveTo(gameObject, duration, x, y, ease);\n// easemove = scene.plugins.get('rexEaseMove').moveTo(gameObject, duration, x, y, ease, easemove);\n
  • x, y : End position.
    • Number : End position x/y.
    • String(+=300) : Related position of current position x/y.
    • undefined : Don't move along x/y axis.
  • ease : 'Linear', 'Cubic', 'Elastic', 'Bounce', 'Back' ...
  • easemove : Ease-move behavior.
"},{"location":"easemove/#move-from","title":"Move from","text":"
var easemove = scene.plugins.get('rexEaseMove').moveFrom(gameObject, duration, x, y);\n// var easemove = scene.plugins.get('rexEaseMove').moveFrom(gameObject, duration, x, y, ease);\n// easemove = scene.plugins.get('rexEaseMove').moveFrom(gameObject, duration, x, y, ease, easemove);\n
  • x, y : Start position.
    • Number : Start position x/y.
    • String(-=300) : Related position of current position x/y.
    • undefined : Don't move along x/y axis.
  • ease : 'Linear', 'Cubic', 'Elastic', 'Bounce', 'Back' ...
  • easemove : Ease-move behavior.
"},{"location":"easemove/#events","title":"Events","text":"

See Events of tween task

  • Move completes or is stopped.
    easemove.on('complete', function(gameObject, easemove){\n\n}, scope);\n
"},{"location":"easemove/#inject-methods","title":"Inject methods","text":"
  • Inject methods into game object
    scene.plugins.get('rexEaseMove').injectMethods(gameObject);\n
  • Inject methods into class of game object
    scene.plugins.get('rexEaseMove').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexEaseMove').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into class of game object
    scene.plugins.get('rexEaseMove').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexEaseMove').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into root class of game object
    scene.plugins.get('rexEaseMove').injectMethodsToRootClass(e);\n// scene.plugins.get('rexEaseMove').injectMethods(Phaser.GameObjects.GameObject.prototype);\n
"},{"location":"easemove/#injected-methods","title":"Injected methods","text":"
  • Move from
    gameObject.moveFrom(duration, x, y);\n// gameObject.moveFrom(duration, x, y, ease);\n// gameObject.moveFrom({x, y, duration, ease});\n// gameObject.moveFrom({x, y, speed, ease});\n
    or
    gameObject\n.moveFromPromise(duration, x, y, ease)\n// .moveFromPromise({x, y, duration, ease})\n// .moveFromPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
    • x, y : Start position.
      • Number : Start position x/y.
      • String(+=300) : Related position of current position x/y.
      • undefined : Current position x/y.
    • speed : Get duration according to speed and distance between current gameObject position to {x, y}
    • ease : 'Linear', 'Cubic', 'Elastic', 'Bounce', 'Back' ...
  • Move-from destroy
    gameObject.moveFromDestroy(duration, x, y);\n// gameObject.moveFrom(duration, x, y, ease);\n// gameObject.moveFrom({x, y, duration, ease});\n// gameObject.moveFrom({x, y, speed, ease});\n
    or
    gameObject\n.moveFromDestroyPromise(duration, x, y, ease)\n// .moveFromDestroyPromise({x, y, duration, ease})\n// .moveFromDestroyPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
  • Move to
    gameObject.moveTo(duration, x, y);\n// gameObject.moveTo(duration, x, y, ease);\n// gameObject.moveTo({x, y, duration, ease});\n// gameObject.moveTo({x, y, speed, ease});\n
    or
    gameObject\n.moveToPromise(duration, x, y, ease)\n// .moveToPromise({x, y, duration, ease})\n// .moveToPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
    • x, y : End position.
      • Number : End position x/y.
      • String(+=300) : Related position of current position x/y.
      • undefined : Current position x/y.
    • speed : Get duration according to speed and distance between current gameObject position to {x, y}
    • ease : 'Linear', 'Cubic', 'Elastic', 'Bounce', 'Back' ...
  • Move-to destroy
    gameObject.moveToDestroy(duration, x, y);\n// gameObject.moveTo(duration, x, y, ease);\n// gameObject.moveTo({x, y, duration, ease});\n// gameObject.moveTo({x, y, speed, ease});\n
    or
    gameObject\n.moveToDestroyPromise(duration, x, y, ease)\n// .moveToDestroyPromise({x, y, duration, ease})\n// .moveToDestroyPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
  • Move-stop
    gameObject.moveStop();\n// gameObject.moveStop(true);  // Set to end position\n
  • Events
    • Move-from complete
      gameObject.on('movefrom.complete', function(gameObject) { });\n
    • Move-to complete
      gameObject.on('moveto.complete', function(gameObject) { });\n
"},{"location":"effect-properties/","title":"Effect properties","text":""},{"location":"effect-properties/#introduction","title":"Introduction","text":"

Attach properties to a game object or camera, to add/remove/control builtin preFX or postFX effects.

  • Author: Rex
  • Method only
  • Pre-fx, and Post-fx shader effects

WebGL only

Only work in WebGL render mode.

"},{"location":"effect-properties/#live-demos","title":"Live demos","text":"
  • Color effects
  • Reveal
  • Interactive
  • Camera
"},{"location":"effect-properties/#usage","title":"Usage","text":"

Sample code

"},{"location":"effect-properties/#install-plugin","title":"Install plugin","text":""},{"location":"effect-properties/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexeffectpropertiesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexeffectpropertiesplugin.min.js', true);\n
  • Attach properties to a game object/camera.
    scene.plugins.get('rexeffectpropertiesplugin').add(gameObject);\n
    scene.plugins.get('rexeffectpropertiesplugin').add(camera);\n
"},{"location":"effect-properties/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import EffectPropertiesPlugin from 'phaser3-rex-plugins/plugins/effectproperties-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexEffectProperties',\nplugin: EffectPropertiesPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Attach properties to a game object/camera.
    scene.plugins.get('rexEffectProperties').add(gameObject);\n
    scene.plugins.get('rexEffectProperties').add(camera);\n
"},{"location":"effect-properties/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import AddEffectPropertiesProperties from 'phaser3-rex-plugins/plugins/effectproperties.js';\n
  • Attach properties to a game object/camera.
    AddEffectPropertiesProperties(gameObject);\n
    AddEffectPropertiesProperties(camera);\n
"},{"location":"effect-properties/#attach-properties","title":"Attach properties","text":"

Supported effects are barrel, blackWhite, bloom, blur, bokeh, brightness, brown, circle, contrast, desaturate, desaturateLuminance, displacement, glow, gradient, grayscale, hue, kodachrome, lsd, negative, pixelate, polaroid, reveal, saturate, sepia, shadow, shiftToBGR, shine, technicolor, tiltShift, vignette, vintagePinhole, wipe.

  • Attatch properties of all effects to a game object/camera.
    scene.plugins.get('rexEffectProperties').add(gameObject);\n
    scene.plugins.get('rexEffectProperties').add(camera);\n
  • Attatch properties of some preFX/postFX effects to a game object/camera.
    scene.plugins.get('rexEffectProperties').add(gameObject, {\nbarrel: true,\nblackWhite: true,\nbloom: true,\nblur: true,\nbokeh: true,\nbrightness: true,\nbrown: true,\ncircle: true,\ncontrast: true,\ndesaturate: true,\ndesaturateLuminance: true,\ndisplacement: true,\nglow: true,\ngradient: true,\ngrayscale: true,\nhue: true,\nkodachrome: true,\nlsd: true,\nnegative: true,\npixelate: true,\npolaroid: true,\nreveal: true,\nsaturate: true,\nsepia: true,\nshadow: true,\nshiftToBGR: true,\nshine: true,\ntechnicolor: true,\ntiltShift: true,\nvignette: true,\nvintagePinhole: true,\nwipe: true,\n});\n
    or
    scene.plugins.get('rexEffectProperties').add(gameObject, [\n'barrel', 'blackWhite', 'bloom', 'blur', 'bokeh', 'brightness', 'brown',\n'circle', 'contrast',\n'desaturate', 'desaturateLuminance', 'displacement',\n'glow', 'gradient', 'grayscale',\n'hue',\n'kodachrome',\n'lsd',\n'negative',\n'pixelate', 'polaroid',\n'reveal',\n'saturate', 'sepia', 'shadow', 'shiftToBGR', 'shine',\n'technicolor', 'tiltShift',\n'vignette', 'vintagePinhole',\n'wipe'\n]);\n
    or
    scene.plugins.get('rexEffectProperties').add(gameObject, effectName);\n
    • A plain object with effect names.
    • A list of effect name string.
    • A effect name string.
"},{"location":"effect-properties/#effect-properties","title":"Effect properties","text":"

Will try to create preFX effect if gameObject has preFX, otherwise, try to create postFX effect.

"},{"location":"effect-properties/#barrel","title":"Barrel","text":"
  • barrel :
    • A number : Enable this effect and set intensity of barrel (1: origin).
    • null : Remove this effect
"},{"location":"effect-properties/#blackwhite","title":"BlackWhite","text":"
  • blackWhite :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#bloom","title":"Bloom","text":"
  • bloomColor :
    • A number : Enable this effect and set color of bloom (0xffffff).
    • null : Remove this effect
  • bloomOffsetX, bloomOffsetY, bloomBlurStrength, bloomStrength, bloomSteps :
    • A number
"},{"location":"effect-properties/#blur","title":"Blur","text":"
  • blurColor :
    • A number : Enable this effect and set color of blur (0xffffff).
    • null : Remove this effect
  • blurQuality, blurX, blurY, blurStrength, blurSteps :
    • A number
"},{"location":"effect-properties/#bokeh","title":"Bokeh","text":"
  • bokehRadius :
    • A number : Enable this effect and set radius of bokeh (0~1).
    • null : Remove this effect
  • bokehAmount, bokehContrast :
    • A number
"},{"location":"effect-properties/#brightness","title":"Brightness","text":"
  • brightness :
    • A number : Enable this effect and set brightness (0~1).
    • null : Remove this effect
"},{"location":"effect-properties/#brown","title":"Brown","text":"
  • brown :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#circle","title":"Circle","text":"
  • circleColor :
    • A number : Enable this effect and set color of circle (0xffffff).
    • null : Remove this effect
  • circleThickness, circleBackgroundColor, circleBackgroundAlpha, circleScale, circleFeather :
    • A number
"},{"location":"effect-properties/#contrast","title":"Contrast","text":"
  • contrast :
    • A number : Enable this effect and set contrast (0~1).
    • null : Remove this effect
"},{"location":"effect-properties/#desaturate","title":"Desaturate","text":"
  • desaturate :
    • A number : Enable this effect and set desaturate (0~1).
    • null : Remove this effect
"},{"location":"effect-properties/#desaturateluminance","title":"DesaturateLuminance","text":"
  • desaturateLuminance :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#displacement","title":"Displacement","text":"
  • displacementKey :
    • A string : Enable this effect and set displacement reference texture.
    • null : Remove this effect
  • displacementX, displacementY :
    • A number
"},{"location":"effect-properties/#glow","title":"Glow","text":"
  • glowColor :
    • A number : Enable this effect and set color of glow (0xffffff).
    • null : Remove this effect
  • glowOuterStrength, glowInnerStrength :
    • A number
"},{"location":"effect-properties/#gradient","title":"Gradient","text":"
  • gradientColor :
    • [number, number] : Enable this effect and set gradient color1 and gradient color2 (0xffffff).
    • null : Remove this effect
  • gradientAlpha, gradientFromX, gradientFromY, gradientToX, gradientToY, gradientSize :
    • A number
"},{"location":"effect-properties/#grayscale","title":"Grayscale","text":"
  • grayscale :
    • A number : Enable this effect and set intensity of grayscale (0~1).
    • null : Remove this effect
"},{"location":"effect-properties/#hue","title":"Hue","text":"
  • hue :
    • A number : Enable this effect and set hue rotation, in degrees.
    • null : Remove this effect
"},{"location":"effect-properties/#kodachrome","title":"Kodachrome","text":"
  • kodachrome :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#lsd","title":"Lsd","text":"
  • lsd :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#negative","title":"Negative","text":"
  • negative :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#pixelate","title":"Pixelate","text":"
  • pixelate :
    • A number : Enable this effect and set size of pixelate, in pixels.
    • null : Remove this effect
"},{"location":"effect-properties/#polaroid","title":"Polaroid","text":"
  • polaroid :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#reveal","title":"Reveal","text":"
  • revealLeft, revealRight, revealUp, or revealDown :
    • A number : Enable this effect with specific reveal direction and set progress (0~1).
    • null : Remove this effect
  • revealWidth :
    • A number
"},{"location":"effect-properties/#saturate","title":"Saturate","text":"
  • saturate :
    • A number : Enable this effect and set saturate (0~1).
    • null : Remove this effect
"},{"location":"effect-properties/#sepia","title":"Sepia","text":"
  • sepia :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#shadow","title":"Shadow","text":"
  • shadowColor :
    • A number : Enable this effect and set color of shadow (0xffffff).
    • null : Remove this effect
  • shadowX, shadowY, shadowDecay, shadowPower, shadowSamples, shadowIntensity :
    • A number
"},{"location":"effect-properties/#shifttobgr","title":"ShiftToBGR","text":"
  • shiftToBGR :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#shine","title":"Shine","text":"
  • shineSpeed :
    • A number : Enable this effect and set speed of shine, in seconds.
    • null : Remove this effect
  • shineLineWidth, shineGradient :
    • A number
"},{"location":"effect-properties/#technicolor","title":"Technicolor","text":"
  • technicolor :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#tiltshift","title":"TiltShift","text":"
  • tiltShiftRadius :
    • A number : Enable this effect and set radius of tiltShift (0~1).
    • null : Remove this effect
  • tiltShiftAmount, tiltShiftContrast, tiltShiftBlurX, tiltShiftBlurY, tiltShiftStrength :
    • A number
"},{"location":"effect-properties/#vignette","title":"Vignette","text":"
  • vignetteRadius :
    • A number : Enable this effect and set radius of vignette (0~1).
    • null : Remove this effect
  • vignetteX, vignetteY, vignetteStrength :
    • A number
"},{"location":"effect-properties/#vintagepinhole","title":"VintagePinhole","text":"
  • vintagePinhole :
    • true, or 1 : Enable this effect.
    • null : Remove this effect
"},{"location":"effect-properties/#wipe","title":"Wipe","text":"
  • wipeLeft, wipeRight, wipeUp, or wipeDown :
    • A number : Enable this effect with specific wipe direction and set progress (0~1).
    • null : Remove this effect
  • wipeWidth :
    • A number
"},{"location":"effect-properties/#clear-all-effects","title":"Clear all effects","text":"
gameObject.clearAllEffects();\n
"},{"location":"effectlayer-outline/","title":"Effectlayer outline","text":""},{"location":"effectlayer-outline/#introduction","title":"Introduction","text":"

Draw outline of target game objects.

  • Author: Rex
  • Game object
"},{"location":"effectlayer-outline/#live-demos","title":"Live demos","text":"
  • Outline
"},{"location":"effectlayer-outline/#usage","title":"Usage","text":"

Sample code

"},{"location":"effectlayer-outline/#install-plugin","title":"Install plugin","text":""},{"location":"effectlayer-outline/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexoutlineeffectlayerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexoutlineeffectlayerplugin.min.js', true);\n
  • Add outline effect layer object
    var effectLayer = scene.add.rexOutlineEffectLayer(config);\n
"},{"location":"effectlayer-outline/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import OutlineEffectLayerPlugin from 'phaser3-rex-plugins/plugins/outlineeffectlayer-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexOutlineEffectLayerPlugin',\nplugin: OutlineEffectLayerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add outline effect layer object
    var effectLayer = scene.add.rexOutlineEffectLayer(config);\n
"},{"location":"effectlayer-outline/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import OutlineEffectLayer from 'phaser3-rex-plugins/plugins/outlineeffectlayer.js';\n
  • Add outline effect layer object
    var effectLayer = new OutlineEffectLayer(scene, config);\nscene.add.existing(effectLayer);\n
"},{"location":"effectlayer-outline/#create-instance","title":"Create instance","text":"
var effectLayer = scene.add.rexOutlineEffectLayer({\n// knockout: false,\n// thickness: 3,\n// outlineColor: 0x000000\n});\n
  • knockout :
    • true : Draw outline only.
    • false : Draw source texture and outline both.
  • thickness : Thickness of outline.
  • outlineColor : Color of outline.
"},{"location":"effectlayer-outline/#custom-class","title":"Custom class","text":"
  • Define class
    class MyOutlineEffectLayer extends OutlineEffectLayer {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var effectLayer = new MyOutlineEffectLayer(scene, config);\n
"},{"location":"effectlayer-outline/#thickness","title":"Thickness","text":"
  • Get
    var thickness = effectLayer.thickness;\n
  • Set
    effectLayer.thickness = thickness;\n// effectLayer.thickness += value;\n
    or
    effectLayer.setThickness(value);\n
"},{"location":"effectlayer-outline/#outline-color","title":"Outline color","text":"
  • Get
    var color = effectLayer.outlineColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    effectLayer.setOutlineColor(value);\n
    effectLayer.outlineColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"effectlayer-outline/#target-game-objects","title":"Target game objects","text":"

Draw outline of added target game objects.

  • Add
    effectLayer.add(gameObject);\n
  • Remove
    effectLayer.remove(gameObject);\n
  • Clear
    effectLayer.clear();\n
  • Contains
    var hasGameObject = effectLayer.contains(gameObject);\n
"},{"location":"effectlayer-outline/#limitation","title":"Limitation","text":"
  • Can't support if camera.zoom is less then 1

  • Can't support if camera.startFollow(gameObject), i.e. please scroll camera before target game objects draw on effect layer game object.

"},{"location":"eightdirection/","title":"8 direction","text":""},{"location":"eightdirection/#introduction","title":"Introduction","text":"

Move game object by cursor keys, with a constant speed.

  • Author: Rex
  • Arcade behavior of game object
"},{"location":"eightdirection/#live-demos","title":"Live demos","text":"
  • Virtual-joyStick + Eight-direction
"},{"location":"eightdirection/#usage","title":"Usage","text":"

Sample code

"},{"location":"eightdirection/#install-plugin","title":"Install plugin","text":""},{"location":"eightdirection/#load-minify-file","title":"Load minify file","text":"
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexeightdirectionplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexeightdirectionplugin.min.js', true);\n
  • Add eight-direction behavior
    var eightDirection = scene.plugins.get('rexeightdirectionplugin').add(gameObject, config);\n
"},{"location":"eightdirection/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine and install plugin in configuration of game
    import EightDirectionPlugin from 'phaser3-rex-plugins/plugins/eightdirection-plugin.js';\nvar config = {\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexEightDirection',\nplugin: EightDirectionPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add eight-direction behavior
    var eightDirection = scene.plugins.get('rexEightDirection').add(gameObject, config);\n
"},{"location":"eightdirection/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Import class
    import EightDirection from 'phaser3-rex-plugins/plugins/eightdirection.js';\n
  • Add eight-direction behavior
    var eightDirection = new EightDirection(gameObject, config);\n
"},{"location":"eightdirection/#create-instance","title":"Create instance","text":"
var eightDirection = scene.plugins.get('rexEightDirection').add(gameObject, {\nspeed: 200,\n// dir: '8dir',     // 0|'up&down'|1|'left&right'|2|'4dir'|3|'8dir'\n// rotateToDirection: false,\n// wrap: false,\n// padding: 0,\n// enable: true,\n// cursorKeys: scene.input.keyboard.createCursorKeys()\n});\n
  • speed : moving speed, pixels in second.
  • dir :
    • 'up&down', or 0 :Aaccept up or down cursor keys only.
    • 'left&right', or 1 : Aaccept left or right cursor keys only.
    • '4dir', or 2 : Aaccept up, down, left or right cursor keys.
    • '8dir', or 3 : Aaccept up, up-left, up-right, down, down-left, down-right, left, or right cursor keys.
  • rotateToDirection : Set true to change angle towards moving direction.
  • Wrap
    • wrap : Set true to enable wrap mode. Default value is false.
    • padding
  • enable : set false to disable moving.
  • cursorKeys : CursorKey object, using keyboard's cursorKeys by default.
"},{"location":"eightdirection/#set-speed","title":"Set speed","text":"
eightDirection.setSpeed(speed);\n// eightDirection.speed = speed;\n
"},{"location":"eightdirection/#set-rotate-to-direction","title":"Set rotate-to-direction","text":"
eightDirection.setRotateToDirection(rotateToDirection);\n
  • rotateToDirection : Set true to change angle towards moving direction
"},{"location":"eightdirection/#set-direction-mode","title":"Set direction mode","text":"
eightDirection.setDirMode(dir);\n
  • dir :
    • 'up&down', or 0 :Aaccept up or down cursor keys only.
    • 'left&right', or 1 : Aaccept left or right cursor keys only.
    • '4dir', or 2 : Aaccept up, down, left or right cursor keys.
    • '8dir', or 3 : Aaccept up, up-left, up-right, down, down-left, down-right, left, or right cursor keys.
"},{"location":"eightdirection/#set-wrap-mode","title":"Set wrap mode","text":"
ship.setWrapMode(wrap, padding);\n
  • wrap : Set true to enable wrap mode.
"},{"location":"eventemitter3/","title":"Event emitter","text":""},{"location":"eventemitter3/#introduction","title":"Introduction","text":"

Event emitter.

"},{"location":"eventemitter3/#usage","title":"Usage","text":""},{"location":"eventemitter3/#get-event-emitter","title":"Get event emitter","text":"
  • Scene:
    var ee = scene.events;\n
  • Game object:
    var ee = gameObject;\n
"},{"location":"eventemitter3/#attach-listener","title":"Attach listener","text":"
ee.on(eventName, callback, scope);\nee.once(eventName, callback, scope);  // only fire listeners one time\n

Alias

ee.addListener(eventName, callback, scope);\nee.addListener(eventName, callback, scope, true);  // only fire listeners one time\n
"},{"location":"eventemitter3/#fire-event","title":"Fire event","text":"
ee.emit(eventName, parameter0, ...);\n
"},{"location":"eventemitter3/#remove-listeners","title":"Remove listeners","text":"
  • Remove a linstener
    ee.off(eventName, callback, scope);\nee.off(eventName, callback, scope, true);   // only remove one-time listeners\n
    or
    ee.removeListener(eventName, callback, scope); ee.removeListener(eventName, callback, scope, true);  // only remove one-time listeners\n
  • Remove listeners of an event
    ee.off(eventName);\n
    or
    ee.removeListener(eventName); 
  • Remove listeners of all events
    ee.removeAllListeners();\n
"},{"location":"eventemitter3/#get-listeners-count","title":"Get listeners count","text":"
var count = ee.listenerCount(eventName);\n//var noListener = (ee.listenerCount(eventName) === 0);\n
"},{"location":"eventemitter3/#get-listeners","title":"Get listeners","text":"
var listeners = ee.listeners(eventName);\n
"},{"location":"eventemitter3/#get-event-names","title":"Get event names","text":"
var names = ee.eventNames();\n
"},{"location":"eventemitter3/#listener","title":"Listener","text":"
{\nfn: callback,\ncontext: scope,\nonce: once\n}\n
"},{"location":"eventemitter3/#custom-event-emitter-class","title":"Custom event emitter class","text":"
class MyEventEmitter extends Phaser.Events.EventEmitter {\n// construct() {\n//     super();\n// }\n\n// destroy() {\n//     super.destroy();\n// }\n}\n
"},{"location":"eventpromise/","title":"Event promise","text":""},{"location":"eventpromise/#introduction","title":"Introduction","text":"

Return a promise of an event.

  • Author: Rex
  • Method only
"},{"location":"eventpromise/#live-demos","title":"Live demos","text":"
  • Wait complete
"},{"location":"eventpromise/#usage","title":"Usage","text":"

Sample code

"},{"location":"eventpromise/#install-plugin","title":"Install plugin","text":""},{"location":"eventpromise/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexeventpromiseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexeventpromiseplugin.min.js', true);\n
  • Get event promise
    var promoise = scene.plugins.get('rexeventpromiseplugin').waitEvent(eventEmitter, eventName);\n// var promoise = scene.plugins.get('rexeventpromiseplugin').waitComplete(eventEmitter);\n
"},{"location":"eventpromise/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import EventPromisePlugin from 'phaser3-rex-plugins/plugins/eventpromise-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexEventPromise',\nplugin: EventPromisePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Get event promise
    var promoise = scene.plugins.get('rexEventPromise').waitEvent(eventEmitter, eventName);\n// var promoise = scene.plugins.get('rexEventPromise').waitComplete(eventEmitter);\n
"},{"location":"eventpromise/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { WaitEvent, WaitComplete } from 'phaser3-rex-plugins/plugins/eventpromise.js';\n
  • Get event promise
    var promoise = WaitEvent(eventEmitter, eventName);\n// var promoise = WaitComplete(eventEmitter);\n
"},{"location":"eventpromise/#get-event-promise","title":"Get event promise","text":"
var promoise = scene.plugins.get('rexEventPromise').waitEvent(eventEmitter, eventName)\n.then(function() {\n\n})\n
  • eventEmitter : Any kind of event emitter. for example, game object, or tween task, or scene event
"},{"location":"eventpromise/#get-complete-event-promise","title":"Get complete event promise","text":"
var promoise = scene.plugins.get('rexEventPromise').waitComplete(eventEmitter)\n.then(function() {\n\n})\n
  • eventEmitter : Event emitter which will fire 'complete' event, for example, tween task.
"},{"location":"expression-parser/","title":"Expression parser","text":""},{"location":"expression-parser/#introduction","title":"Introduction","text":"

Parse expression string into function. Parser is generated from jison

  • Author: Rex
  • Member of scene
"},{"location":"expression-parser/#live-demos","title":"Live demos","text":"
  • Dot-notation
  • Custom method
  • Proxy as context
"},{"location":"expression-parser/#usage","title":"Usage","text":"

Sample code

"},{"location":"expression-parser/#install-plugin","title":"Install plugin","text":""},{"location":"expression-parser/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexexpressionparserplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexexpressionparserplugin.min.js', true);\n
  • Add parser
    var parser = scene.plugins.get('rexexpressionparserplugin').add();\n
  • Or, parse expression to function object.
    var f = scene.plugins.get('rexexpressionparserplugin').compile(expressionString);\n// var value = f(context);\n
"},{"location":"expression-parser/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ExpressionParserPlugin from 'phaser3-rex-plugins/plugins/expressionparser-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexExpressionParserPlugin',\nplugin: ExpressionParserPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add parser
    var parser = scene.plugins.get('rexExpressionParserPlugin').add();\n
  • Or, parse expression to function object.
    var f = scene.plugins.get('rexExpressionParserPlugin').compile(expressionString);\n// var value = f(context);\n
"},{"location":"expression-parser/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ExpressionParser from 'phaser3-rex-plugins/plugins/expressionparser.js';\n
  • Add parser
    var parser = new ExpressionParser();\n
"},{"location":"expression-parser/#create-instance","title":"Create instance","text":"
var parser = scene.plugins.get('rexExpressionParserPlugin').add();\n
"},{"location":"expression-parser/#execute","title":"Execute","text":""},{"location":"expression-parser/#compile-then-execute","title":"Compile then execute","text":"
  1. Compile expression string into function
    var f = parser.compile(expressionString);\n
    or
    var f = scene.plugins.get('rexExpressionParserPlugin').compile(expressionString);\n
    • expressionString :
      • Number : 1, 1.5, 0xf.
      • Variable : a, $a, _a, a.$b._c_, a['b'].c
      • Arithmetic : +, -, *, \\, %, (, ), ex : '(a + b.c) * 3 + (2 % 3)'.
      • Boolean : >, <, >=, <=, ==, !=, &&, ||, ex '(a > 10) && (a < 30) || (b.c > c)'.
      • Condition : (cond)? v0:v1, ex'(a > b.c)? a:b.c'.
      • Custom method : randomInt(a, b.c).
      • String concat : 'Hello ' + name.
  2. Invoke function
    var value = f(context);\n
    • f : Function object from compiled result.
    • context : Varables used in expression.
      {\na: 10,  // Number\nb: {c: 10},  // Objet with number property\nc: 20,\nrandomInt(a, b) {  // Custom method\nreturn Math.floor(Math.random()*(b-a)+a);\n}\n}\n
"},{"location":"expression-parser/#execute-directly","title":"Execute directly","text":"
var value = parser.exec(expressionString, context);\n

or

var value = parser.exec(f, context);\n
"},{"location":"expression-parser/#custom-method","title":"Custom method","text":"
  • Add method into parser instance
    var parser = scene.plugins.get('rexExpressionParserPlugin').add();\nparser.randomInt = function(a, b) {\nreturn Math.floor(Math.random()*(b-a)+a); }\n// var value = parser.exec('randomInt(a, b)', {a:10, b:20});\n
  • Declare method into class of parser
    class MyParser extends ExpressionParser {\nrandomInt(a, b) {\nreturn Math.floor(Math.random()*(b-a)+a); }\n}\nvar parser = new MyParser();\n// var value = parser.exec('randomInt(a, b)', {a:10, b:20});\n
  • Add method into context
    var context = {\na: 10,\nb: 20,\nrandomInt(a, b) {  // Custom method\nreturn Math.floor(Math.random()*(b-a)+a);\n}\n}\nvar value = parser.exec('randomInt(a, b)', context);\n
"},{"location":"expression-parser/#proxy-as-context","title":"Proxy as context","text":"

Proxy with has and get handlers could be a context.

For example, proxy scene data :

var context = new Proxy({}, {\nhas(target, key) {\nreturn scene.data.has(key);\n},\nget(target, prop) {\nreturn scene.data.get(prop);\n}\n})\n

or

var context = scene.plugins.get('rexExpressionParserPlugin').createProxyContext({\nhas(target, key) {\n// return boolean\n},\nget(target, prop) {\n// return any;\n}\n})\n
"},{"location":"fadeoutdestroy/","title":"Fade out destroy","text":""},{"location":"fadeoutdestroy/#introduction","title":"Introduction","text":"

Fade out game object then destroy it.

  • Author: Rex
  • Method only
"},{"location":"fadeoutdestroy/#usage","title":"Usage","text":"

Sample code

"},{"location":"fadeoutdestroy/#install-plugin","title":"Install plugin","text":""},{"location":"fadeoutdestroy/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfadeplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfadeplugin.min.js', true);\n
  • Fade-out-destroy
    var fade = scene.plugins.get('rexfadeplugin').fadeOutDestroy(gameObject, duration);\n
"},{"location":"fadeoutdestroy/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FadePlugin from 'phaser3-rex-plugins/plugins/fade-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFade',\nplugin: FadePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Fade-out-destroy
    var fade = scene.plugins.get('rexFade').fadeOutDestroy(gameObject, duration);\n
"},{"location":"fadeoutdestroy/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import FadeOutDestroy from 'phaser3-rex-plugins/plugins/fade-out-destroy.js';\n
  • Fade-out-destroy
    var fade = FadeOutDestroy(gameObject, duration);\n
"},{"location":"fadeoutdestroy/#fade-out-destroy","title":"Fade-out-destroy","text":"
var fade = scene.plugins.get('rexFade').fadeOutDestroy(gameObject, duration);\n
"},{"location":"fadeoutdestroy/#events","title":"Events","text":"

See Events of tween task

  • Scale completes or is stopped.
    fade.on('complete', function(gameObject, fade){\n\n}, scope);\n
"},{"location":"fadeoutdestroy/#inject-methods","title":"Inject methods","text":"
  • Inject methods into game object
    scene.plugins.get('rexFade').injectMethods(gameObject);\n
  • Inject methods into class of game object
    scene.plugins.get('rexFade').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexFade').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into class of game object
    scene.plugins.get('rexFade').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexFade').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into root class of game object
    scene.plugins.get('rexFade').injectMethodsToRootClass(e);\n// scene.plugins.get('rexFade').injectMethods(Phaser.GameObjects.GameObject.prototype);\n
"},{"location":"fadeoutdestroy/#injected-methods","title":"Injected methods","text":"
  • Fade-in
    gameObject.fadeIn(duration);\n
    or
    gameObject.fadeIn(duration, endAlpha);\n
    or
    gameObject.fadeIn(duration, {start:0, end:1});\n
    or
    gameObject.fadeInPromise(duration, endAlpha)\n.then(function(){\n// ...\n})\n
    or
    gameObject.fadeInPromise(duration, {start:0, end:1})\n.then(function(){\n// ...\n})\n
  • Fade-out destroy
    gameObject.fadeOutDestroy(duration);\n
    or
    gameObject.fadeOutDestroyPromise(duration)\n.then(function(){\n// ...\n})\n
  • Fade-out without destroy
    gameObject.fadeOut(duration);\n
    or
    gameObject.fadeOutPromise(duration)\n.then(function(){\n// ...\n})\n
  • Events
    • Fade-in complete
      gameObject.on('fadein.complete', function(gameObject) { });\n
    • Fade-out, fade-out destroy complete
      gameObject.on('fadeout.complete', function(gameObject) { });\n
"},{"location":"fadevolume/","title":"Volume fading","text":""},{"location":"fadevolume/#introduction","title":"Introduction","text":"

Fade-in/fade-out volume of sound.

  • Author: Rex
  • Method only
"},{"location":"fadevolume/#usage","title":"Usage","text":"

Sample code

"},{"location":"fadevolume/#install-plugin","title":"Install plugin","text":""},{"location":"fadevolume/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexsoundfadeplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexsoundfadeplugin.min.js', true);\n
  • Sound fade-in/fade-out
    var sound = scene.plugins.get('rexsoundfadeplugin').fadeIn(sound, duration);\nvar sound = scene.plugins.get('rexsoundfadeplugin').fadeOut(sound, duration);\n
"},{"location":"fadevolume/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SoundFadePlugin from 'phaser3-rex-plugins/plugins/soundfade-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexSoundFade',\nplugin: SoundFadePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Sound fade-in/fade-out
    var sound = scene.plugins.get('rexSoundFade').fadeIn(sound, duration);\nvar sound = scene.plugins.get('rexSoundFade').fadeOut(sound, duration);\n
"},{"location":"fadevolume/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import SoundFade from 'phaser3-rex-plugins/plugins/soundfade.js';\n
  • Sound fade-in/fade-out
    var sound = SoundFade.fadeIn(sound, duration);\nvar sound = SoundFade.fadeOut(sound, duration);\n
"},{"location":"fadevolume/#fade-in","title":"Fade in","text":"
  • Play and fade in voluem.
    var sound = scene.plugins.get('rexSoundFade').fadeIn(sound, duration);\n// var sound = scene.plugins.get('rexSoundFade').fadeIn(sound, duration, endVolume, startVolume);\n
    • sound : Sound instance, or a key of audio cache.
"},{"location":"fadevolume/#fade-out","title":"Fade out","text":"
  • Fade out volume then destroy it
    scene.plugins.get('rexSoundFade').fadeOut(sound, duration);\n
    • sound : Sound instance.
  • Fade out volume then stop it
    scene.plugins.get('rexSoundFade').fadeOut(sound, duration, false);\n
    • sound : Sound instance.
"},{"location":"filechooser/","title":"File chooser","text":""},{"location":"filechooser/#introduction","title":"Introduction","text":"

Create a transparent file chooser button (<input type=\"file\">).

  • Author: Rex
  • DOM Game object
"},{"location":"filechooser/#live-demos","title":"Live demos","text":"
  • File chooser button
  • Open file chooser dialog
"},{"location":"filechooser/#usage","title":"Usage","text":"

Sample code

"},{"location":"filechooser/#install-plugin","title":"Install plugin","text":""},{"location":"filechooser/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfilechooserplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfilechooserplugin.min.js', true);\n
  • Add file chooser object
    var fileChooser = scene.add.rexFileChooser(config);\n
"},{"location":"filechooser/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FileChooserPlugin from 'phaser3-rex-plugins/plugins/filechooser-plugin.js';\nvar config = {    parent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFileChooser',\nplugin: FileChooserPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add file chooser object
    var fileChooser = scene.add.rexFileChooser(config);\n
"},{"location":"filechooser/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import { FileChooser } from 'phaser3-rex-plugins/plugins/filechooser.js';\n
  • Add file chooser object
    var fileChooser = new FileChooser(config);\nscene.add.existing(fileChooser);\n
"},{"location":"filechooser/#add-file-chooser-object","title":"Add file chooser object","text":"
var fileChooser = scene.add.rexFileChooser({\naccept: '',\nmultiple: false\n});\n// var fileChooser = scene.add.rexFileChooser(x, y, width, height, config);\n
  • accept : A filter for what file types the user can pick from the file input dialog box.
    • 'image/*' : The user can pick all image files.
    • 'audio/*' : The user can pick all sound files.
    • 'video/*' : The user can pick all video files.
    • file_extension : Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can pick from.
  • multiple : Set true to select multiple files.
"},{"location":"filechooser/#custom-class","title":"Custom class","text":"
  • Define class
    class MyFlieChooser extends FileChooser {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config) {\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var fileChooser = new MyFlieChooser(scene, x, y, width, height, config);\n
"},{"location":"filechooser/#sync","title":"Sync","text":"

Sync position, size and origin to another game object.

fileChooser.syncTo(gameObject);\n
"},{"location":"filechooser/#selected-files","title":"Selected files","text":"
var files = fileChooser.files;\n
  • files : Array of file object.
"},{"location":"filechooser/#set-accept-filter","title":"Set accept filter","text":"
fileChooser.setAccept(accept);\n
  • accept : A filter for what file types the user can pick from the file input dialog box.
    • 'image/*' : The user can pick all image files.
    • 'audio/*' : The user can pick all sound files.
    • 'video/*' : The user can pick all video files.
    • file_extension : Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can pick from.
"},{"location":"filechooser/#multiple-files","title":"Multiple files","text":"
  • Enable
    fileChooser.setMultiple();\n
  • Disable
    fileChooser.setMultiple(false);\n
"},{"location":"filechooser/#events","title":"Events","text":"
  • Selected file(s) changed
    fileChooser.on('change', function(fileChooser) {\nvar files = fileChooser.files;\nif (files.length === 0) { // No selected file\nreturn;\n}\n\nvar file = files[0];\nvar url = URL.createObjectURL(file);\n// ...\n})\n
"},{"location":"filechooser/#load-file-to-cache","title":"Load file to cache","text":"
fileChooser.loadFile(file, loaderType, key);\n// fileChooser.loadFile(file, loaderType, key, cahceType);\n

or

fileChooser.loadFilePromise(file, loaderType, key, cahceType)\n.then(function(content) {\n\n})\n
  • file : File object, see Events
  • loaderType : image, text, binary, ... See Loader
  • key : Unique string key.
  • cahceType :
    • undefined : Use default value.
  • content : Content of file.
"},{"location":"filechooser/#create-object-url","title":"Create object URL","text":"
  • Create object url
    var objectURL = URL.createObjectURL(file);\n
  • Release object url
    URL.revokeObjectURL(objectURL);\n
"},{"location":"filechooser/#open-file-chooser","title":"Open file chooser","text":"

Failure

This method won't work at ios.

Note

Open a file chooser dialog under any touch event. i.e. User can't open file chooser dialog directly.

scene.plugins.get('rexFileChooser').open({\n// accept: '',\n// multiple: false,\n// closeDelay: 200\n})\n.then(function(result) {\n// var files = result.files;\n})\n
  • accept : A filter for what file types the user can pick from the file input dialog box.
    • 'image/*' : The user can pick all image files.
    • 'audio/*' : The user can pick all sound files.
    • 'video/*' : The user can pick all video files.
    • file_extension : Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can pick from.
  • multiple : Set true to select multiple files.
  • closeDelay : Add a small delay to detect dialog canceled after game focus.
    • File chooser dialog dose not have cancel event.
  • files : Array of selected files.
    • Each file object (files[i]) has properties
      • file.name : File name with file extension.
      • file.type : File type. (ex. 'image/jpeg')
      • file.size : File size in bytes.
      • file.lastModified : Timestamp of last-modified time.
      • file.lastModifiedDate : Date object of last-modified time. Equal to new Data(lastModified).
      • Get object url :
        var objectURL = URL.createObjectURL(file);\n
    • Length files is 0 : User cancels file chooser dialog.
"},{"location":"filechooser/#enable-clicking-open","title":"Enable clicking-open","text":"
  • Enable
    fileChooser.setOpenEnable();\n// fileChooser.setOpenEnable(true);\n
  • Disable
    fileChooser.setOpenEnable(false)\n
"},{"location":"filechooser/#other-properties","title":"Other properties","text":"

See dom game object, game object

"},{"location":"filechooser/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"

See dom-element's Interactive with other game objects

"},{"location":"filedropzone/","title":"File drop zone","text":""},{"location":"filedropzone/#introduction","title":"Introduction","text":"

Create a div element for dropping file(s).

  • Author: Rex
  • DOM Game object
"},{"location":"filedropzone/#live-demos","title":"Live demos","text":"
  • Drop text file
  • Drop image file
  • Interactve with other game objects
"},{"location":"filedropzone/#usage","title":"Usage","text":"

Sample code

"},{"location":"filedropzone/#install-plugin","title":"Install plugin","text":""},{"location":"filedropzone/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfiledropzoneplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfiledropzoneplugin.min.js', true);\n
  • Add file-drop-zone object
    var fileDropZone = scene.add.rexFileDropZone(config);\n
"},{"location":"filedropzone/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FileDropZonePlugin from 'phaser3-rex-plugins/plugins/filedropzone-plugin.js';\nvar config = {    parent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n}, // ...\nplugins: {\nglobal: [{\nkey: 'rexFileDropZone',\nplugin: FileDropZonePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add file-drop-zone object
    var fileDropZone = scene.add.rexFileDropZone(config);\n
"},{"location":"filedropzone/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import { FileDropZone } from 'phaser3-rex-plugins/plugins/filedropzone.js';\n
  • Add file-drop-zone object
    var fileDropZone = new FileDropZone(config);\nscene.add.existing(fileDropZone);\n
"},{"location":"filedropzone/#add-file-drop-zone-object","title":"Add file-drop-zone object","text":"
var fileDropZone = scene.add.rexFileDropZone({\n// style: { },\n\n// dropEnable: true,\n// filters: { filterType: (file, files) => boolean }\n});\n// var fileDropZone = scene.add.rexFileDropZone(x, y, width, height, config);\n
  • style : CSS style of div element.
  • dropEnable :
    • true : Fire drop events when dropping files. Default behavior.
    • false : Won't fire drop events.
  • filters : Filter methods, optional. For example, image files filter, will fire 'drop.image' event
    {\nimage: function(file, files) { return file.name.match(/\\.(jpg|jpeg|png|gif)$/i)\n}\n}\n
"},{"location":"filedropzone/#custom-class","title":"Custom class","text":"
  • Define class
    class MyFileDropZone extends FileDropZone {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config) {\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var fileDropZone = new MyFileDropZone(scene, x, y, width, height, config);\n
"},{"location":"filedropzone/#sync","title":"Sync","text":"

Sync position, size and origin to another game object.

fileDropZone.syncTo(gameObject);\n
"},{"location":"filedropzone/#dropped-files","title":"Dropped files","text":"
var files = fileDropZone.files;\n
  • files : Array of file object.
"},{"location":"filedropzone/#events","title":"Events","text":"
  • Drop files
    fileDropZone.on('drop', function(fileDropZone) {\nvar files = fileDropZone.files;\n})\n
  • Drop filtered files
    fileDropZone.on('drop.' + filterType, function(files) {\n})\n
  • Drag-enter/drag-leave/drag-over file(s)
    fileDropZone.on('dragenter', function(fileDropZone) {\n})\n
    fileDropZone.on('dragleave', function(fileDropZone) {\n})\n
    fileDropZone.on('dragover', function(fileDropZone) {\n})\n

Warning

Game objects under this file drop zone can't receive touch input events.

"},{"location":"filedropzone/#enable-drop-events","title":"Enable drop events","text":"
  • Enable
    fileDropZone.setDropEnable();\n// fileDropZone.setDropEnable(true);\n
  • Disable
    fileDropZone.setDropEnable(false);\n
  • Toggle
    fileDropZone.toggleDropEnable();\n
"},{"location":"filedropzone/#load-file-to-cache","title":"Load file to cache","text":"
fileDropZone.loadFile(file, loaderType, key);\n// fileDropZone.loadFile(file, loaderType, key, cahceType, onComplete);\n

or

fileDropZone.loadFilePromise(file, loaderType, key, cahceType)\n.then(function(content) {\n\n})\n
  • file : File object, see Events
  • loaderType : image, text, binary, ... See Loader
  • key : Unique string key.
  • cahceType :
    • undefined : Use default value.
  • onComplete : Callback invoked when file loaded to cache.
  • content : Content of file.
"},{"location":"filedropzone/#create-object-url","title":"Create object URL","text":"
  • Create object url
    var objectURL = URL.createObjectURL(file);\n
  • Release object url
    URL.revokeObjectURL(objectURL);\n
"},{"location":"filedropzone/#other-properties","title":"Other properties","text":"

See dom game object, game object

"},{"location":"filedropzone/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"

See dom-element's Interactive with other game objects

"},{"location":"firebase-auth/","title":"Authentication","text":""},{"location":"firebase-auth/#introduction","title":"Introduction","text":"

It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.

  • Author: Firebase
"},{"location":"firebase-auth/#usage","title":"Usage","text":"

Official document

Sample code

"},{"location":"firebase-auth/#setup","title":"Setup","text":"
  1. Import firestore
    import firebase from 'firebase/app';\nimport 'firebase/auth';\n
    Firebase has been included in package.json.
  2. Initialize
    var firebaseApp = firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n});\n
"},{"location":"firebase-auth/#on-sign-insign-out","title":"On sign-in/sign-out","text":"
firebaseApp.auth().onAuthStateChanged(function (user) {\nif (user) {\n// User is signed in.\nvar displayName = user.displayName;\nvar email = user.email;\nvar emailVerified = user.emailVerified;\nvar photoURL = user.photoURL;\nvar isAnonymous = user.isAnonymous;\nvar uid = user.uid;\nvar providerData = user.providerData;\n// ...\n} else {\n// User is signed out.\n// ...\n}\n});\n
"},{"location":"firebase-auth/#sign-in-with-facebook","title":"Sign-in with facebook","text":"
var provider = new firebase.auth.FacebookAuthProvider();\nfirebaseApp.auth().signInWithPopup(provider).then(function (result) {\n// This gives you a Facebook Access Token. You can use it to access the Facebook API.\nvar token = result.credential.accessToken;\n// The signed-in user info.\nvar user = result.user;\n// ...\n}).catch(function (error) {\n// Handle Errors here.\nvar errorCode = error.code;\nvar errorMessage = error.message;\n// The email of the user's account used.\nvar email = error.email;\n// The firebase.auth.AuthCredential type that was used.\nvar credential = error.credential;\n// ...\n});\n
"},{"location":"firebase-auth/#sign-in-with-google","title":"Sign-in with Google","text":"
var provider = new firebase.auth.GoogleAuthProvider();\nfirebaseApp.auth().signInWithPopup(provider).then(function (result) {\n// This gives you a Google Access Token. You can use it to access the Google API.\nvar token = result.credential.accessToken;\n// The signed-in user info.\nvar user = result.user;\n// ...\nconsole.log(user);\n}).catch(function (error) {\n// Handle Errors here.\nvar errorCode = error.code;\nvar errorMessage = error.message;\n// The email of the user's account used.\nvar email = error.email;\n// The firebase.auth.AuthCredential type that was used.\nvar credential = error.credential;\n// ...\n});\n
"},{"location":"firebase-auth/#sign-in-with-password","title":"Sign-in with password","text":"
  • Create new user
    firebaseApp.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {\n// Handle Errors here.\nvar errorCode = error.code;\nvar errorMessage = error.message;\n});\n
  • Sign-in
    firebase.auth().signInWithEmailAndPassword(email, password).catch(function (error) {\n// Handle Errors here.\nvar errorCode = error.code;\nvar errorMessage = error.message;\n});\n
"},{"location":"firebase-auth/#sign-out","title":"Sign-out","text":"
firebaseApp.auth().signOut();\n
"},{"location":"firebase-auth/#current-sign-in-user","title":"Current sign-in user","text":"
var user = firebaseApp.auth().currentUser;\nif (user != null) {\nvar name = user.displayName;\nvar email = user.email;\nvar photoUrl = user.photoURL;\nvar emailVerified = user.emailVerified;\nvar uid = user.uid;\n}\n
"},{"location":"firebase-auth/#update-email","title":"Update email","text":"
user.updateEmail('...').then(function() {\n// Update successful.\n}).catch(function(error) {\n// An error happened.\n});\n
"},{"location":"firebase-auth/#update-profile","title":"Update profile","text":"
user.updateProfile({\ndisplayName: '...',\nphotoURL: '...'\n}).then(function() {\n// Update successful.\n}).catch(function(error) {\n// An error happened.\n});\n
"},{"location":"firebase-auth/#send-a-verification-email","title":"Send a verification email","text":"
user.sendEmailVerification().then(function() {\n// Email sent.\n}).catch(function(error) {\n// An error happened.\n});\n
"},{"location":"firebase-broadcast/","title":"Broadcast","text":""},{"location":"firebase-broadcast/#introduction","title":"Introduction","text":"

Broadcast real-time messages, using firebase-database.

  • Author: Rex
"},{"location":"firebase-broadcast/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-broadcast/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-broadcast/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add messager object
    var messager = scene.plugins.get('rexfirebaseplugin').add.broadcast(config);\n
"},{"location":"firebase-broadcast/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add messager object
    var messager = scene.plugins.get('rexFirebase').add.broadcast(config);\n
"},{"location":"firebase-broadcast/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { Broadcast } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add messager object
    var messager = new Broadcast(config);\n
"},{"location":"firebase-broadcast/#create-instance","title":"Create instance","text":"
var messager = scene.plugins.get('rexFirebase').add.broadcast({\nroot: '',\n// senderID: '',\n// senderName: '',\n// receiverID: '',\n// history: 0\n});\n
  • root : Path of this messager.
  • senderID : ID of sender.
  • senderName : Name of sender.
  • receiverID : ID of receiver/channel.
  • history : Stored received (history) messages in client side.
    • 0, or false : No history message stored.
    • -1, or true : Infinity history message stored. i.e. store all messages from starting updating.
    • A number larger then 0 : Length of stored history message.
"},{"location":"firebase-broadcast/#send-message","title":"Send message","text":"
  1. Set sender in config, or setSender method.
    messager.setSender(userID, userName);\n
    or
    messager.setSender({\nuserID: userID,\nuserName: userName\n});\n
    • userID : User ID of sender.
    • userName : Display name of sender.
  2. Set receiver in config, or setReceiver method.
    messager.setReceiver(receiverID);\n
    • receiverID : ID of receiver/channel.
  3. Send message to receiverID.
    messager.send(message)\n// .then(function() { })\n// .catch(function() { })\n
    • message : A string message, or a JSON data.
"},{"location":"firebase-broadcast/#receive-messages","title":"Receive messages","text":"
  1. Register receive event
    messager.on('receive', function(data){\n// var senderID = data.senderID;\n// var senderName = data.senderName;\n// var message = data.message;\n})\n
  2. Set receiver in config, or setReceiver method
    messager.setReceiver(receiverID);\n
    • receiverID : ID of receiver/channel.
  3. Start receiving
    messager.startReceiving();\n
  4. Stop receive
    messager.stopReceiving();\n

Only receive messages after invoking startReceiving method. Previous messages won't be got anymore.

"},{"location":"firebase-broadcast/#received-messages","title":"Received messages","text":"

Received messages will be saved in client side.

  • Get received (history) messages.
    var messages = messager.getHistory();\n
  • Clear history messages.
    messager.clearHistory();\n
"},{"location":"firebase-files/","title":"Files","text":""},{"location":"firebase-files/#introduction","title":"Introduction","text":"

Save JSON data, using firebase-firestore.

Each owner has several files, each file contains header and content indexed by fileID.

  • Author: Rex
"},{"location":"firebase-files/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-files/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-files/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add file-manager object
    var fileManager = scene.plugins.get('rexfirebaseplugin').add.files(config);\n
"},{"location":"firebase-files/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add file-manager object
    var fileManager = scene.plugins.get('rexFirebase').add.files(config);\n
"},{"location":"firebase-files/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { Files } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add file-manager object
    var fileManager = new Files(config);\n
"},{"location":"firebase-files/#create-instance","title":"Create instance","text":"
var fileManager = scene.plugins.get('rexFirebase').add.files({\nroot: ''\n});\n
  • root : Collection name of these files.
"},{"location":"firebase-files/#save-file","title":"Save file","text":"
  1. Set file owner.
    fileManager.setOwner(userID);\n
    or
    fileManager.setOwner({\nuserID: userID\n});\n
    • userID : User ID of file owner.
  2. Save header and content data.
    • Overwrite
      fileManager.save(fileID, header, content);\n
      • fileID : Unique ID of this file.
      • header : Header data for indexing, a JSON object.
        • Reserve keys : userID, fileID, type, contentDocID. (i.e. don't use these keys)
      • content : Content/body, a JSON object.
        • Reserve keys : userID, fileID, type. (i.e. don't use these keys)
    • Update
      fileManager.save(fileID, header, content, true);\n
"},{"location":"firebase-files/#load-headers","title":"Load headers","text":"
  1. Set file owner.
    fileManager.setOwner(userID);\n
  2. Load all headers of this file owner.
    fileManager.loadHeaders()\n.then(function(result) { // var headers = result.headers;\n// var userID = result.userID;\n})\n.catch(function(result) {\n// var error = result.error;\n// var userID = result.userID;\n})\n
    • headers : Get header by headers[fileID], each header contains
      • header.fileID : Unique ID of this file.
      • header.userID : User ID of file owner.
"},{"location":"firebase-files/#load-file","title":"Load file","text":"
  1. Set file owner.
    fileManager.setOwner(userID);\n
  2. Load file.
    fileManager.load(fileID)\n.then(function(result) { // var header = result.header;\n// var content = result.content;\n// var fileID = result.fileID;\n// var userID = result.userID;\n})\n.catch(function(result) {\n// var error = result.error;\n// var fileID = result.fileID;\n// var userID = result.userID;\n})\n
    • header, content : Header/content of this file.
    • fileID : Unique ID of this file.
    • userID : User ID of file owner.
"},{"location":"firebase-firestore/","title":"Firestore","text":""},{"location":"firebase-firestore/#introduction","title":"Introduction","text":"

Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform.

  • Author: Firebase
"},{"location":"firebase-firestore/#usage","title":"Usage","text":"

Official document

Sample code

"},{"location":"firebase-firestore/#setup","title":"Setup","text":"
  1. Import firestore
    import firebase from 'firebase/app';\nimport 'firebase/firestore';\n
    Firebase has been included in package.json.
  2. Initialize
    var firebaseApp = firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n});\nvar db = firebaseApp.firestore();\ndb.settings({\ntimestampsInSnapshots: true\n})\n
"},{"location":"firebase-firestore/#references","title":"References","text":"
  • Reference of collection
    var collectionRef = db.collection(collectionName);\n
  • Reference of document
    var docRef = db.collection(collectionName).doc(docName);\n
"},{"location":"firebase-firestore/#save","title":"Save","text":"
  • Add document
    db.collection(collectionName).add(doc)      // doc: { ... }\n.then(function(doc) { /* ... */ })\n.catch(function(error) { /* ... */ });\n
    Maximum size for a document : 1 MiB (1,048,576 bytes)
  • Set document
    db.collection(collectionName).doc(docName).set(keyValues)  // keyValues: { ... }\n.then(function(doc) { /* ... */ })\n.catch(function(error) { /* ... */ });\n
    Overwrite document
  • Update data
    db.collection(collectionName).doc(docName).update(keyValues)  // keyValues: { ... }\n.then(function(doc) { /* ... */ })\n.catch(function(error) { /* ... */ });\n
  • Batched writes
    // Get a new write batch\nvar batch = db.batch();\n\nbatch.set(db.collection(collectionName).doc(docName), keyValues);\nbatch.update(db.collection(collectionName).doc(docName), keyValues);\nbatch.delete(db.collection(collectionName).doc(docName));\n// ...\n\n// Commit the batch\nbatch.commit()\n.then(function() { /* ... */ })\n.catch(function(error) { /* ... */ });\n
    Maximum document writting in a commit : 500
  • Delete a document
    db.collection(collectionName).doc(docName).delete()\n.then(function() { /* ... */ })\n.catch(function(error) { /* ... */ });\n
  • Delete a field
    db.collection(collectionName).doc(docName).update({\nkey: firebase.firestore.FieldValue.delete()\n})\n.then(function() { /* ... */ })\n.catch(function(error) { /* ... */ });\n
  • Transaction
    var docRef = db.collection(collectionName).doc(docName);\ndb.runTransaction(function(transaction) {\n// read-modify-write\n// This code may get re-run multiple times if there are conflicts.\nreturn transaction.get(docRef).then(function(doc) {\n// doc.exists\ntransaction.update(docRef, keyValues);\n});\n})\n.then(function() {\n//console.log(\"Transaction successfully committed!\");\n})\n.catch(function(error) {\n//console.log(\"Transaction failed: \", error);\n});\n

Limitation: Writes and transactions section

"},{"location":"firebase-firestore/#server-timestamp","title":"Server timestamp","text":"
firebase.firestore.FieldValue.serverTimestamp()\n
"},{"location":"firebase-firestore/#load","title":"Load","text":"
  • Get a document
    db.collection(collectionName).doc(docName).get()\n.then(function(doc) { /* ... */ })\n.catch(function(error) { /* ... */ });\n
    • doc
      • doc.id
      • doc.data()
  • Get all documents
    db.collection(collectionName).get()\n.then(function(querySnapshot) { /* ... */ })\n.catch(function(error){ /* ... */ });\n
    • querySnapshot
      • querySnapshot.docs
      • querySnapshot.forEach(callback, thisArg)
      • querySnapshot.empty
      • querySnapshot.size
  • Simple queries
    db.collection(collectionName).where(key, op, value).get()\n.then(function(querySnapshot) { /* ... */ })\n.catch(function(error){ /* ... */ });\n
    • op : '>', '==', '<', '>=', '<='
      • != : where(key,'>', value).where(key, '<', value)
  • Compound queries
    db.collection(collectionName).where(key0, op0, value0).where(key1, op1, value1).get()\n.then(function(querySnapshot) { /* ... */ })\n.catch(function(error){ /* ... */ });\n
    • Range filters (<, <=, >, >=) on only one field
"},{"location":"firebase-firestore/#paginate","title":"Paginate","text":"
  • Order, limit
    db.collection(collectionName).orderBy(key).limit(count)\n
    • Descending order : orderBy(key, 'desc')
    • Order by multiple fields : orderBy(key0).orderBy(key1)
  • Query, order, limit
    db.collection(collectionName).where(key, op, value).orderBy(key).limit(count)\n
    • Key of first order must be equal to range comparison (<, <=, >, >=)
  • Page
    1. Start at
      db.collection(collectionName).orderBy(key).startAt(value).limit(count).get()\n.then(function(querySnapshot) { /* ... */ })\n.catch(function(error){ /* ... */ });\n
      • endAt(value)
    2. Next page
      var lastDoc = querySnapshot.docs[querySnapshot.docs.length - 1];\ndb.collection(collectionName).orderBy(key).startAfter(lastDoc).limit(count).get()\n.then(function(querySnapshot) { /* ... */ })\n.catch(function(error){ /* ... */ });\n
      • endBefore(lastDoc)
"},{"location":"firebase-firestore/#get-realtime-updates","title":"Get realtime updates","text":"
  • Get updates of a document
    var unsubscribe = db.collection(collectionName).doc(docName)\n.onSnapshot(function(doc) { /* ... */ });\n
  • Get updates of documents
    var unsubscribe = db.collection(collectionName).where(key, op, value)\n.onSnapshot(function(querySnapshot) { /* ... */ });\n
    • Changes
      var changes = querySnapshot.docChanges();  // [change]\n
      • Change
        • change.type : 'added', 'modified', 'removed'
        • change.newIndex
        • change.oldIndex
  • Detach a listener
    unsubscribe();\n
  • Events for metadata changes
    var unsubscribe = db.collection(collectionName).doc(docName)\n.onSnapshot({\nincludeMetadataChanges: true    // Listen for document metadata changes\n},\nfunction(doc) { /* ... */ } );\n
"},{"location":"firebase-firestore/#indexing","title":"Indexing","text":"

Reference

"},{"location":"firebase-idalias/","title":"ID-alias","text":""},{"location":"firebase-idalias/#introduction","title":"Introduction","text":"

Map an unique ID to another unique ID (alias), using firebase-firestore.

Each owner has several files, each file contains header and content indexed by fileID.

  • Author: Rex
"},{"location":"firebase-idalias/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-idalias/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-idalias/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add id-alias object
    var idAlias = scene.plugins.get('rexfirebaseplugin').add.idAlias(config);\n
"},{"location":"firebase-idalias/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add id-alias object
    var idAlias = scene.plugins.get('rexFirebase').add.idAlias(config);\n
"},{"location":"firebase-idalias/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { IdAlias } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add id-alias object
    var idAlias = new IdAlias(config);\n
"},{"location":"firebase-idalias/#create-instance","title":"Create instance","text":"
var idAlias = scene.plugins.get('rexFirebase').add.idAlias({\nroot: ''\n});\n
  • root : Collection name of this id-alias.
"},{"location":"firebase-idalias/#random-alias","title":"Random alias","text":"

Get alias of an id, or register an alias from a random word.

idAlias.getRandomAlias(id, {\ndigits: 10,\ncandidates: '0123456789',\nretry: 1000\n})\n.then(function(result) { // var alias = result.alias;\n// var id = result.id;\n})\n.catch(function(error) { })\n
  • id : An unique ID.
  • digits : String length of alias.
  • candidates : Candidate characters.
  • retry : Max retry count.
"},{"location":"firebase-idalias/#specific-alias","title":"Specific alias","text":"
  • Add a specific alias
    idAlias.add(id, alias)\n.then(function(result) { // var alias = result.alias;\n// var id = result.id;\n})\n.catch(function(error) { })\n
    • id : An unique ID.
    • alias : Another unique ID.
  • Get ID from alias
    idAlias.getId(alias)\n.then(function(result) { // var alias = result.alias;\n// var id = result.id; // Return undefined if alias is not existed.\n})\n.catch(function(error) { })\n
  • Get alias from ID
    idAlias.getAlias(id)\n.then(function(result) { // var alias = result.alias; // Return undefined if id is not existed.\n// var id = result.id;\n})\n.catch(function(error) { })\n
"},{"location":"firebase-itemtable/","title":"Item table","text":""},{"location":"firebase-itemtable/#introduction","title":"Introduction","text":"

1d/2d/3d table, using firebase-database.

  • Author: Rex
"},{"location":"firebase-itemtable/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-itemtable/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-itemtable/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add table object
    var table = scene.plugins.get('rexfirebaseplugin').add.itemTable(config);\n
"},{"location":"firebase-itemtable/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add table object
    var table = scene.plugins.get('rexFirebase').add.itemTable(config);\n
"},{"location":"firebase-itemtable/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { ItemTable } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add table object
    var table = new ItemTable(config);\n
"},{"location":"firebase-itemtable/#create-instance","title":"Create instance","text":"
var table = scene.plugins.get('rexFirebase').add.itemTable({\nroot: '',\ntype: 3\n});\n
  • root : Path of this item table.
  • type : Table type.
    • 1, or '1d' : 1d table, indexing by (key0)
    • 2, or '2d' : 2d table, indexing by (key0, key1)
    • 3, or '3d' : 3d table, indexing by (key0, key1, key2)
"},{"location":"firebase-itemtable/#write","title":"Write","text":"
  • Set data
    table.setData(key0, value)\n// table.setData(key0, key1, value)\n// table.setData(key0, key1, key2, value)\n.then(function() { })\n.catch(function() { })\n
    • key0, key1, key2 : Any string.
    • value : Number, string, or JSON data.
  • Increase value
    table.incValue(key0, value)\n// table.incValue(key0, key1, value)\n// table.incValue(key0, key1, key2, value)\n.then(function() { })\n.catch(function() { })    
    • key0, key1, key2 : Any string.
    • value : Number.
  • Remove key
    table.removeData(key0)\n// table.removeData(key0, key1)\n// table.inremoveDatacValue(key0, key1, key2)\n.then(function() { })\n.catch(function() { })    
    • key0, key1, key2 : Any string.
  • Batch writing specific values at key pathes
    table.updateData({\n`${key0}` : value0,\n`${key0}/${key1}` : value1,\n`${key0}/${key1}/${key2}` : value2,\n...\n})\n.then(function() { })\n.catch(function() { })    
  • Transaction, write new value according to latest value
    table.transaction(key0, callback)\n// table.transaction(key0, key1, callback)\n// table.transaction(key0, key1, key2, callback)\n.then(function() { })\n.catch(function() { })    
    • key0, key1, key2 : Any string.
    • callback : Write new value according to latest value.
      function(preValue) { return newValue; }\n
  • Remove key when current user disconnect
    table.removeDataOnDisconnect(key0)\n// table.removeDataOnDisconnect(key0, key1)\n// table.removeDataOnDisconnect(key0, key1, key2)\n.then(function() { })\n.catch(function() { })        
  • Set value when current user disconnect
    table.setDataOnDisconnect(key0, value)\n// table.setDataOnDisconnect(key0, key1, value)\n// table.setDataOnDisconnect(key0, key1, key2, value)\n.then(function() { })\n.catch(function() { })        
"},{"location":"firebase-itemtable/#read","title":"Read","text":"
  • Start updating
    table.startUpdate();\n
    • Trigger 'init' event when all data read back.
    • table.initialFlag : Return true when all data read back.
  • Stop updating
    table.stopUpdate();\n
  • Read data stored in client
    var data = table.getData(key0);\n// var data = table.getData(key0, key1);\n// var data = table.getData(key0, key1, key2);\n
    • data : Number, string, or JSON data.
  • Read all data stored in client
    var data = table.getData();\n
    • data : JSON data.
  • Clone data stored in client
    var data = table.cloneData(key0);\n// var data = table.cloneData(key0, key1);\n// var data = table.cloneData(key0, key1, key2);    \n
  • Clone all data stored in client
    var data = table.cloneData();\n
"},{"location":"firebase-itemtable/#events","title":"Events","text":"
  • Initialize, read all data back after start updating
    table.on('init', function(data) { })\n
    • data : Table data.
    • table.initialFlag will be set to true.
  • Any value updated
    table.on('update', function(data) { })\n
    • data : Table data.
"},{"location":"firebase-itemtable/#1d-table","title":"1d table","text":"

1d table, indexing by (key0)

  • On add key0
    table.on('addkey0', function(key0, value) {  });\n
  • On remove key0
    table.on('removekey0', function(key0) {  });\n
  • On change key0
    table.on('changekey0', function(key0, value) {  });\n
"},{"location":"firebase-itemtable/#2d-table","title":"2d table","text":"

2d table, indexing by (key0, key1)

  • On add key0
    table.on('addkey0', function(key0, value) {  });\n
  • On remove key0
    table.on('removekey0', function(key0) {  });\n
  • On add key1
    table.on('addkey1', function(key0, key1, value) {  });\n
  • On remove key1
    table.on('removekey1', function(key0, key1) {  });\n
  • On change key1
    table.on('changekey1', function(key0, key1, value) {  });\n
"},{"location":"firebase-itemtable/#3d-table","title":"3d table","text":"

3d table, indexing by (key0, key1, key2)

  • On add key0
    table.on('addkey0', function(key0, value) {  });\n
  • On remove key0
    table.on('removekey0', function(key0) {  });\n
  • On add key1
    table.on('addkey1', function(key0, key1, value) {  });\n
  • On remove key1
    table.on('removekey1', function(key0, key1) {  });\n
  • On add key2
    table.on('addkey2', function(key0, key1, key2, value) {  });\n
  • On remove key2
    table.on('removekey2', function(key0, key1, key2) {  });\n
  • On change key2
    table.on('changekey2', function(key0, key1, key2, value) {  });\n
"},{"location":"firebase-leaderboard/","title":"Leaderboard","text":""},{"location":"firebase-leaderboard/#introduction","title":"Introduction","text":"

Descending sort scores, using firebase-firestore.

  • Author: Rex
"},{"location":"firebase-leaderboard/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-leaderboard/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-leaderboard/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add leader-board object
    var leaderBoard = scene.plugins.get('rexfirebaseplugin').add.leaderBoard(config);\n
"},{"location":"firebase-leaderboard/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add leader-board object
    var leaderBoard = scene.plugins.get('rexFirebase').add.leaderBoard(config);\n
"},{"location":"firebase-leaderboard/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { LeaderBoard } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add leader-board object
    var leaderBoard = new LeaderBoard(config);\n
"},{"location":"firebase-leaderboard/#create-instance","title":"Create instance","text":"
var leaderBoard = scene.plugins.get('rexFirebase').add.leaderBoard({\nroot: '',\n// timeFilters: false,\n// timeFilterType: 'year',\n// pageItemCount: 100,\n// userID: '',\n// userName: '',\n// boardID: undefined,\n// tag: undefined\n});\n
  • root : Collection name of this leaderboard.
  • timeFilters : Time filter of day/week/month/year.
    • false : Don't use any time filter.
    • true : Enable all time filters.
    • JSON object, enable some time filters.
      {\nday: true,\nweek: true,\nmonth: true,\nyear: true,\nall: true\n}\n
  • timeFilterType : Type of time filter.
    • 'day', or 'd' : Filter scores by current day.
    • 'week', or 'w' : Filter scores by current week.
    • 'month', 'm' : Filter scores by current month.
    • 'year', 'y' : Filter scores by current year. Default value.
    • 'all', 'a' : No time filter to track all scores.
  • pageItemCount : Item count of a page, default value is 100
  • userID : ID of user.
  • userName : Name of user.
  • boardID : Board ID, optional.
  • tag : Custom tag, optional.

Time filter enabled

Add indexes if time filter is enabled. - tagD(ascending), scoreD(descending), boardID(ascending), tag(ascending) - tagW(ascending), scoreW(descending), boardID(ascending), tag(ascending) - tagM(ascending), scoreM(descending), boardID(ascending), tag(ascending) - tagY(ascending), scoreY(descending), boardID(ascending), tag(ascending) - tagA(ascending), scoreA(descending), boardID(ascending), tag(ascending)

"},{"location":"firebase-leaderboard/#post-score","title":"Post score","text":"
  1. Set user.
    leaderBoard.setUser(userID, userName);\n
    or
    leaderBoard.setUser({\nuserID: userID,\nuserName: userName\n});\n
    • userID : User ID.
    • userName : Display name of user, optional.
  2. Set board property, optional.
    • Board ID
      leaderBoard.setBoardID(boardID);\n
    • Custom tag
      leaderBoard.setTag(tag);\n
  3. Post score
    leaderBoard.post(score)\n// leaderBoard.post(score, extraData)\n// leaderBoard.post(score, extraData, timestamp)\n.then(function(record) { })\n.catch(function(error) { })\n
    • score : A number, scores will be sorted descend.
    • extraData : Extra data in JSON format.
    • timestamp : Timestamp of posting.
      • undefined : Current time.
      • A number : For debug usage.
"},{"location":"firebase-leaderboard/#get-my-score","title":"Get my score","text":"
leaderBoard.getScore()\n// leaderBoard.getScore(userID)\n.then(function(score) { })\n.catch(function(error) { })\n
  • userID : User ID, optional.
    • undefined : Current user ID.
  • score : Score object.
    • Time filter enabled : {userID, scoreD, scoreW, scoreM, scoreY, tagD, tagW, tagM, tagY, tagA}
      • scoreD, scoreW, scoreM, scoreY, scoreA : Score of day/week/month/year/all-time.
      • tagD, tagW, tagM, tagY, tagA : Time tag of day/week/month/year/all-time.
    • Time filter disabled : {userID, score}
"},{"location":"firebase-leaderboard/#get-my-rank","title":"Get my rank","text":"
leaderBoard.getRank()\n// leaderBoard.getRank(userID)\n.then(function(rank) { })\n.catch(function(error) { })\n
  • userID : User ID, optional.
    • undefined : Current user ID.
  • rank : Rank object. {userID, rank}
"},{"location":"firebase-leaderboard/#get-scores","title":"Get scores","text":"
  1. Set board property, optional.
    • Board ID
      leaderBoard.setBoardID(boardID);\n
    • Custom tag
      leaderBoard.setTag(tag);\n
  2. Set time filter, optional.
    leaderBoard.setTimeFilterType(type);\n
    • type :
      • 'day', or 'd' : Filter scores by current day.
      • 'week', or 'w' : Filter scores by current week.
      • 'month', 'm' : Filter scores by current month.
      • 'year', 'y' : Filter scores by current year.
      • 'all', 'a' : No time filter to track all scores.
  3. Load scores page by page.
    • Load first page.
      leaderBoard.loadFirstPage()\n.then(function(scores) { })\n.catch(function(error) { })\n
      • scores : An array of score object. Each score object is {userID, userName, socre}
    • Load next page.
      leaderBoard.loadNextPage()\n.then(function(scores) { })\n.catch(function(error) { })\n
      • scores : An array of score object. Each score object is {userID, userName, socre}
    • Load previous page.
      leaderBoard.loadPreviousPage()\n.then(function(scores) { })\n.catch(function(error) { })\n
      • scores : An array of score object. Each score object is {userID, userName, socre}
    • Reload current page.
      leaderBoard.loadCurrentPage()\n.then(function(scores) { })\n.catch(function(error) { })\n
      • scores : An array of score object. Each score object is {userID, userName, socre}
"},{"location":"firebase-leaderboard/#page-index","title":"Page index","text":"
  • Current page index
    var pageIndex = leaderBoard.pageIndex;\n
  • Is first page
    var isFirstPage = leaderBoard.isFirstPage;\n
  • Is last page
    var isLastPage = leaderBoard.isLastPage;\n
"},{"location":"firebase-leaderboard/#delete","title":"Delete","text":"
  • Delete user
    leaderBoard.deleteUserScore(userID)\n.then(function(){ })\n.catch(function(){ })\n
  • Delete board
    leaderBoard.deleteBoard(boardID, tag)\n.then(function(){ })\n.catch(function(){ })\n
"},{"location":"firebase-messages/","title":"Messages","text":""},{"location":"firebase-messages/#introduction","title":"Introduction","text":"

Store messages in firebase-firestore.

  • Author: Rex
"},{"location":"firebase-messages/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-messages/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-messages/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add leader-board object
    var messages = scene.plugins.get('rexfirebaseplugin').add.messages(config);\n
"},{"location":"firebase-messages/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add leader-board object
    var messages = scene.plugins.get('rexFirebase').add.messages(config);\n
"},{"location":"firebase-messages/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { Messages } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add leader-board object
    var messages = new Messages(config);\n
"},{"location":"firebase-messages/#create-instance","title":"Create instance","text":"
var messages = scene.plugins.get('rexFirebase').add.messages({\nroot: '',\n// pageItemCount: 100,\n\n// senderID: '',\n// senderName: '',\n// receiverID: undefined,\n});\n
  • root : Collection name of this messages.
  • pageItemCount : Item count of a page, default value is 100
  • senderID : ID of sender.
  • senderName : Name of sender, optional.
  • receiverID : ID of receiver, optional.
"},{"location":"firebase-messages/#send-message","title":"Send message","text":"
  1. Set sender.
    messages.setSender(userID, userName);\n
    or
    messages.setSender({\nuserID: userID,\nuserName: userName\n});\n
    • userID : User ID.
    • userName : Display name of user, optional.
  2. Set receiver, optional.
    messages.setReceiver(userID);\n
    • userID : User ID.
  3. Send message
    messages.send(message)    .then(function() { })\n.catch(function(error) { })\n
    • message : String, number, or JSON object.
"},{"location":"firebase-messages/#receive-messages","title":"Receive messages","text":"
  1. Set receiverID, optional.
    messages.setReceiver(userID)\n
    • userID : User ID.
  2. Load previous messages, optional.
    messages.loadPreviousMessages()\n.then(function(messageObjs) { })\n.catch(function(error) { })    
    • messageObjs : Array of Received message objects
      • messageObj.senderID, messageObj.senderName : Sernder ID and name.
      • messageObj.receiverID : Receiver ID, optional.
      • messageObj.message : Sent message, a string, number, or JSON object.
      • messageObj.timestamp : Server-timestamp.
  3. Add 'receiver' event.
    messages.on('receive', function(messageObj) {\n// var senderID = messageObj.senderID;\n// var senderName = messageObj.senderName;\n// var receiverID = messageObj.receiverID;\n// var message = messageObj.message;\n// var timestamp = messageObj.timestamp;\n})\n
    • messageObj : Received message object.
  4. Start receiving
    messages.startReceiving();\n
  5. Stop receiving
    messages.stopReceiving();\n

Received messages will be stored in messages.cacheMessages

"},{"location":"firebase-onlineuserlist/","title":"Online user list","text":""},{"location":"firebase-onlineuserlist/#introduction","title":"Introduction","text":"

Online user list, using firebase-database.

  • Author: Rex
"},{"location":"firebase-onlineuserlist/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-onlineuserlist/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-onlineuserlist/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add online-user-list object
    var userList = scene.plugins.get('rexfirebaseplugin').add.onlineUserList(config);\n
"},{"location":"firebase-onlineuserlist/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add online-user-list object
    var userList = scene.plugins.get('rexFirebase').add.onlineUserList(config);\n
"},{"location":"firebase-onlineuserlist/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { OnlineUserList } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add online-user-list object
    var userList = new OnlineUserList(config);\n
"},{"location":"firebase-onlineuserlist/#create-instance","title":"Create instance","text":"
var userList = scene.plugins.get('rexFirebase').add.onlineUserList({\nroot: '',\n// maxUsers: 0,\n\n// userID: '',\n// userName: '',\n});\n
  • root : Path of this online user list.
  • maxUsers: Maximum users in this list. Set to 0 to have infinity users.
  • userID : ID of user.
  • userName : Name of user.
"},{"location":"firebase-onlineuserlist/#join","title":"Join","text":"
  1. Set userID and user name.
    userList.setUser(userID, userName);\n
    or
    userList.setUser({\nuserID: userID,\nuserName: userName\n});\n
    • userID : User ID.
    • userName : Display name.
  2. Join list.
    userList.join()\n// .then(function() { })\n// .catch(function() { })\n
"},{"location":"firebase-onlineuserlist/#leave","title":"Leave","text":"
userList.leave()\n// .then(function() { })\n// .catch(function() { })\n
"},{"location":"firebase-onlineuserlist/#kick-user","title":"Kick user","text":"
userList.leave(userID)\n// .then(function() { })\n// .catch(function() { })\n
"},{"location":"firebase-onlineuserlist/#change-user-name","title":"Change user name","text":"
userList.changeUserName(newUserName)\n// .then(function() { })\n// .catch(function() { })\n
"},{"location":"firebase-onlineuserlist/#user-list","title":"User list","text":"
  • Get users in user list
    var users = userList.getUsers();\n
    • users : Array of user {userID, userName}
  • Is first user in user list?
    var isFirstUser = userList.isFirstUser(userID);\n// var isFirstUser = userList.isFirstUser();  // Current user is first user\n
  • User list is full
    var isFull = userList.isFull();\n
  • Maximun users setting value
    var maxUsers = userList.maxUsers;\n
  • Current user is in list
    var isInList = userList.isInList;\n
"},{"location":"firebase-onlineuserlist/#events","title":"Events","text":"
  • Any user join
    userList.on('join', user);\n
    • user : {userID, userName}
  • Any user leave
    userList.on('leave', user);\n
    • user : {userID, userName}
  • User list updated, includes user join, user leave, and user name changed
    userList.on('update', users);\n
    • users : Array of user {userID, userName}
  • User name is changed
    userList.on('changename', userID, userName, prevUserName);\n
"},{"location":"firebase-overview/","title":"Overview","text":""},{"location":"firebase-overview/#introduction","title":"Introduction","text":"
  • Home page
  • Available libraries
"},{"location":"firebase-overview/#usage","title":"Usage","text":""},{"location":"firebase-overview/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-overview/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n    <script src=\"/__/firebase/10.13/firebase-firestore-compat.js\"></script>        \n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Get firebase plugin
    var rexFireBase = scene.plugins.get('rexfirebaseplugin');\n
"},{"location":"firebase-overview/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Get firebase plugin
    var rexFireBase = scene.plugins.get('rexFirebase');\n
"},{"location":"firebase-singleroom/","title":"Single room","text":""},{"location":"firebase-singleroom/#introduction","title":"Introduction","text":"

Chat room, using firebase-database.

  • Author: Rex
"},{"location":"firebase-singleroom/#usage","title":"Usage","text":"

Sample code

"},{"location":"firebase-singleroom/#install-plugin","title":"Install plugin","text":""},{"location":"firebase-singleroom/#load-minify-file","title":"Load minify file","text":"
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfirebaseplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add single-room object
    var room = scene.plugins.get('rexfirebaseplugin').add.singleRoom(config);\n
"},{"location":"firebase-singleroom/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Install plugin in configuration of game
    import FirebasePlugin from 'phaser3-rex-plugins/plugins/firebase-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFirebase',\nplugin: FirebasePlugin,\nstart: true\n}]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Add single-room object
    var room = scene.plugins.get('rexFirebase').add.singleRoom(config);\n
"},{"location":"firebase-singleroom/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add Firebase SDKs
    <body>\n    <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->\n    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->\n    <script src=\"/__/firebase/10.13/firebase-app-compat.js\"></script>\n    <!-- Add Firebase products that you want to use -->\n    <script src=\"/__/firebase/10.13/firebase-database-compat.js\"></script>\n</body>    \n
  • Initialize firebase application.
    firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n})\n
  • Import class
    import { SingleRoom } from 'phaser3-rex-plugins/plugins/firebase-components.js';\n
  • Add single-room object
    var room = new SingleRoom(config);\n
"},{"location":"firebase-singleroom/#create-instance","title":"Create instance","text":"
var room = scene.plugins.get('rexFirebase').add.singleRoom({\nroot: '',\n// maxUsers: 0,\n// userID: '',\n// userName: '',\n// broadcast: true,\n// tables: undefined,\n\n});\n
  • root : Path of this room.
  • maxUsers: Maximum users in this list. Set to 0 to have infinity users.
  • userID : ID of user.
  • userName : Name of user.
  • broadcast : Broadcast chat messages.
    • true : Enable broadcasting, without storing received (history) messages. Default behavior.
    • false : Disable broadcasting.
    • A JSON object :
      {\nhistory: 0\n}\n
      • history : Stored received (history) messages in client side.
        • 0, or false : No history message stored.
        • -1, or true : Infinity history message stored. i.e. store all messages from starting updating.
        • A number larger then 0 : Length of stored history message.
  • tables : Configuration of tables.
    • undefined : No table.
    • Array of table-config JSON object for each table.
      [\n{\nkey: tableKey,\ntype: '1d'\n},\n{\n...\n}\n]\n
      • key : Unique name of this table.
      • type : Table type.
        • 1, or '1d' : 1d table, indexing by (key0)
        • 2, or '2d' : 2d table, indexing by (key0, key1)
        • 3, or '3d' : 3d table, indexing by (key0, key1, key2)
"},{"location":"firebase-singleroom/#current-user-infomation","title":"Current user infomation","text":"
  • User name
    • Get
      var userName = room.userInfo.userName;\n
    • Set
      room.changeUserName(newUserName);\n
  • User ID
    • Get
      var userID = room.userInfo.userID;\n
"},{"location":"firebase-singleroom/#join-room","title":"Join room","text":"
  1. Set userID and user name.
    room.setUser(userID, userName);\n
    • userID : User ID.
    • userName : Display name.
  2. Join room.
    room.joinRoom();\n
"},{"location":"firebase-singleroom/#leave-room","title":"Leave room","text":"
room.leaveRoom();\n
"},{"location":"firebase-singleroom/#kick-user","title":"Kick user","text":"
room.kickUser(userID);\n
"},{"location":"firebase-singleroom/#user-list","title":"User list","text":"
  • Get users in room(user list)
    var users = room.getUsers();\n
    • users : Array of user {userID, userName}
  • Is first user in room(user list)?
    var isFirstUser = room.isFirstUser(userID);\n// var isFirstUser = room.isFirstUser();  // Current user is first user\n
  • Room(user list) is full
    var isFull = room.isFull();\n
  • Maximun users setting value
    var maxUsers = room.maxUsers;\n
  • Current user is in room(user list)
    var isInRoom = room.isInRoom();\n
"},{"location":"firebase-singleroom/#send-message","title":"Send message","text":"
room.broadcast.send(message);\n
  • message : A string message, or a JSON data.
"},{"location":"firebase-singleroom/#receive-messages","title":"Receive messages","text":"
  1. Register receive event
    room.on('broadcast.receive', function(data){\n// var senderID = data.senderID;\n// var senderName = data.senderName;\n// var message = data.message;\n})\n

Only receive messages after joined room. Previous messages won't be got anymore.

"},{"location":"firebase-singleroom/#received-messages","title":"Received messages","text":"

Received messages will be saved in client side.

  • Get received (history) messages.
    var messages = room.broadcast.getHistory();\n
  • Clear history messages.
    room.broadcast.clearHistory();\n
"},{"location":"firebase-singleroom/#tables","title":"Tables","text":"
  • Get table
    var table = room.getTable(key);\n
    • key : Unique name of this table.
"},{"location":"firebase-singleroom/#write","title":"Write","text":"

See here

"},{"location":"firebase-singleroom/#read","title":"Read","text":"

See here

"},{"location":"firebase-singleroom/#events","title":"Events","text":""},{"location":"firebase-singleroom/#user-list-events","title":"User list events","text":"
  • Any user join
    room.on('userlist.join', user);\n
    • user : {userID, userName}
  • Any user leave
    room.on('userlist.leave', user);\n
    • user : {userID, userName}
  • User list updated, includes user join, user leave, and user name changed
    room.on('userlist.update', users);\n
    • users : Array of user {userID, userName}
  • User name is changed
    room.on('userlist.changename', userID, userName, prevUserName);\n
"},{"location":"firebase-singleroom/#broadcast-events","title":"Broadcast events","text":"
  • Receive message
    room.on('broadcast.receive', function(data){\n// var senderID = data.senderID;\n// var senderName = data.senderName;\n// var message = data.message;\n})\n
"},{"location":"firebase-singleroom/#table-events","title":"Table events","text":"

Event names of each table indexed by key

  • init : tables.${key}.init
  • update : tables.${key}.update
  • addkey0 : tables.${key}.addkey0
  • removekey0 : tables.${key}.removekey0
  • changekey0 : tables.${key}.changekey0
  • addkey1 : tables.${key}.addkey1
  • removekey1 : tables.${key}.removekey1
  • changekey1 : tables.${key}.changekey1
  • addkey2 : tables.${key}.addkey2
  • removekey2 : tables.${key}.removekey2
  • changekey2 : tables.${key}.changekey2
"},{"location":"firebase-storage/","title":"Storage","text":""},{"location":"firebase-storage/#introduction","title":"Introduction","text":"

It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.

  • Author: Firebase
"},{"location":"firebase-storage/#usage","title":"Usage","text":"

Official document

Sample code

"},{"location":"firebase-storage/#setup","title":"Setup","text":"
  1. Import firestore
    import firebase from 'firebase/app';\nimport 'firebase/storage';\n
    Firebase has been included in package.json.
  2. Initialize
    var firebaseApp = firebase.initializeApp({\napiKey: '...',\nauthDomain: '...',\ndatabaseURL: '...',\nprojectId: '...',\nstorageBucket: '...',\nmessagingSenderId: '...'\n});\nvar storageRef = firebaseApp.storage().ref();\n
"},{"location":"firebase-storage/#upload-string","title":"Upload string","text":"
  • Upload string
    var fileRef = storageRef.child('path/to/filename');\nvar uploadTask = fileRef.putString(content)\n.then(function (snapshot) {})\n.catch(function (error) {});\n
  • Upload base64 formatted string
    var fileRef = storageRef.child('path/to/filename');\nvar uploadTask = fileRef.putString(content, 'base64')\n.then(function (snapshot) {})\n.catch(function (error) {});\n
  • Upload base64url formatted string
    var fileRef = storageRef.child('path/to/filename');\nvar uploadTask = fileRef.putString(content, 'base64url')\n.then(function (snapshot) {})\n.catch(function (error) {});\n
  • Upload data URL string
    var fileRef = storageRef.child('path/to/filename');\nvar uploadTask = fileRef.putString(content, 'data_url')\n.then(function (snapshot) {})\n.catch(function (error) {});\n
"},{"location":"firebase-storage/#upload-image","title":"Upload image","text":"
  1. Get image from image texture
    var image = scene.textures.get(key).getSourceImage();\n
  2. Copy image to canvas
    var canvas = CanvasPool.create(scene, image.width, image.height);\nvar ctx = canvas.getContext('2d');\nctx.drawImage(image, 0, 0, image.width, image.height);\n
  3. Get blob from canvas, then upload this blob.
    var uploadTask;\ncanvasToBlob(canvas)\n.then(function(blob) {\nvar metadata = {\ncontentType: 'image/jpeg',\n};        var fileRef = storageRef.child('path/to/filename');\nuploadTask = fileRef.put(blob, metadata);\nreturn uploadTask;\n})\n.then(function (snapshot) {})\n.catch(function (error) {});\n
    Reference: canvasToBlob
  4. Free canvas
    CanvasPool.remove(canvas);\n
"},{"location":"firebase-storage/#upload-task","title":"Upload task","text":"
  • Pause task
    uploadTask.pause();\n
  • Resume task
    uploadTask.resume();\n
  • Cancel task
    uploadTask.cancel();\n
  • Monitor progress
    uploadTask.on('state_changed', function(snapshot){\n// Observe state change events such as progress, pause, and resume\nvar progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;\nswitch (snapshot.state) {\ncase firebase.storage.TaskState.PAUSED: // or 'paused'\nconsole.log('Upload is paused');\nbreak;\ncase firebase.storage.TaskState.RUNNING: // or 'running'\nconsole.log('Upload is running');\nbreak;\n}\n},\nfunction(error) {\n// Handle unsuccessful uploads\n// https://firebase.google.com/docs/storage/web/handle-errors\nswitch (error.code) {\ncase 'storage/unauthorized':\n// User doesn't have permission to access the object\nbreak;\ncase 'storage/canceled':\n// User canceled the upload\nbreak;\ncase 'storage/unknown':\n// Unknown error occurred, inspect error.serverResponse\nbreak;\n}\n},\nfunction() {\n// Handle successful uploads on complete\n// Get download url\nuploadTask.snapshot.ref.getDownloadURL()\n.then(function(url) {\nconsole.log('File available at', url);\n})\n.catch(function (error) {});\n}\n);\n
"},{"location":"firebase-storage/#download-file","title":"Download file","text":"
  1. Get download url
    var fileRef = storageRef.child('path/to/filename');\nfileRef.getDownloadURL()\n.then(function(url) {})\n.catch(function (error) {});\n
  2. Download file by loader
"},{"location":"firebase-storage/#delete-file","title":"Delete file","text":"
var fileRef = storageRef.child('path/to/filename');\nfileRef.delete()\n.then(function() {})\n.catch(function(error) {});\n
"},{"location":"flash/","title":"Flash","text":""},{"location":"flash/#introduction","title":"Introduction","text":"

Flashing (set invisible then visible) game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"flash/#usage","title":"Usage","text":"

Sample code

"},{"location":"flash/#install-plugin","title":"Install plugin","text":""},{"location":"flash/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexflashplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexflashplugin.min.js', true);\n
  • Add flash behavior
    var flash = scene.plugins.get('rexflashplugin').add(gameObject, config);\n
"},{"location":"flash/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FlashPlugin from 'phaser3-rex-plugins/plugins/flash-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFlash',\nplugin: FlashPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add flash behavior
    var flash = scene.plugins.get('rexFlash').add(gameObject, config);\n
"},{"location":"flash/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Flash from 'phaser3-rex-plugins/plugins/flash.js';\n
  • Add flash behavior
    var flash = new Flash(gameObject, config);\n
"},{"location":"flash/#create-instance","title":"Create instance","text":"
var flash = scene.plugins.get('rexFlash').add(gameObject, {\n// duration: 500,\n// repeat: 2\n});\n
  • duration : Duration of invisible(50%) and visible(50%), in millisecond.
  • repeat : The number of times the flashing will repeat itself (a value of 1 means the flash will play twice, as it repeated once)
"},{"location":"flash/#start-flashing","title":"Start flashing","text":"
flash.flash();\n// flash.flash(duration, repeat);\n

or

flash.flash({\nduration: 500,\nrepeat: 2\n});\n
"},{"location":"flash/#stop-flashing","title":"Stop flashing","text":"
flash.stop();\n
"},{"location":"flash/#enable","title":"Enable","text":"
  • Enable/resume (default)
    flash.setEnable();\n
    or
    flash.enable = true;\n
  • Disable/pause
    flash.setEnable(false);\n
    or
    flash.enable = false;\n
"},{"location":"flash/#set-duration","title":"Set duration","text":"
flash.setDuration(duration);\n// flash.duration = duration;\n
"},{"location":"flash/#set-repeat","title":"Set repeat","text":"
flash.setRepeat(repeat);\n// flash.repeat = repeat;\n
"},{"location":"flash/#events","title":"Events","text":"
  • On reached target
    flash.on('complete', function(flash, gameObject){});\n
"},{"location":"flash/#status","title":"Status","text":"
  • Is flashing
    var isRunning = flash.isRunning;\n
"},{"location":"flip/","title":"Flip","text":""},{"location":"flip/#introduction","title":"Introduction","text":"

Flipping game object to another face by scaling width/height.

  • Author: Rex
  • Behavior of game object
"},{"location":"flip/#live-demos","title":"Live demos","text":"
  • Flip image
  • Flip ui
"},{"location":"flip/#usage","title":"Usage","text":"

Sample code, Sample code-2

"},{"location":"flip/#install-plugin","title":"Install plugin","text":""},{"location":"flip/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexflipplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexflipplugin.min.js', true);\n
  • Add flip behavior
    var flip = scene.plugins.get('rexflipplugin').add(gameObject, config);\n
"},{"location":"flip/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FlipPlugin from 'phaser3-rex-plugins/plugins/flip-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFlip',\nplugin: FlipPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add flip behavior
    var flip = scene.plugins.get('rexFlip').add(gameObject, config);\n
"},{"location":"flip/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Flip from 'phaser3-rex-plugins/plugins/flip.js';\n
  • Add flip behavior
    var flip = new Flip(gameObject, config);\n
"},{"location":"flip/#create-instance","title":"Create instance","text":"
var flip = scene.plugins.get('rexFlip').add(gameObject, {\nface: 'back',\nfront: { key, frame }, // key, or callback\nback: { key, frame },  // key, or callback\n\n// orientation: 0, // 0|'x'|1|'y'\n// duration: 500,\n// delay: 0,\n// ease: 'Sine',\n});\n
  • face : Initial face.
    • 0, 'front' : Front face.
    • 1, 'back' : Back face.
  • front, back : Texture of front/back face.
    • undefined : Use current texture key, or frame name
    • key : A string for texture key.
    • {key, frame}, or {frame} : A texture key and frame name
    • callback : Configure game object via callback.
      function(gameObject) {\n}\n
  • orientation : Flipping orientation.
    • 0, 'x', or 'horizontal' : Horizontal flipping.
    • 1, 'y', or 'vertical' : Vertical flipping.
  • duration : Duration of flipping, in millisecond.
  • delay : Initial delay
  • ease Ease function. Default value is 'Sine'.
"},{"location":"flip/#start-flipping","title":"Start flipping","text":"
flip.flip();\n// flip.flip(duration);\n
"},{"location":"flip/#stop-flipping","title":"Stop flipping","text":"
flip.stop();\n
"},{"location":"flip/#set-duration","title":"Set duration","text":"
flip.setDuration(duration);\n// flip.duration = duration;\n
"},{"location":"flip/#set-ease","title":"Set ease","text":"
flip.setEase(ease);\n// flip.ease = ease;\n
"},{"location":"flip/#faces","title":"Faces","text":""},{"location":"flip/#current-face","title":"Current face","text":"
  • Get
    var face = flip.face;\n
    • 0 : Front face
    • 1 : Back face
  • Set
    flip.setFace(face);\n// flip.face = face;\n
    • 0, 'front' : Front face.
    • 1, 'back' : Back face.
  • Toggle face
    flip.toggleFace();\n
"},{"location":"flip/#set-texture-of-face","title":"Set texture of face","text":"
  • Front face
    flip.setFrontFace(key, frame);\n
    or
    flip.setFrontFace(callback);\n
    • callback :
      function(gameObject) {\n// ...\n}\n
  • Back face
    flip.setBackFace(key, frame);\n
    or
    flip.setBackFace(callback);\n
    • callback :
      function(gameObject) {\n// ...\n}\n
"},{"location":"flip/#events","title":"Events","text":"
  • On flipping complete
    flip.on('complete', function(gameObject, flip){\n// ...\n});\n
"},{"location":"flip/#status","title":"Status","text":"
  • Is flipping
    var isRunning = flip.isRunning;\n
"},{"location":"format/","title":"Format","text":""},{"location":"format/#introduction","title":"Introduction","text":"

Format string with variables, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"format/#usage","title":"Usage","text":"

Replace %x from an array. x starts from 1.

// const Format = Phaser.Utils.String.Format;\nvar template = 'hello, %1';\nvar view = ['rex'];\nvar result = Format(template, view);\n
"},{"location":"framemanager/","title":"Frame manager","text":""},{"location":"framemanager/#introduction","title":"Introduction","text":"

Draw frames on canvas texture, or dynamic texture.

  • Author: Rex
  • Member of scene
"},{"location":"framemanager/#live-demos","title":"Live demos","text":"
  • Paste text
"},{"location":"framemanager/#usage","title":"Usage","text":"

Sample code

"},{"location":"framemanager/#install-plugin","title":"Install plugin","text":""},{"location":"framemanager/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexframemanagerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexframemanagerplugin.min.js', true);\n
  • Add frame-manager object
    var frameManager = scene.plugins.get('rexframemanagerplugin').add(scene, config);\n
"},{"location":"framemanager/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FrameManagerPlugin from 'phaser3-rex-plugins/plugins/framemanager-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFrameManager',\nplugin: FrameManagerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add frame-manager object
    var frameManager = scene.plugins.get('rexFrameManager').add(scene, config);\n
"},{"location":"framemanager/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import FrameManager from 'phaser3-rex-plugins/plugins/framemanager.js';\n
  • Add frame-manager object
    var frameManager = new FrameManager(scene, config);\n
"},{"location":"framemanager/#create-instance","title":"Create instance","text":"
var frameManager = scene.plugins.get('rexFrameManager').add(scene, {\nkey: '',\nwidth: 4096,\nheight: 4096,\ncellWidth: 64,\ncellHeight: 64,\ncellPadding: 0,\ncolumns: undefined,\nrows: undefined,\nfillColor: undefined,\nuseDynamicTexture: false,\n});\n
  • key : Texture key in texture manager
  • width, height : Size of canvas.
    • Calculate width/height by columns/rows and cellWidth/cellHeight, if columns, rows parameters are given.
  • columns, rows :
    • undefined : Calculate columns/rows by width/height and cellWidth/cellHeight.
  • cellWidth, cellHeight : Maximum frame size.
  • cellPadding : Extra space around frame. Default value is 0.
    • Total cell width will be cellWidth + (cellPadding * 2)
    • Total cell height will be cellHeight + (cellPadding * 2)
  • fillColor : Fill an initial color, in css color string (for canvas-texture), or number (for dynamic-texture)
    • undefined : Don't fill color.
  • useDynamicTexture
    • false : Use canvas-texture. Default behavior.
    • true : Use dynamic-texture.

or

var frameManager = scene.plugins.get('rexFrameManager').add(scene, key, width, height, cellWidth, cellHeight, fillColor, useDynamicTexture);\n

Steps of generating bitmapfont :

  1. Add frames :
    frameManager.paste(frameName, gameObject);\n
  2. Update texture
    frameManager.updateTexture();\n
  3. Export frame data to bitmapfont
    frameManager.addToBitmapFont();\n
"},{"location":"framemanager/#add-frame","title":"Add frame","text":""},{"location":"framemanager/#from-game-object","title":"From game object","text":"

After rendering content on text, bbcode text, canvas

frameManager.paste(frameName, gameObject);\n
  • frameName : Frame name.
  • gameObject :
    • Canvas-texture mode :
      • Game objects which has canvas, for example, text, bbcode text, or canvas.
    • Dynamic-texture mode :
      • Any render-able game object except :
        • Graphics can't paste directly, because that Graphics game object does not have size.
          • Draw Graphics to RenderTexture, then paste this RenderTexture to frameMamager.
"},{"location":"framemanager/#custom-drawing","title":"Custom drawing","text":"

frameManager.draw(frameName, callback, scope)\n
- frameName : Frame name. - callback : - Canvas-texture mode :
function(canvas, context, frameSize) {\n// The maximum frame size\nvar cellWidth = frameSize.width;\nvar cellHeight = frameSize.height;\n\n// Draw content in area of (0, 0) - (cellWidth, cellHeight)\n\n// Update frame size\n// frameSize.width = ...\n// frameSize.height = ...\n}\n
- Dynamic-texture mode :
function(texture, frameSize) {\n// The maximum frame size\nvar cellWidth = frameSize.width;\nvar cellHeight = frameSize.height;\n\n// Draw content in area of (0, 0) - (cellWidth, cellHeight)\n\n// Update frame size\n// frameSize.width = ...\n// frameSize.height = ...\n}\n

"},{"location":"framemanager/#empty-frame","title":"Empty frame","text":"
frameManager.addEmptyFrame(frameName);\n// frameManager.addEmptyFrame(frameName, width, height);\n
  • frameName : Frame name.
  • width : Frame width, default value is cellWidth
  • height : Frame height, default value is cellHeight
"},{"location":"framemanager/#update-texture","title":"Update texture","text":"

Update texture after adding frames, for Canvas-texture mode.

frameManager.updateTexture();\n

Do nothing in Dynamic-texture mode.

"},{"location":"framemanager/#remove-frame","title":"Remove frame","text":"
  • Remove a frame
    frameManager.remove(frameName);\n
    • frameName : Frame name.
  • Remove all frames
    frameManager.clear();\n

Remove frame data but won't clear texture image.

"},{"location":"framemanager/#export-to-bitmapfont","title":"Export to bitmapfont","text":"
frameManager.addToBitmapFont();\n
"},{"location":"framemanager/#destroy-instance","title":"Destroy instance","text":"
frameManager.destroy();\n
"},{"location":"fsm/","title":"FSM","text":""},{"location":"fsm/#introduction","title":"Introduction","text":"

Finite state machine.

  • Author: Rex
  • Object
"},{"location":"fsm/#usage","title":"Usage","text":"

Sample code

"},{"location":"fsm/#install-plugin","title":"Install plugin","text":""},{"location":"fsm/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfsmplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfsmplugin.min.js', true);\n
  • Add FSM object
    var states = scene.plugins.get('rexfsmplugin').add(config);\n
"},{"location":"fsm/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FSMPlugin from 'phaser3-rex-plugins/plugins/fsm-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFSM',\nplugin: FSMPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add FSM object
    var states = scene.plugins.get('rexFSM').add(config);\n
"},{"location":"fsm/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import FSM from 'phaser3-rex-plugins/plugins/fsm.js';\n
  • Add FSM object
    var states = new FSM(config);\n
"},{"location":"fsm/#create-instance","title":"Create instance","text":""},{"location":"fsm/#create-by-config","title":"Create by config","text":"
var states = scene.plugins.get('rexFSM').add({\nstart: 'A',   // default: undefined\nstates: {\nA: {\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},                 // this: this fsm instance\nexit: function() {},                  // this: this fsm instance\nupdate: function(time, delta) {},     // this: this fsm instance\npreupdate: function(time, delta) {},  // this: this fsm instance\npostupdate: function(time, delta) {}, // this: this fsm instance\n},\n// ...\n},\ninit: function() {},   // this: this fsm instance\nextend: {\ni: 0,        // Add member `i` into this fsm instance\nname: 'abc'\n// ...\n},\nenable: true,\nscene: undefined,\neventEmitter: undefined\n});\n
  • start: Initial state.
  • states: Define states.
    • stateName
      • next: String of next state, or a callback to get next state.
      • enter: Callback when enter state.
        function() {\n// this : this fsm instance\n}\n
      • exit: Callback when exit state. javascript function() { // this : this fsm instance }
      • update, preupdate, postupdate : Callback invoked by scene's 'update', 'preupdate', 'postupdate' events.
        function(time, delta) {\n// this : this fsm instance\n}\n
  • init: Initial callback when creating instance.
    function() {\n// this : this fsm instance\n}\n
  • extend: Inject key-value pairs into this fsm instance.
  • enable: Set false to block any state changing.
  • scene : Scene object for startUpdate, startPreUpdate, startPostUpdate method. Optional.
  • eventEmitter
    • undefined : Create a private event emitter, default value.
    • false : Don't add any event emitter, i.e. no event will be fired.
    • Event emitter object : Fire event through this event emitter.
"},{"location":"fsm/#inheritance","title":"Inheritance","text":"
  1. Create new class
    class State extends FSM {\nconstructor() {\nsuper();\n}\n\nnext_A() { return 'B' }\n\nenter_A() { }\n\nexit_A() { }\n\nupdate_A(time, delta) { }\npreupdate_A(time, delta) { }\npostupdate_A(time, delta) { }\n}\n
    Members: - next_ + stateName : Callback to get next state. - enter_ + stateName : Callback when enter state. - exit_ + stateName : Callback when exit state. - update_ + stateName, preupdate_ + stateName, postupdate_ + stateName : Callback invoked by scene's 'update', 'preupdate', 'postupdate' events.
  2. Create instance
    var states = new State();\n
"},{"location":"fsm/#read-state","title":"Read state","text":"
  • Current state
    var curState = states.state;\n
  • Previous state
    var preState = states.prevState;\n
"},{"location":"fsm/#start-at-state","title":"Start at state","text":"
states.start(newState);\n

Note

Set new state without triggering any state-changing callbacks or events.

"},{"location":"fsm/#next-state","title":"Next state","text":"
graph TB\n\nnext[\"states.next()\"] --> next_A[\"states.next_A()<br>return 'B'\"]\n\nnext_A --> eventStateChange[\"states.emit('statechange', states)<br>states.prevState -> states.state\"]\n\nsubgraph State changing\n\neventStateChange --> exit_A[\"states.exit_A()\"]\nexit_A --> eventExitA[\"states.emit('exit_A', states)\"]\n\neventExitA --> enter_B[\"states.enter_B()\"]\nenter_B --> eventEnterB[\"states.emit('enter_B', states)\"]\n\nsubgraph Exit\nexit_A\neventExitA\nend\n\nsubgraph Enter\nenter_B\neventEnterB\nend\n\nend\n\ngoto[\"states.goto('B')\"] --> eventStateChange\n\nsubgraph Request\n\nsubgraph Next\nnext\nnext_A\nend\n\nsubgraph Goto\ngoto\nend\n\nend
"},{"location":"fsm/#request","title":"Request","text":"
  • Get next state by callback
    states.next();    // nextState = states.next_A()    \n
  • Goto state
    states.goto(nextState);\n// states.state = nextState;\n
"},{"location":"fsm/#state-changing","title":"State-changing","text":"

These callbacks or events will be triggered if state is changing.

For example, state is changing from 'A' to 'B'.

  1. event statechange
    states.on('statechange', function(states) {\nconsole.log( states.prevState + '->' + states.state );\n});\n
  2. callback states.exit_A
  3. event exit_A
    states.on('exit_A', function(states) {\n/*...*/\n});\n
  4. callback states.enter_B
  5. event enter_B
    states.on('enter_B', function(states) {\n/*...*/\n});\n
"},{"location":"fsm/#enable","title":"Enable","text":"
states.setEnable();\n// states.setEnable(false); // disable\n

or

states.toggleEnable();\n

states.next() and states.goto() will be ignored if disabled.

"},{"location":"fsm/#update","title":"Update","text":"
  • Start
    states.startUpdate();\nstates.startPreUpdate();\nstates.startPostUpdate();\n// Assume that `scene` is assigned in config of constructor\n
    or
    states.startUpdate(scene);\nstates.startPreUpdate(scene);\nstates.startPostUpdate(scene);\n
    • scene : Scene object
  • Stop
    states.stopUpdate();\nstates.stopPreUpdate();\nstates.stopPostUpdate();\n
"},{"location":"fsm/#add-new-state","title":"Add new state","text":"

states.addState(name, {\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {},\nupdate: function(time, delta) {},\npreupdate: function(time, delta) {},\npostupdate: function(time, delta) {},\n})\n
states.addState({\nname: 'A',\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {},\nupdate: function(time, delta) {},\npreupdate: function(time, delta) {},\npostupdate: function(time, delta) {},\n})\n

or

states.addStates({\n'A' : {\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {},\nupdate: function(time, delta) {},\npreupdate: function(time, delta) {},\npostupdate: function(time, delta) {},\n},\n// ...\n})\n
states.addStates([\n{\nname: 'A',\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {},\nupdate: function(time, delta) {},\npreupdate: function(time, delta) {},\npostupdate: function(time, delta) {},\n},\n// ...\n]);\n

"},{"location":"fullscreen/","title":"Full screen","text":""},{"location":"fullscreen/#introduction","title":"Introduction","text":"

Enable or disable full screen mode, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"fullscreen/#usage","title":"Usage","text":""},{"location":"fullscreen/#enabledisable","title":"Enable/disable","text":"

Under any input event (touch or keyboard)

gameObject.setInteractive().on('pointerdown', function() {\nif (scene.scale.isFullscreen) {\nscene.scale.stopFullscreen();\n// On stop fulll screen\n} else {\nscene.scale.startFullscreen();\n// On start fulll screen\n}\n});\n

Fire one of these events

  • 'fullscreenunsupported' : Tried to enter fullscreen mode, but it is unsupported by the browser.
  • 'enterfullscreen' : Entered fullscreen mode successfully.
  • 'fullscreenfailed' : Tried to enter fullscreen mode but failed.
"},{"location":"fullscreen/#toggle","title":"Toggle","text":"

Under any input event (touch or keyboard)

gameObject.setInteractive().on('pointerdown', function() {\nscene.scale.toggleFullscreen();\nif (scene.scale.isFullscreen) {\n// On start fulll screen\n} else {\n// On stop fulll screen\n}\n});\n
  • Fire 'fullscreenunsupported' or 'enterfullscreen' event.
"},{"location":"fullscreen/#state","title":"State","text":"
  • Is in full screen mode
    var isFullScreen = scene.scale.isFullscreen;\n
  • Support full screen
    var supported = Phaser.Device.Fullscreen.available;\n
"},{"location":"fullscreen/#events","title":"Events","text":"
  • Full screen mode unsupported
    scene.scale.on('fullscreenunsupported', function() {});\n
  • Enter full screen mode
    scene.scale.on('enterfullscreen', function() {});\n
"},{"location":"fullscreen/#with-dom-game-object","title":"With DOM game object","text":"

Set gameConfig.fullscreenTarget to parent id.

var config = {\nparent: parentDivID,\nfullscreenTarget: parentDivID\n};\n\nvar game = new Phaser.Game(config);\n
"},{"location":"fuzzy/","title":"Fuzzy","text":""},{"location":"fuzzy/#introduction","title":"Introduction","text":"

A wrap of fuzzy logic (MIT license).

  • Author of wrap : Rex , Core API : Michael Herzog
  • Member of scene, or game object
"},{"location":"fuzzy/#live-demos","title":"Live demos","text":"
  • Fuzzy
"},{"location":"fuzzy/#usage","title":"Usage","text":"

Sample code

"},{"location":"fuzzy/#install-plugin","title":"Install plugin","text":""},{"location":"fuzzy/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfuzzyplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfuzzyplugin.min.js', true);\n
  • Add fuzzy module object
    var fuzzyModule = scene.plugins.get('rexfuzzyplugin').add(config);\n
"},{"location":"fuzzy/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GashaponPlugin from 'phaser3-rex-plugins/plugins/fuzzy-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGashapon',\nplugin: GashaponPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add fuzzy module object
    var fuzzyModule = scene.plugins.get('rexFuzzy').add(config);\n
"},{"location":"fuzzy/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import BuildFuzzyModule from 'phaser3-rex-plugins/plugins/fuzzy.js';\n
  • Add fuzzy module object
    var fuzzyModule = BuildFuzzyModule(config);\n
"},{"location":"fuzzy/#create-instance","title":"Create instance","text":"
var fuzzyModule = scene.plugins.get('rexFuzzy').add(`\n// Declare fuzzy sets\nFuzzySetName : left, middle, right, setType\nFuzzySetName : left, middle, right\nFuzzySetName : left, right\n\n// Declare rules\nFuzzySetNameA => FuzzySetNameT\nFuzzySetNameA and FuzzySetNameB => FuzzySetNameT\nFuzzySetNameA or FuzzySetNameB => FuzzySetNameT\nFuzzySetNameA or (FuzzySetNameA and FuzzySetNameB) => FuzzySetNameT\n\n// More comment lines...\n`);\n
  • config can be a multiple lines string, or a plain object
    • A multiple lines string contains
      • FuzzySetName : left, middle, right, setType : A line with ':', declare a fuzzy set.
        • FuzzySetName : Fuzzy set name in one of these format
          • Variable name with postfix '+', or '-'. For example, HP-, HP, HP+, HP--, HP++, the variable name is HP.
          • variableName.setName. For example, DIST.near, DIST.middle, DIST.far, the variable name is DIST.
            • Variable name and set name are composed of number(0-9) or English characters (A-Za-z).
        • left, middle, right : Left, middle, right point of fuzzy set, in numbers.
          • left, right : Two numbers for left and right point, middle point is the average of (left + right).
        • setType :
          • Can be one of these string, or none.
            • Left part : leftShoulder, leftSCurve.
              • Default value is leftShoulder for first fuzzy set of a variable.
            • Right part : rightShoulder, rightSCurve.
              • Default value is rightShoulder for last fuzzy set of a variable.
            • Middle parts : triangular, singleton, normal.
              • Default value is triangular for other fuzzy sets of a variable.
      • FuzzySetNameA and FuzzySetNameB => FuzzySetNameT : A line with '=>', declare a fuzzy rule.
      • // ... : Comment lines
    • A plain object
      {\nvariables: {\nVariableName: [\n{\nname: leftSetName, setType: undefined,\nparameters: [left, middle, right]\n},\n{\nname: middleSetName, setType: undefined,\nparameters: [left, middle, right]\n},\n{\nname: rightSetName, setType: undefined,\nparameters: [left, middle, right]\n},\n],\n// ....\n},\n\nrules: [\n'FuzzySetNameA => FuzzySetNameT',\n'FuzzySetNameA and FuzzySetNameB => FuzzySetNameT',\n'FuzzySetNameA or FuzzySetNameB => FuzzySetNameT',\n// ...\n]\n\n}\n
"},{"location":"fuzzy/#set-input","title":"Set input","text":"
fuzzyModule.fuzzify(variableName, value);\n
  • variableName : An antecedent variable name string.
  • value : A number.

or

fuzzyModule.fuzzify({\nvarName: value,\n});\n
"},{"location":"fuzzy/#get-result","title":"Get result","text":"
var result = fuzzyModule.defuzzify(variableName);\n
  • variableName : A consequence variable name string.

or

var result = fuzzyModule.defuzzify([varName0, varName1, ...]);\n
  • result : {varName0: value0, varName1, value1, ...}

or

var result = fuzzyModule.defuzzify();\n
  • result : {varName0: value0, varName1, value1, ...}
    • Grab variable names from all consequence of rules.
"},{"location":"game/","title":"Game","text":""},{"location":"game/#boot","title":"Boot","text":"
var config = {\ntype: Phaser.AUTO,\nparent: null,\nwidth: 1024,\nheight: 768,\nscale: {\nmode: Phaser.Scale.FIT,\nautoCenter: Phaser.Scale.CENTER_BOTH\n},\n\nscene: null\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"game/#configuration","title":"Configuration","text":"

Reference

{\ntype: Phaser.AUTO,\nparent: 'phaser-example',\nwidth: 800,\nheight: 600,\nscale: {\nmode: Phaser.Scale.FIT,\nautoCenter: Phaser.Scale.CENTER_BOTH\n},\ndom: {\ncreateContainer: false,\n},\nscene: null,\nbackgroundColor: 0x333333\n}\n

or

{\ntype: Phaser.AUTO,\nparent: null,\nwidth: 800,\nheight: 600,\n\nscale: {\nmode: Phaser.Scale.NONE,\nautoCenter: Phaser.Scale.NO_CENTER,\nresizeInterval: 500,\n// width:\n// height:\n// zoom:\n// parent:\nexpandParent: true.\n// min: {width: 0, height: 0},\n// max: {width: 0, height: 0},\n// snap: {width: 0, height: 0},\n// autoRound: false,\nfullscreenTarget: null,\n},\n\nautoRound: false,\ncanvas: null,\ncanvasStyle: null,\n\nscene: null,\n\ncallbacks: {\npreBoot: NOOP,\npostBoot: NOOP\n},\n\nseed: [ (Date.now() * Math.random()).toString() ],\n\ntitle: '',\nurl: 'https://phaser.io',\nversion: '',\n\nautoFocus: true,\ninput: {\nkeyboard: {\ntarget: window\n},\nmouse: {\ntarget: null,\ncapture: true\n},\nactivePointers: 1,\ntouch: {\ntarget: null,\ncapture: true\n},\nsmoothFactor: 0,\ngamepad: false,\nwindowEvents: true,\n},\ndisableContextMenu: false,\n\nbackgroundColor: 0,\n\nrender: {\nantialias: true,\nantialiasGL: true,\ndesynchronized: false,\npixelArt: false,\nroundPixels: false,\ntransparent: false,\nclearBeforeRender: true,\npreserveDrawingBuffer: false,\npremultipliedAlpha: true,\nfailIfMajorPerformanceCaveat: false,\npowerPreference: 'default', // 'high-performance', 'low-power' or 'default'\nbatchSize: 4096,\nmaxLights: 10,\nmaxTextures: -1,\nmipmapFilter: 'LINEAR', // 'NEAREST', 'LINEAR', 'NEAREST_MIPMAP_NEAREST', 'LINEAR_MIPMAP_NEAREST', 'NEAREST_MIPMAP_LINEAR', 'LINEAR_MIPMAP_LINEAR'\nautoMobilePipeline: true,\ndefaultPipeline: 'MultiPipeline',\npipeline:[]\n},\ndisablePreFX: false,\ndisablePostFX: false,\n\nphysics: {\ndefault: false,  // 'arcade', or 'matter'\narcade: {...},   // See arcade-world#Configuration\nmatter: {...},   // See matterjs-world#Configuration\n},\n\nloader:{\nbaseURL: '',\npath: '',\nmaxParallelDownloads: 4,\ncrossOrigin: undefined,\nresponseType: '',\nasync: true,\nuser: '',\npassword: '',\ntimeout: 0,\nmaxRetries: 2,\nwithCredentials: false,\nimageLoadType: 'XHR',    // 'HTMLImageElement' \nlocalScheme: [ 'file://', 'capacitor://' ]\n},\n\nimages: {\ndefault: 'data:image/png;base64....',\nmissing: 'data:image/png;base64....',\nwhite: 'data:image/png;base64....',\n},\n\naudio: {\ndisableWebAudio: false,\ncontext:\nnoAudio: false,\n},\n\ndom: {\ncreateContainer: false,\nbehindCanvas: false,\npointerEvents: 'none'\n},\n\nplugins: {\nglobal: [\n//{key, plugin, start}\n],\nscene: [\n// ...\n]\n},\n\npipeline: { key:PipelineClass },\n\nfps: {\nmin: 10,\ntarget: 60,\nlimit: 0,\nforceSetTimeOut: false,\ndeltaHistory: 10,\npanicMax: 120,\nsmoothStep: true,\n},\n\nbanner: {\nhidePhaser: false,\ntext: '#ffffff',\nbackground: [\n'#ff0000',\n'#ffff00',\n'#00ff00',\n'#00ffff',\n'#000000'\n]\n},\n// banner: false,\n\nstableSort: -1\n}\n
"},{"location":"game/#destroy","title":"Destroy","text":"
game.destroy();\n// game.destroy(removeCanvas, noReturn);\n
  • removeCanvas : Set to true if you would like the parent canvas element removed from the DOM, or false to leave it in place.
  • noReturn : If true all the core Phaser plugins are destroyed. You cannot create another instance of Phaser on the same web page if you do this.
"},{"location":"game/#global-members","title":"Global members","text":""},{"location":"game/#scene-manager","title":"Scene manager","text":"

Global scene manager in game.scene, or scene.scene in each scene.

"},{"location":"game/#global-data","title":"Global data","text":"

Instance of data manager in game.registry, or scene.registry in each scene.

  • Get
    var value = scene.registry.get(key);\n// var value = game.registry.get(key);\n
  • Set
    scene.registry.set(key, value);\n// game.registry.set(key, value);\n
  • Event
    • Set data event
      scene.registry.events.on('setdata', function(parent, key, value){ /* ... */ });\n// game.registry.events.on('setdata', function(parent, key, value){ /* ... */ })\n
    • Change data event
      scene.registry.events.on('changedata', function(parent, key, value, previousValue){ /* ... */ });\n// game.registry.events.on('changedata', function(parent, key, value, previousValue){ /* ... */ })\n
      scene.registry.events.on('changedata-' + key, function(parent, value, previousValue){ /* ... */ });\n// game.registry.events.on('changedata-' + key, function(parent, value, previousValue){ /* ... */ });\n
"},{"location":"game/#game-time","title":"Game time","text":"
  • The time that the current game step started at.
    var time = game.getTime();\n// var time = scene.game.getTime();\n
  • The current game frame.
    var frameCount = game.getFrame();\n// var frameCount = scene.game.getFrame();\n
  • The delta time, since the last game step. This is a clamped and smoothed average value.
    var delta = game.loop.delta;\n// var delta = scene.game.loop.delta;\n
"},{"location":"game/#game-config","title":"Game config","text":"
var config = game.config;\n// var config = scene.game.config;\n
"},{"location":"game/#window-size","title":"Window size","text":"
  • Width
    var width = game.config.width;\n// var width = scene.game.config.width;\n
  • Height
    var height = game.config.height;\n// var height = scene.game.config.height;\n
"},{"location":"game/#pause-resume","title":"Pause / Resume","text":"
  • Pause the entire game and emit a PAUSE event.
    game.pause();\n
  • Resume the entire game and emit a RESUME event.
    game.resume();\n
  • Get pause duration
    var time = game.pauseDuration;\n
  • Is paused
    var isPaused = game.isPaused;\n
"},{"location":"game/#events","title":"Events","text":"
  • Pause(window is invisible)/Resume(window is visible)
    game.events.on('pause', function() {});\n
    game.events.on('resume', function() {});\n
  • Destroy event, triggered by game.destroy()
    game.events.on('destroy', function() {})\n
  • On window focused/blurred
    game.events.on('focus', function() {})\n
    game.events.on('blur', function(){ })\n
"},{"location":"gameobject/","title":"Game object","text":""},{"location":"gameobject/#introduction","title":"Introduction","text":"

Base class of all game object in phaser.

  • Author: Richard Davey
"},{"location":"gameobject/#usage","title":"Usage","text":""},{"location":"gameobject/#destroy","title":"Destroy","text":"
  • Destroy game object
    gameObject.destroy();\n
  • Game object will be destroyed automatically when scene destroyed, if it is in display list, or update list.
  • Event
    gameObject.once('destroy', function(gameObject, fromScene) {\n\n}, scope);\n
    • fromScene : true if game object is destroyed during scene is shutdown. When scene is shutdown, all game objects will be destroyed.
"},{"location":"gameobject/#position","title":"Position","text":"
  • Get
    var x = gameObject.x;\nvar y = gameObject.y;\n
  • Set
    gameObject.x = 0;\ngameObject.y = 0;\ngameObject.setPosition(x,y);\ngameObject.setX(x);\ngameObject.setY(y);\n
    • Set random
      gameObject.setRandomPosition(x, y, width, height);\n// gameObject.setRandomPosition(); // x=0, y=0, width=game.width, height=game.height\n
"},{"location":"gameobject/#local-point","title":"Local point","text":"

Transfer world point to local point

var point = gameObject.getLocalPoint(x, y);  // point : {x, y}\n// var out = gameObject.getLocalPoint(x, y, out);\n
or
var out = gameObject.getLocalPoint(x, y, out, camera);\n

"},{"location":"gameobject/#angle","title":"Angle","text":"
  • Get
    var angle = gameObject.angle;\nvar radians = gameObject.rotation;  // angle in radians\n
  • Set
    gameObject.angle = degrees;\ngameObject.rotation = radians;\ngameObject.setAngle(degrees);\ngameObject.setRotation(radians);\n
"},{"location":"gameobject/#visible","title":"Visible","text":"
  • Get
    var visible = gameObject.visible; // visible: true/false\n
  • Set
    gameObject.visible = visible;\ngameObject.setVisible(visible);\n
"},{"location":"gameobject/#alpha","title":"Alpha","text":"
  • Get
    var alpha = gameObject.alpha;  // 0~1\n
  • Set
    gameObject.setAlpha(alpha);\n// gameObject.alpha = alpha;\n
    or
    gameObject.setAlpha(topLeft, topRight, bottomLeft, bottomRight);\n// gameObject.alphaTopLeft = alpha;\n// gameObject.alphaTopRight = alpha;\n// gameObject.alphaBottomLeft = alpha;\n// gameObject.alphaBottomRight = alpha;\n
  • Clear (set to 1)
    gameObject.clearAlpha();\n
"},{"location":"gameobject/#flipx-flipy","title":"FlipX, FlipY","text":"
  • Get
    var flip = gameObject.flipX;  // flip: true/false\nvar flip = gameObject.flipY;  // flip: true/false\n
  • Set
    gameObject.flipX = flip;\ngameObject.flipY = flip;\ngameObject.setFlipX(flip);\ngameObject.setFlipY(flip);\ngameObject.setFlip(flipX, flipY);\ngameObject.toggleFlipX();\ngameObject.toggleFlipY();\ngameObject.resetFlip();  // equal to gameObject.setFlip(false, false);\n
"},{"location":"gameobject/#order-of-rendering","title":"Order of rendering","text":""},{"location":"gameobject/#depth-z-index","title":"Depth (z-index)","text":"

The depth starts from zero (the default value) and increases from that point. A game object with a higher depth value will always render in front of one with a lower value.

  • Get
    var depth = gameObject.depth;\n
  • Set
    gameObject.depth = value;\ngameObject.setDepth(value);\n
"},{"location":"gameobject/#display-list","title":"Display list","text":"
  • Get displayList
    var displayList = gameObject.getDisplayList();\n
  • Move the game Object to the top of the display list
    gameObject.setToTop()\n
    var displayList = gameObject.getDisplayList();\ndisplayList.bringToTop(child);\n
  • Move the game Object to the bottom of the display list
    gameObject.setToBack()\n
    var displayList = gameObject.getDisplayList();\ndisplayList.sendToBack(child);\n
  • Move the Game Object to appear above a given Game Object
    gameObject.setAbove(givenGameObject)\n
    var displayList = gameObject.getDisplayList();\ndisplayList.moveAbove(gameObject, givenGameObject);\n
  • Move the Game Object to appear below a given Game Object
    gameObject.setBelow(givenGameObject)\n
    var displayList = gameObject.getDisplayList();\ndisplayList.moveBelow(gameObject, givenGameObject);\n
  • Move the game object by index
    var displayList = gameObject.getDisplayList();\ndisplayList.moveTo(gameObject, index);\n
  • Swap two game objects
    var displayList = gameObject.getDisplayList();\ndisplayList.swap(gameObject, givenGameObject);\n
  • Move up or down
    var displayList = gameObject.getDisplayList();\ndisplayList.moveUp(gameObject);\ndisplayList.moveDown(gameObject);\n
"},{"location":"gameobject/#layer-game-object","title":"Layer game object","text":"

Place game object into Layer game object

"},{"location":"gameobject/#scroll-factor","title":"Scroll factor","text":"
  • Get
    var scrollFactorX = gameObject.scrollFactorX;\nvar scrollFactorY = gameObject.scrollFactorY;\n
  • Set
    gameObject.setScrollFactor(scrollFactor);\ngameObject.setScrollFactor(scrollFactorX, scrollFactorY);\n

Scroll factor: 0~1

  • 0= fixed to camera
  • 0.25= quarter the speed of the camera
  • 0.5= half the speed of the camera
"},{"location":"gameobject/#bounds","title":"Bounds","text":"
var output = gameObject.getTopLeft(output);     // output: {x, y}\nvar output = gameObject.getTopCenter(output);     // output: {x, y}\nvar output = gameObject.getTopRight(output);    // output: {x, y}\nvar output = gameObject.getLeftCenter(output);    // output: {x, y}\nvar output = gameObject.getRightCenter(output);    // output: {x, y}\nvar output = gameObject.getBottomLeft(output);  // output: {x, y}\nvar output = gameObject.getBottomCenter(output);     // output: {x, y}\nvar output = gameObject.getBottomRight(output); // output: {x, y}\nvar output = gameObject.getCenter(output);      // output: {x, y}\nvar output = gameObject.getBounds(output);      // output: {x, y, width, height}\n
"},{"location":"gameobject/#origin","title":"Origin","text":"
  • Get
    var originX = gameObject.originX;\nvar originY = gameObject.originY;\n
  • Set
    gameObject.setOrigin(x, y);\n// gameObject.setOrigin(x); // y = x\n
    • Set to top-left
      gameObject.setOrigin(0);\n
    • Set to center
      gameObject.setOrigin(0.5);\n
    • Set to bottom-right
      gameObject.setOrigin(1);\n
"},{"location":"gameobject/#tint","title":"Tint","text":"
  • Get
    var color = gameObject.tintTopLeft;     // color: 0xRRGGBB\nvar color = gameObject.tintTopRight;\nvar color = gameObject.tintBottomLeft;\nvar color = gameObject.tintBottomRight;\nvar isTinted = gameObject.isTinted;\n
  • Set
    gameObject.tint = color;\ngameObject.setTint(color);  // multiply color value\ngameObject.setTint(colorTopLeft, colorTopRight, colorBottomLeft, colorBottomRight);\ngameObject.setTintFill(color);  // replace color value\ngameObject.setTintFill(colorTopLeft, colorTopRight, colorBottomLeft, colorBottomRight);    gameObject.clearTint();     // equal to `gameObject.setTint(0xffffff)`\n

Note

gameObject.tint is a write-only property

"},{"location":"gameobject/#blend-mode","title":"Blend mode","text":"
  • Get
    var blendMode = gameObject.blendMode;\n
  • Set
    gameObject.blendMode = blendMode;\ngameObject.setBlendMode(blendMode);\n
    • blendMode : Blend mode
"},{"location":"gameobject/#mask","title":"Mask","text":"

See Mask.

"},{"location":"gameobject/#built-in-shader-effects","title":"Built-in shader effects","text":"

See built-in shader effects

"},{"location":"gameobject/#post-fx-pipeline","title":"Post-fx pipeline","text":""},{"location":"gameobject/#register-post-fx-pipeline","title":"Register post-fx pipeline","text":"
  • Register post-fx pipeline in game config
    import PostFxClass from 'path';\nvar config = {\n// ...\npipeline: [PostFxClass]\n// ...\n};\nvar game = new Phaser.Game(config);\n

Some post-fx pipelines:

  • Barrel: Barrel post processing filter.
  • Color replace: Replace color post processing filter.
  • Cross-stitching: Cross-stitching post processing filter.
  • Dissolve: Dissolve transition post processing filter.
  • Fish eye: Fish-eye post processing filter.
  • Glow-filter: Glow post processing filter.
  • Glow-filter: Glow post processing filter, ported from pixi.
  • Gray-scale: Gray scale post processing filter.
  • Hsl-adjust: Adjust color in HSL domain, post processing filter.
  • Horri-fi: 6-in-1 post processing filter.
  • Inverse: Inverse color post processing filter.
  • Kawase-blur: Kawase-blur post processing filter.
  • Pixelation: Pixelation post processing filter.
  • Toonify: Draw outlines and quantize color in HSV domain, post processing filter.
  • Shockwave: Shockwave post processing filter.
  • Split: Split image into 4 parts.
  • Swirl: Swirl post processing filter.
  • Warp: Warp post processing filter.
"},{"location":"gameobject/#add-post-fx-pipeline","title":"Add post-fx pipeline","text":"
gameObject.setPostPipeline(PostFxClass);\n
  • PostFxClass : Class of post-fx pipeline.
"},{"location":"gameobject/#remove-post-fx-pipeline","title":"Remove post-fx pipeline","text":"
  • Remove a post-fx pipeline
    gameObject.removePostPipeline(PostFxClass);\n
  • Remove all post-fx pipelines
    gameObject.resetPipeline(true);\n
    or
    gameObject.postPipelines = [];\ngameObject.hasPostPipeline = false;\n
"},{"location":"gameobject/#get-post-fx-pipeline","title":"Get post-fx pipeline","text":"
var pipelineInstance = gameObject.getPostPipeline(PostFxClass);\n
"},{"location":"gameobject/#size","title":"Size","text":"
  • Native (un-scaled) size
    • Get
      var width = gameObject.width;\nvar height = gameObject.height;\n
    • Set
      gameObject.setSize(width, height);\n
      or
      gameObject.width = width;\ngameObject.height = height;\n
  • Display size
    • Get
      var displayWidth = gameObject.displayWidth;\nvar displayHeight = gameObject.displayHeight;\n
    • Set
      gameObject.setDisplaySize(displayWidth, displayHeight);\n
      or
      gameObject.displayWidth = displayWidth;\ngameObject.displayHeight = displayHeight;\n
  • Scale
    • Get
      var scaleX = gameObject.scaleX;\nvar scaleY = gameObject.scaleY;\n
      or
      var scale = gameObject.scale;  // Return (scaleX + scaleY)/2\n
    • Set
      gameObject.setScale(scaleX, scaleY);\n
      or
      gameObject.scaleX = scaleX;\ngameObject.scaleY = scaleY;\n
      or
      gameObject.scale = scale;  // Set scaleX, scaleY to scale\n
"},{"location":"gameobject/#click","title":"Click","text":"
gameObject.setInteractive().on('pointerdown', function(pointer, localX, localY, event){\n// ...\n});\n

See touch event

"},{"location":"gameobject/#state","title":"State","text":"
  • Get
    var state = gameObject.state;\n
  • Set
    gameObject.setState(state);\n
"},{"location":"gameobject/#data","title":"Data","text":"
  • Get
    var value = gameObject.getData(key);\nvar values = gameObject.getData(keys); // keys: an array of keys\nvar value = gameObject.data.values[key];\n
  • Set
    gameObject.setData(key, value);\ngameObject.incData(key, value);    gameObject.setData(obj); // obj: {key0:value0, key1:value1, ...}\ngameObject.data.values[key] = value;\ngameObject.data.values[key] += inc;\n
    or
    gameObject.toggleData(key);\n
  • Enable
    gameObject.setDataEnabled();\n
  • Events :
    • Set data evant
      gameObject.on('setdata', function(gameObject, key, value){ /* ... */ });\n
    • Change data event
      gameObject.on('changedata', function(gameObject, key, value, previousValue){ /* ... */ });\n
      gameObject.on('changedata-' + key, function(gameObject, value, previousValue){ /* ... */ });\n

See data manager

Note

Ensure data manager is created before binding any data-changed events.

"},{"location":"gameobject/#texture","title":"Texture","text":"
  • Set texture via key string
    gameObject.setTexture(key);\n// gameObject.setTexture(key, frame);\n// gameObject.setTexture(key, frame, updateSize, updateOrigin);\n
  • Set texture via texture object
    gameObject.setTexture(texture);\n// gameObject.setTexture(texture, frame);\n
    • texture : Texture object, or canvas texture object
  • Set frame
    gameObject.setFrame(frame);\n// gameObject.setFrame(frame, updateSize, updateOrigin);\n
    • frame :\u3000The name or index of the frame within the Texture.
    • updateSize : Should this call adjust the size of the Game Object?
    • updateOrigin : Should this call adjust the origin of the Game Object?
  • Set frame by frame object
    gameObject.setFrame(frameObject);\n// gameObject.setFrame(frameObject, updateSize, updateOrigin);\n
  • Applies a crop to a texture
    gameObject.setCrop(x, y, width, height);\n
    The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left.
    • Reset crop
      gameObject.setCrop();\n// gameObject.isCropped = false;\n
  • Get texture, frame.
    var texture = gameObject.texture;\nvar frame = gameObject.frame;\n
  • Get texture key, frame name.
    var textureKey = gameObject.texture.key;\nvar frameName = gameObject.frame.name;\n
"},{"location":"gameobject/#name","title":"Name","text":"
  • Get
    var name = gameObject.name;\n
  • Set
    gameObject.setName(name);\ngameObject.name = name;\n
"},{"location":"gameobject/#will-render","title":"Will render","text":"
  • Test render flag and camera filter.
    var willRennder = gameObject.willRender(camera);\n
  • Test render flag only
    var willRender = (gameObject.renderFlags === Phaser.GameObjects.GameObject.RENDER_MASK);\n
    • Phaser.GameObjects.GameObject.RENDER_MASK : 15 (Visible, Alpha, Transform and Texture)
"},{"location":"gameobject/#add-to-scenecontainer","title":"Add to scene/container","text":""},{"location":"gameobject/#add","title":"Add","text":"

Trigger 'addedtoscene' event, which invoke gameObject.addedToScene()

  • Register 'addedtoscene' event
    gameObject.on('addedtoscene', function(gameObject, scene){});\n
  • Or, override addedToScene method
    class MyClass extends BaseClass {\n// ...\naddedtoscene() {\nsuper.addedtoscene();\n// ...\n}\n}\n
"},{"location":"gameobject/#remove","title":"Remove","text":"

Trigger 'removedfromscene' event, which invoke gameObject.removedFromScene()

  • Register 'removedfromscene' event
    gameObject.on('removedfromscene', function(gameObject, scene){});\n
  • Or, override removedFromScene method
    class MyClass extends BaseClass {\n// ...\nremovedFromScene() {\nsuper.removedFromScene();\n// ...\n}\n}\n
"},{"location":"gameobject/#custom-class","title":"Custom class","text":"
  • Define class
    class MyClass extends BaseClass {\nconstructor(scene, x, y) {\nsuper(scene, x, y);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     if (super.preUpdate) {\n//         super.preUpdate(time, delta);\n//     }\n// }\n\n// destroy(fromScene) {\n//     //  This Game Object has already been destroyed\n//     if (!this.scene) {\n//         return;\n//     }\n//     super.destroy(fromScene);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
        • Some kinds of game object like Sprite, Dom-element has preUpdate method already.
  • Create instance
    var image = new MyClass(scene, x, y, key);\n
"},{"location":"gamepad/","title":"Gamepad","text":""},{"location":"gamepad/#introduction","title":"Introduction","text":"

Gamepad's state of buttons, or axis.

  • Author: Richard Davey
"},{"location":"gamepad/#usage","title":"Usage","text":""},{"location":"gamepad/#enable-gamepad-manager","title":"Enable gamepad manager","text":"
var config = {\n// ...\ninput: {\ngamepad: true\n},\n// ...\n}\nvar game = new Phaser.Game(config);\n
"},{"location":"gamepad/#get-gamepad","title":"Get gamepad","text":"
  • Get all currently connected Gamepads.
    var gamepads = scene.input.gamepad.getAll();\n
  • Get gamepad by index
    var gamepad = scene.input.gamepad.getPad(0);\n// var gamepad = scene.input.gamepad.getPad(index);\n
  • Get gamepad when button-down.
    scene.input.gamepad.once('down', function (gamepad, button, value) {\n}\n
    • gamepad : A reference to the Gamepad on which the button was released. See Properties of gamepad
    • button : A reference to the Button which was released.
    • value : The value of the button at the time it was released. Between 0 and 1. Some Gamepads have pressure-sensitive buttons.
"},{"location":"gamepad/#events","title":"Events","text":"
  • Button down
    scene.input.gamepad.on('down', function (gamepad, button, value) {\n})\n
    or
    gamepad.on('down', function(buttonIndex, value, button) {\n})\n
  • Button up
    scene.input.gamepad.on('up', function (gamepad, button, value) {\n}\n
    or
    gamepad.on('up', function(buttonIndex, value, button) {\n})\n
  • Gamepad connected
    scene.input.gamepad.on('connected', function (gamepad, event) {\n}\n
  • Gamepad disconnected
    scene.input.gamepad.on('disconnected', function (gamepad, event) {\n}\n
"},{"location":"gamepad/#gamepad","title":"Gamepad","text":""},{"location":"gamepad/#buttons","title":"Buttons","text":"
  • Cursor buttons
    var isLeftDown = gamepad.left;\nvar isRightftDown = gamepad.right;\nvar isUpDown = gamepad.up;\nvar isDownDown = gamepad.down;\n
  • Right buttons cluster
    var isADown = gamepad.A;  // Dual Shock controller: X button\nvar isYDown = gamepad.Y;  // Dual Shock controller: Triangle button\nvar isXDown = gamepad.X;  // Dual Shock controller: Square button.\nvar isBDown = gamepad.B;  // Dual Shock controller: Circle button\n
  • Shoulder buttons
    var isL1Down = gamepad.L1; // XBox controller: LB button\nvar isL2Down = gamepad.L2; // XBox controller: LT button\nvar isR1Down = gamepad.R1; // XBox controller: RB button\nvar isR2Down = gamepad.R2; // XBox controller: RT button\n
"},{"location":"gamepad/#axis-sticks","title":"Axis sticks","text":"
  • Left sticks, right sticks
    var leftStick = gamepad.leftStick;\nvar rightStick = gamepad.rightStick;\n
    • leftStick, rightStick : Read only vector2.
      • Angle : leftStick.angle()
      • Length : leftStick.length()
      • x, y : leftStick.x , leftStick.y
"},{"location":"gamepad/#properties","title":"Properties","text":"
  • gamepad.index : An integer that is unique for each Gamepad currently connected to the system. This can be used to distinguish multiple controllers. Note that disconnecting a device and then connecting a new device may reuse the previous index.
  • gamepad.id : A string containing some information about the controller.
  • gamepad.buttons : An array of Gamepad Button objects, corresponding to the different buttons available on the Gamepad.
  • gamepad.axes : An array of Gamepad Axis objects, corresponding to the different axes available on the Gamepad, if any.
"},{"location":"gashapon/","title":"Gashapon","text":""},{"location":"gashapon/#introduction","title":"Introduction","text":"

Pick random item from box.

  • Author: Rex
  • Member of scene, or game object
"},{"location":"gashapon/#usage","title":"Usage","text":"

Sample code

"},{"location":"gashapon/#install-plugin","title":"Install plugin","text":""},{"location":"gashapon/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexgashaponplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgashaponplugin.min.js', true);\n
  • Add gashapon object
    var gashapon = scene.plugins.get('rexgashaponplugin').add(config);\n
"},{"location":"gashapon/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GashaponPlugin from 'phaser3-rex-plugins/plugins/gashapon-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGashapon',\nplugin: GashaponPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add gashapon object
    var gashapon = scene.plugins.get('rexGashapon').add(config);\n
"},{"location":"gashapon/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Gashapon from 'phaser3-rex-plugins/plugins/gashapon.js';\n
  • Add gashapon object
    var gashapon = new Gashapon(config);\n
"},{"location":"gashapon/#create-instance","title":"Create instance","text":"
var gashapon = scene.plugins.get('rexGashapon').add({\nmode: 'shuffle',  // 0|'shuffle'|1|'random\nitems: {  // name:count\na:1, b:2, c:3 },\nreload: true,     // true|false\nrnd: undefined,\n});\n
  • mode :
    • 'shuffle', or 0 : pick item from box without put it back.
    • 'random', or 1 : pick item from box then put it back.
  • reload : set true to reload items when box is empty for shuffle mode.
  • items : initial items { name:count } in box.
  • rnd : Use random data generator to generate result.
    • undefined : Use Math.random() to generate result.
    • Phaser.Math.RND : Use pre-defined random data generator.
"},{"location":"gashapon/#pick-item","title":"Pick item","text":"
  • Pick a random item
    var item = gashapon.next();\n
    • return null if pick nothing
  • Pick specific item
    var item = gashapon.next(name);\n
    • return null if pick nothing
  • Last picked item
    var item = gashapon.result;\n
"},{"location":"gashapon/#set-item","title":"Set item","text":"
  • Set item
    gashapon.setItem(name, count);\n
  • Add item
    gashapon.addItem(name, count);\n
  • Put item back
    gashapon.putItemBack(name, count);\n
"},{"location":"gashapon/#remove-item","title":"Remove item","text":"
  • Remove item
    gashapon.removeItem(name);\n
  • Remove all items
    gashapon.removeAllItems();\n
"},{"location":"gashapon/#current-status","title":"Current status","text":"
  • Get current status
    var status = gashapon.toJSON();\n
  • Clone object
    var state = gashapon.toJSON();\nvar gashapon2 = new Gashapon(state);\n
  • Overwrite current status
    var status = gashapon.toJSON();\n// gashapon.next()...\ngashapon.resetFromJSON(status);\n
"},{"location":"gashapon/#get-items","title":"Get items","text":"
  • Get initial items
    var items = gashapon.getItems();\n
  • Get remainder items
    var items = gashapon.getRemain();\n
  • Get initial item count
    var count = gashapon.getItemCount(name);\n
  • Get remainder item count
    var count = gashapon.getRemainCount(name);\n
  • For each initial item
    gashapon.forEachItem(function(name, count) {\n\n}, scope);\n
  • For each remainder item
    gashapon.forEachRemain(function(name, count) {\n\n}, scope);\n
"},{"location":"gashapon/#set-random-generator","title":"Set random generator","text":"
gashapon.setRND(rnd);\n
  • rnd : Use random data generator to generate result.
    • undefined, or null : Use Math.random() to generate result.
    • Phaser.Math.RND : Use pre-defined random data generator.
"},{"location":"geom-circle/","title":"Circle","text":""},{"location":"geom-circle/#introduction","title":"Introduction","text":"

Circle shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-circle/#usage","title":"Usage","text":""},{"location":"geom-circle/#create-shape","title":"Create shape","text":"
var circle = new Phaser.Geom.Circle(x, y, radius);\n
"},{"location":"geom-circle/#clone-shape","title":"Clone shape","text":"
var circle1 = Phaser.Geom.Circle.Clone(circle0);\n
"},{"location":"geom-circle/#draw-on-graphics","title":"Draw on graphics","text":"
  • Fill shape
    // graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\ngraphics.fillCircleShape(circle);\n
  • Stroke shape
    // graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\ngraphics.strokeCircleShape(circle);\n

Note

Negative radius will be treated as positive radius. i.e. Math.abs(radius)

"},{"location":"geom-circle/#set-properties","title":"Set properties","text":"
  • All properties
    circle.setTo(x, y, radius);\n
    or
    Phaser.Geom.Circle.CopyFrom(source, dest);\n
  • Position
    circle.setPosition(x, y);\n
    or
    circle.x = 0;\ncircle.y = 0;\n
    or
    circle.left = 0;       // circle.x\ncircle.top = 0;        // circle.y\n// circle.right = 0;   // circle.x\n// circle.bottom = 0;  // circle.y\n
    or
    Phaser.Geom.Circle.Offset(circle, dx, dy); // circle.x += dx, circle.y += dy\n
    or
    Phaser.Geom.Circle.OffsetPoint(circle, point); // circle.x += point.x, circle.y += point.y\n
  • Radius
    circle.radius = radius;\n
    or
    circle.diameter = diameter;  // diameter = 2 * radius\n
"},{"location":"geom-circle/#get-properties","title":"Get properties","text":"
  • Position
    var x = circle.x;\nvar y = circle.y;\nvar top = circle.top;\nvar left = circle.left;\nvar right = circle.right;\nvar bottom = circle.bottom;\n
  • Radius
    var radius = circle.radius;\n// var diameter = circle.diameter;\n
  • Bound
    var bound = Phaser.Geom.Circle.GetBounds(circle);\n// var bound = Phaser.Geom.Circle.GetBounds(circle, bound);  // push bound\n
    • bound : A Rectangle shape object
  • Area
    var area = Phaser.Geom.Circle.Area(circle);\n
  • Circumference
    var circumference = Phaser.Geom.Circle.Circumference(circle);\n
  • Type:
    var type = circle.type; // 0\n
"},{"location":"geom-circle/#points-shape","title":"Point(s) & shape","text":"
  • Get point at shape's edge
    var point = circle.getPoint(t);  // t : 0 ~ 1 (angle/360)\n// var point = circle.getPoint(t, point);  // modify point\n
    or
    var point = Phaser.Geom.Circle.CircumferencePoint(circle, angle);  // angle in degrees\n// var point = Phaser.Geom.Circle.CircumferencePoint(circle, angle, point);  // modify point\n
  • Get a random point inside shape
    var point = circle.getRandomPoint();\n// var point = circle.getRandomPoint(point);  // modify point\n
  • Get points around shape's edge
    var points = circle.getPoints(quantity);\n// var points = circle.getPoints(quantity, null, points);  // push points\n
    or calculate quantity from steps
    var points = circle.getPoints(false, step);\n// var points = circle.getPoints(false, step, points);  // push points\n
    • points : an array of point
  • Point is inside shape
    var isInside = circle.contains(x, y);\n
    or
    var isInside = Phaser.Geom.Circle.ContainsPoint(circle, point);\n
  • Rectangle is inside shape
    var isInside = Phaser.Geom.Circle.ContainsRect(circle, rect);  // rect : 4 points\n
"},{"location":"geom-circle/#empty","title":"Empty","text":"
  • Set empty
    circle.setEmpty();     // circle.radius = 0\n
  • Is empty
    var isEmpty = circle.isEmpty();   // circle.radius <= 0\n
"},{"location":"geom-circle/#equal","title":"Equal","text":"
var isEqual = Phaser.Geom.Circle.Equals(circle0, circle1);\n

Position and radius are equal.

"},{"location":"geom-circle/#intersection","title":"Intersection","text":""},{"location":"geom-circle/#circle-to-circle","title":"Circle to circle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.CircleToCircle(circleA, circleB);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetCircleToCircle(circleA, circleB);\n// var out = Phaser.Geom.Intersects.GetCircleToCircle(circleA, circleB, out);\n
"},{"location":"geom-circle/#circle-to-rectangle","title":"Circle to rectangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.CircleToRectangle(circle, rect);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetCircleToRectangle(circle, rect);\n// var out = Phaser.Geom.Intersects.GetCircleToRectangle(circle, rect, out);\n
"},{"location":"geom-circle/#circle-to-triangle","title":"Circle to triangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.TriangleToCircle(triangle, circle);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetTriangleToCircle(triangle, circle);\n// var out = Phaser.Geom.Intersects.GetTriangleToCircle(triangle, circle, out);\n
"},{"location":"geom-circle/#circle-to-line","title":"Circle to line","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.LineToCircle(line, circle);\n// var result = Phaser.Geom.Intersects.LineToCircle(line, circle, nearest);\n
    • nearest : Nearest point on line.
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetLineToCircle(line, circle);\n// var out = Phaser.Geom.Intersects.GetLineToCircle(line, circle, out);\n
"},{"location":"geom-ellipse/","title":"Ellipse","text":""},{"location":"geom-ellipse/#introduction","title":"Introduction","text":"

Ellipse shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-ellipse/#usage","title":"Usage","text":""},{"location":"geom-ellipse/#create-shape","title":"Create shape","text":"
var ellipse = new Phaser.Geom.Ellipse(x, y, width, height);\n
"},{"location":"geom-ellipse/#clone-shape","title":"Clone shape","text":"
var ellipse1 = Phaser.Geom.Ellipse.Clone(ellipse0);\n
"},{"location":"geom-ellipse/#draw-on-graphics","title":"Draw on graphics","text":"
  • Fill shape
    // graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\ngraphics.fillEllipseShape(ellipse);\n
  • Stroke shape
    // graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\ngraphics.strokeEllipseShape(ellipse);\n

Note

Negative width, height will be treated as positive width, height. i.e. Math.abs(width), Math.abs(height)

"},{"location":"geom-ellipse/#set-properties","title":"Set properties","text":"
  • All properties
    ellipse.setTo(x, y, width, height);\n
    or
    Phaser.Geom.Ellipse.CopyFrom(source, dest);\n
  • Position
    ellipse.setPosition(x, y);\n
    or
    ellipse.x = 0;\nellipse.y = 0;\n
    or
    ellipse.left = 0;       // ellipse.x\nellipse.top = 0;        // ellipse.y\n// ellipse.right = 0;   // ellipse.x\n// ellipse.bottom = 0;  // ellipse.y\n
    or
    Phaser.Geom.Ellipse.Offset(ellipse, dx, dy); // ellipse.x += dx, ellipse.y += dy\n
    or
    Phaser.Geom.Ellipse.OffsetPoint(ellipse, point); // ellipse.x += point.x, ellipse.y += point.y\n
  • Width, height
    ellipse.width = width;\nellipse.height = height;\n
"},{"location":"geom-ellipse/#get-properties","title":"Get properties","text":"
  • Position
    var x = ellipse.x;\nvar y = ellipse.y;\nvar top = ellipse.top;\nvar left = ellipse.left;\nvar right = ellipse.right;\nvar bottom = ellipse.bottom;\n
  • Width, height
    var width = ellipse.width;\nvar height = ellipse.height;\n
  • Bound
    var bound = Phaser.Geom.Ellipse.GetBounds(ellipse);\n// var bound = Phaser.Geom.Ellipse.GetBounds(ellipse, bound);  // push bound\n
    • bound : A Rectangle shape object
  • Area
    var area = Phaser.Geom.Ellipse.Area(ellipse);\n
  • Circumference
    var circumference = Phaser.Geom.Ellipse.Circumference(ellipse);\n
  • Type:
    var type = ellipse.type; // 1\n
"},{"location":"geom-ellipse/#points-shape","title":"Point(s) & shape","text":"
  • Get point at shape's edge
    var point = ellipse.getPoint(t);  // t : 0 ~ 1 (angle/360)\n// var point = ellipse.getPoint(t, point);  // modify point\n
    or
    var point = Phaser.Geom.Ellipse.CircumferencePoint(ellipse, angle);  // angle in degrees\n// var point = Phaser.Geom.Ellipse.CircumferencePoint(ellipse, angle, point);  // modify point\n
  • Get a random point inside shape
    var point = ellipse.getRandomPoint();\n// var point = ellipse.getRandomPoint(point);  // modify point\n
  • Get points around shape's edge
    var points = ellipse.getPoints(quantity);\n// var points = ellipse.getPoints(quantity, null, points);  // push points\n
    or calculate quantity from steps
    var points = ellipse.getPoints(false, step);\n// var points = ellipse.getPoints(false, step, points);  // push points\n
    • points : an array of point
  • Point is inside shape
    var isInside = ellipse.contains(x, y);\n
    or
    var isInside = Phaser.Geom.Ellipse.ContainsPoint(ellipse, point);\n
  • Rectangle is inside shape
    var isInside = Phaser.Geom.Ellipse.ContainsRect(ellipse, rect);  // rect : 4 points\n
"},{"location":"geom-ellipse/#empty","title":"Empty","text":"
  • Set empty
    ellipse.setEmpty();     // ellipse.width = 0, ellipse.height = 0\n
  • Is empty
    var isEmpty = ellipse.isEmpty();   // ellipse.width <= 0 || ellipse.height <= 0\n
"},{"location":"geom-ellipse/#equal","title":"Equal","text":"
var isEqual = Phaser.Geom.Ellipse.Equals(ellipse0, ellipse1);\n

Position and width, height are equal.

"},{"location":"geom-hexagon/","title":"Hexagon","text":""},{"location":"geom-hexagon/#introduction","title":"Introduction","text":"

Hexagon shape and methods, extends from Polygon geometry object.

  • Author: Rex
  • Geometry object
"},{"location":"geom-hexagon/#usage","title":"Usage","text":"

Sample code

"},{"location":"geom-hexagon/#install-plugin","title":"Install plugin","text":""},{"location":"geom-hexagon/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexhexagonplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexhexagonplugin.min.js', true);\n
  • Add hexagon geometry object
    var hexagon = scene.plugins.get('rexhexagonplugin').add(x, y, size, orientationType);\n
"},{"location":"geom-hexagon/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import HexagonPlugin from 'phaser3-rex-plugins/plugins/hexagon-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexHexagon',\nplugin: HexagonPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add hexagon geometry object
    var hexagon = scene.plugins.get('rexHexagon').add(x, y, size, orientationType);\n
"},{"location":"geom-hexagon/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Hexagon from 'phaser3-rex-plugins/plugins/hexagon.js';\n
  • Add hexagon geometry object
    var hexagon = new Hexagon(x, y, size, orientationType);\n
"},{"location":"geom-hexagon/#create-shape","title":"Create shape","text":"

var hexagon = scene.plugins.get('rexHexagon').add(x, y, size, orientationType);\n
or
var hexagon = scene.plugins.get('rexHexagon').add({\nx: 0,\ny: 0,\nsize: 20,\norientationType: 0     // 0|'flat'|'vertical'|1|'pointy'|'horizontal'\n});\n
or
var hexagon = new Phaser.Geom.rexHexagon(x, y, size, orientationType);\n

  • x : Center X.
  • y : Center Y.
  • size : Distance between center to each corner.
  • orientationType : See here
    • 0, 'flat', or 'y'
    • 1, 'pointy' or ,'x'
"},{"location":"geom-hexagon/#draw-on-graphics","title":"Draw on graphics","text":"

See Polygon shape.

"},{"location":"geom-hexagon/#set-properties","title":"Set properties","text":"
  • All properties
    hexagon.setTo(x, y, size, orientationType);\n
  • Position
    hexagon.setPosition(x, y);\n
    or
    hexagon.x = 0;\nhexagon.y = 0;\n
    or
    hexagon.centerX = 0;  // equal to hexagon.x\nhexagon.centerY = 0;  // equal to hexagon.y\n
    or
    hexagon.left = 0;       // hexagon.x\nhexagon.top = 0;        // hexagon.y\nhexagon.right = 0;      // hexagon.x\nhexagon.bottom = 0;     // hexagon.y\n
  • Size
    hexagon.setSize(size);\n
    or
    hexagon.size = size;\n
  • Orientation type
    hexagon.setType(orientationType);\n
    or
    hexagon.orientationType = orientationType;\n
    • orientationType : See here
      • 0, 'flat', or 'y'
      • 1, 'pointy' or ,'x'
"},{"location":"geom-hexagon/#get-properties","title":"Get properties","text":"

See Polygon shape.

  • Position
    • Center
      var centerX = hexagon.centerX;\nvar centerY = hexagon.centerY;\n
      or
      var centerX = hexagon.x;\nvar centerY = hexagon.y;\n
    • Bound
      var top = hexagon.top;\nvar left = hexagon.left;\nvar right = hexagon.right;\nvar bottom = hexagon.bottom;\n
  • Width
    var width = hexagon.width;\n
  • Height
    var width = hexagon.height;\n
  • Lines around hexagon
    var edge01 = hexagon.getLineA();\nvar edge12 = hexagon.getLineB();\nvar edge23 = hexagon.getLineC();\nvar edge34 = hexagon.getLineD();\nvar edge45 = hexagon.getLineE();\nvar edge50 = hexagon.getLineF();\n// var out = hexagon.getLineF(out);\n
    or
    var edge = hexagon.getEdge(edgeIdx);\n// var out = hexagon.getEdge(edgeIdx, out);\n
"},{"location":"geom-hexagon/#points-shape","title":"Point(s) & shape","text":"

See Polygon shape.

"},{"location":"geom-line/","title":"Line","text":""},{"location":"geom-line/#introduction","title":"Introduction","text":"

Line shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-line/#usage","title":"Usage","text":""},{"location":"geom-line/#create-shape","title":"Create shape","text":"
var line = new Phaser.Geom.Line(x1, y1, x2, y2);\n
"},{"location":"geom-line/#clone-shape","title":"Clone shape","text":"
var line1 = Phaser.Geom.Line.Clone(line0);\n
"},{"location":"geom-line/#draw-on-graphics","title":"Draw on graphics","text":"
// graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\ngraphics.strokeLineShape(line);\n
"},{"location":"geom-line/#set-properties","title":"Set properties","text":"
  • All properties
    line.setTo(x1, y1, x2, y2);\n
    or
    Phaser.Geom.Line.CopyFrom(source, dest);\n
  • Position
    line.x1 = 0;\nline.y1 = 0;\nline.x2 = 0;\nline.y2 = 0;\n
    or
    line.left = 0;    // min(x1, x2)\nline.top = 0;     // min(y1, y2)\nline.right = 0;   // max(x1, x2)\nline.bottom = 0;  // max(y1, y2)\n
    • Offset start, end
      var line = Phaser.Geom.Line.Offset(line, dx, dy); // line.x1 += dx, line.y1 += dy, line.x2 += dx, line.y2 += dy\n
    • Set center position
      var line = Phaser.Geom.Line.CenterOn(line, x, y);\n
  • Start point, angle, length
    var line = Phaser.Geom.Line.SetToAngle(line, x, y, angle, length);\n
    • line : The line to set
    • x , y : start point
    • angle : The angle of the line in radians
      var rad = Phaser.Math.DegToRad(deg);\n
    • length :\u3000The length of the line
  • Rotate
    • Rotate around midpoint
      var line = Phaser.Geom.Line.Rotate(line, angle)\n
      • line : The line to set
      • angle : The angle of the line in radians
        var rad = Phaser.Math.DegToRad(deg);\n
    • Rotate around point
      var line = Phaser.Geom.Line.RotateAroundPoint(line, point, angle);\n
      or
      var line = Phaser.Geom.Line.RotateAroundXY(line, x, y, angle);\n
      • line : The line to set
      • angle : The angle of the line in radians
        var rad = Phaser.Math.DegToRad(deg);\n
  • Extend
    var line = Phaser.Geom.Line.Extend(line, left, right);\n
"},{"location":"geom-line/#get-properties","title":"Get properties","text":"
  • Position
    var x1 = line.x1;\nvar y1 = line.y1;\nvar x2 = line.x2;\nvar y2 = line.y2;\nvar top = line.top;       // min(x1, x2)\nvar left = line.left;     // min(y1, y2)\nvar right = line.right;   // max(x1, x2)\nvar bottom = line.bottom; // max(y1, y2)\n
    • Start point
      var start = line.getPointA();  // start: {x, y}\nvar start = line.getPointA(start);  // push start\n
    • End point
      var end = line.getPointB();  // end: {x, y}\nvar end = line.getPointB(end);  // push end\n
    • Middle point
      var middle = Phaser.Geom.Line.GetMidPoint(line);  // middle: {x, y}\n// var middle = Phaser.Geom.Line.GetMidPoint(line, middle);\n
  • Length
    var length = Phaser.Geom.Line.Length(line);\n
    • Width : Abs(x1 - x2)
      var width = Phaser.Geom.Line.Width(line);\n
    • Height : Abs(y1 - y2)
      var width = Phaser.Geom.Line.Height(line);\n
  • Slope
    • Slope : (y2 - y1) / (x2 - x1)
      var slope = Phaser.Geom.Line.Slope(line);\n
    • Perpendicular slope : -((x2 - x1) / (y2 - y1))
      var perpSlope = Phaser.Geom.Line.PerpSlope(line);\n
  • Angle
    • Angle
      var angle = Phaser.Geom.Line.Angle(line);\n
      • angle : The angle of the line in radians
        var deg = Phaser.Math.RadToDeg(rad);  // deg : -180 ~ 180\n
    • Normal angle (angle - 90 degrees)
      • Normal angle
        var normalAngle = Phaser.Geom.Line.NormalAngle(line);\n
      • Normal vector
        var normal = Phaser.Geom.Line.GetNormal(line);  // normal: {x, y}\n// var normal = Phaser.Geom.Line.GetNormal(line, normal);  // push normal\n
        or
        var normalX = Phaser.Geom.Line.NormalX(line);\nvar normalY = Phaser.Geom.Line.NormalY(line);\n
    • Reflect angle
      var reflectAngle = Phaser.Geom.Line.ReflectAngle(aimLine, reflectingLine);\n
  • Type:
    var type = line.type; // 2\n
"},{"location":"geom-line/#points-shape","title":"Point(s) & shape","text":"
  • Get point at shape's edge
    var point = line.getPoint(t);  // t : 0 ~ 1. 0=start, 0.5=middle, 1=end\n// var point = line.getPoint(t, point);  // modify point\n
  • Get a random point inside shape
    var point = line.getRandomPoint();\n// var point = line.getRandomPoint(point);  // modify point\n
  • Get points around shape's edge
    var points = line.getPoints(quantity);\n// var points = line.getPoints(quantity, null, points);  // push points\n
    or calculate quantity from steps
    var points = line.getPoints(false, step);\n// var points = line.getPoints(false, step, points);  // push points\n
    • points : an array of point
  • Get points using Bresenham's line algorithm
    var points = Phaser.Geom.Line.BresenhamPoints(line, step);\n// var points = Phaser.Geom.Line.BresenhamPoints(line, step, points);  // push points\n
  • Get points using easing function
    var points = Phaser.Geom.Line.GetEasedPoints(line, ease, quantity);\n// var points = Phaser.Geom.Line.GetEasedPoints(line, ease, quantity, collinearThreshold, easeParams);\n
    • ease : String of ease function, or a custom function (function (t) { return value}).
    • quantity : The number of points to return.
    • collinearThreshold : Each point is spaced out at least this distance apart. This helps reduce clustering in noisey eases.
    • easeParams : Array of ease parameters to go with the ease.
  • Get the nearest point on a line perpendicular to the given point.
    var point = Phaser.Geom.Line.GetNearestPoint(line, pointIn);\n// var point = Phaser.Geom.Line.GetNearestPoint(line, pointIn, point);\n
  • Get the shortest distance from a Line to the given Point.
    var distance = Phaser.Geom.Line.GetShortestDistance(line, point);\n
"},{"location":"geom-line/#equal","title":"Equal","text":"
var isEqual = Phaser.Geom.Line.Equals(line0, line1);\n

x1, y2, x2, y2 are equal.

"},{"location":"geom-line/#intersection","title":"Intersection","text":""},{"location":"geom-line/#line-to-circle","title":"Line to circle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.LineToCircle(line, circle);\n// var result = Phaser.Geom.Intersects.LineToCircle(line, circle, nearest);\n
    • nearest : Nearest point on line.
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetLineToCircle(line, circle);\n// var out = Phaser.Geom.Intersects.GetLineToCircle(line, circle, out);\n
"},{"location":"geom-line/#line-to-rectangle","title":"Line to rectangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.LineToRectangle(line, rect);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetLineToRectangle(line, rect);\n// var out = Phaser.Geom.Intersects.GetLineToRectangle(line, rect, out);\n
"},{"location":"geom-line/#line-to-triangle","title":"Line to triangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.TriangleToLine(triangle, line);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetTriangleToLine(triangle, line);\n// var out = Phaser.Geom.Intersects.GetTriangleToLine(triangle, line, out);\n
"},{"location":"geom-line/#line-to-line","title":"Line to line","text":"
  • Is intersection
    var isIntersection = Phaser.Geom.Intersects.LineToLine(line1, line2);\n
    • isIntersection : Return true if line1 and line2 are intersectioned
  • Get intersection point
    var isIntersection = Phaser.Geom.Intersects.LineToLine(line1, line2, out);\n
    • isIntersection : Return true if line1 and line2 are intersectioned
    • out : intersected point
"},{"location":"geom-point/","title":"Point","text":""},{"location":"geom-point/#introduction","title":"Introduction","text":"

Warning

The Geom.Point class and all related functions will be removed. All functionality for this can be found in the existing Vector2 math classes. All Geometry classes that currently create and return Point objects will be updated to return Vector2 objects instead.

Point shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-point/#usage","title":"Usage","text":""},{"location":"geom-point/#create-shape","title":"Create shape","text":"
var point = new Phaser.Geom.Point(x, y);\n
"},{"location":"geom-point/#clone-shape","title":"Clone shape","text":"
var point1 = Phaser.Geom.Point.Clone(point0);\n
"},{"location":"geom-point/#draw-on-graphics","title":"Draw on graphics","text":"
// graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\ngraphics.fillPointShape(point, size);\n
"},{"location":"geom-point/#set-properties","title":"Set properties","text":"
  • All properties
    point.setTo(x, y);\n
    or
    Phaser.Geom.Point.CopyFrom(source, dest);\n
  • Position
    point.x = 0;\npoint.y = 0;\n
  • Round
    • Ceil : Apply Math.ceil() to each coordinate of the given Point
      var point = Phaser.Geom.Point.Ceil(point)\n
    • Floor : Apply Math.floor() to each coordinate of the given Point.
      var point = Phaser.Geom.Point.Floor(point)\n
"},{"location":"geom-point/#symmetry","title":"Symmetry","text":"
  • Invert : x = y, y = x
    var point = Phaser.Geom.Point.Invert(point);\n
  • Negative : x = -x, y = -y
    var out = Phaser.Geom.Point.Negative(point);\n// var out = Phaser.Geom.Point.Negative(point, out);  // modify out\n
"},{"location":"geom-point/#get-properties","title":"Get properties","text":"
  • Position
    var x = point.x;\nvar y = point.y;\n
  • Type:
    var type = point.type; // 3\n
"},{"location":"geom-point/#equal","title":"Equal","text":"
var isEqual = Phaser.Geom.Point.Equals(point0, point1);\n

x, y are equal.

"},{"location":"geom-point/#points","title":"Points","text":"
  • Centroid : center-point over some points
    var out = Phaser.Geom.Point.GetCentroid(points);\n// var out = Phaser.Geom.Point.GetCentroid(points, out);  // modify out\n
  • Calculates the Axis Aligned Bounding Box (or aabb) from an array of points (rectangle)
    var rect = Phaser.Geom.Point.GetRectangleFromPoints(points);\n// var rect = Phaser.Geom.Point.GetRectangleFromPoints(points, rect);  // modify rect\n
  • Interpolate
    var out = Phaser.Geom.Point.Interpolate(pointA, pointB, t);  // out : point\n// var out = Phaser.Geom.Point.Interpolate(pointA, pointB, t, out);  // modify out\n
"},{"location":"geom-point/#intersection","title":"Intersection","text":"
  • Point to line
    var result = Phaser.Geom.Intersects.PointToLine(point, line);\n// var result = Phaser.Geom.Intersects.PointToLine(point, line, lineThickness);\n
    var result = Phaser.Geom.Intersects.PointToLineSegment(point, line);\n
"},{"location":"geom-point/#point-as-vector","title":"Point as Vector","text":"

Vector starting at (0,0)

  • Magnitude : sqrt( (x * x) + (y * y) )
    var magnitude = Phaser.Geom.Point.GetMagnitude(point);\n
    or
    var magnitudeSq = Phaser.Geom.Point.GetMagnitudeSq(point);\n
  • Project
    var out = Phaser.Geom.Point.Project(from, to);\n// var out = Phaser.Geom.Point.Project(from, to, out);  // modify out\n
    or
    var out = Phaser.Geom.Point.ProjectUnit(from, to);  // vector `from` and `to` are unit vector (length = 1)\n// var out = Phaser.Geom.Point.ProjectUnit(from, to, out);  // modify out\n
"},{"location":"geom-polygon/","title":"Polygon","text":""},{"location":"geom-polygon/#introduction","title":"Introduction","text":"

Polygon shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-polygon/#usage","title":"Usage","text":""},{"location":"geom-polygon/#create-shape","title":"Create shape","text":"
var polygon = new Phaser.Geom.Polygon(points);\n
  • points :
    • An array of number : [x0, y0, x1, y1, ...]
    • An array of points : [{x:x0, y:y0}, {x:x1, y:y1}, ...]
    • A string : 'x0 y0 x1 y1 ...'
"},{"location":"geom-polygon/#clone-shape","title":"Clone shape","text":"
var polygon1 = Phaser.Geom.Polygon.Clone(polygon0);\n
"},{"location":"geom-polygon/#draw-on-graphics","title":"Draw on graphics","text":"
  • Fill shape
    // graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\ngraphics.fillPoints(polygon.points, true);\n
  • Stroke shape
    // graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\ngraphics.strokePoints(polygon.points, true);\n
"},{"location":"geom-polygon/#set-properties","title":"Set properties","text":"
polygon.setTo(points);\n// points = [x0, y0, x1, y1, x2, y2, ...] , or [{x,y}, {x,y}, {x,y}, ...]\n
"},{"location":"geom-polygon/#get-properties","title":"Get properties","text":"
  • Points
    var points = polygon.points;    // array of points {x,y}\n
  • Area
    var area = polygon.area;\n
  • Number array
    var out = Phaser.Geom.Polygon.GetNumberArray(polygon);\n// var out = Phaser.Geom.Polygon.GetNumberArray(polygon, out);  // modify out\n
    • arr : [x0, y0, x1, y1, x2, y2, ...]
  • AABB (A minimum rectangle to cover this polygon)
    var out = Phaser.Geom.Polygon.GetAABB(polygon);\n// var out = Phaser.Geom.Polygon.GetAABB(polygon, out);\n
    • out : A rectangle object
  • Type:
    var type = polygon.type; // 4\n
"},{"location":"geom-polygon/#points-shape","title":"Point(s) & shape","text":"
  • Point is inside shape
    var isInside = polygon.contains(x, y);\n
    or
    var isInside = Phaser.Geom.Polygon.ContainsPoint(polygon, point);\n
  • Translate : Shift points.
    Phaser.Geom.Polygon.Translate(polygon, x, y);\n
  • Reverse the order of points.
    var polygon = Phaser.Geom.Polygon.Reverse(polygon);\n
  • Smooth : Takes a Polygon object and applies Chaikin's smoothing algorithm on its points.
    Phaser.Geom.Polygon.Smooth(polygon)\n
  • Simplify : Simplifies the points by running them through a combination of Douglas-Peucker and Radial Distance algorithms. Simplification dramatically reduces the number of points in a polygon while retaining its shape, giving a huge performance boost when processing it and also reducing visual noise.
    var polygon = Phaser.Geom.Polygon.Simplify(polygon);\n// var polygon = Phaser.Geom.Polygon.Simplify(polygon, tolerance, highestQuality);\n
"},{"location":"geom-polygon/#vector-to-polygon","title":"Vector to polygon","text":"
  • Get closest point of intersection between a vector and an array of polygons
    var result = Phaser.Geom.Intersects.GetLineToPolygon(line, polygons);\n// var out = Phaser.Geom.Intersects.GetLineToPolygon(line, polygons, isRay, out);\n
    • line : Vector of line object
    • polygons : A single polygon, or array of polygons
    • isRay : Is line a ray or a line segment?
    • out :
      • out.x, out.y : Intersection point
      • out.z : Closest intersection distance
      • out.w : Index of the polygon
  • Projects rays out from the given point to each line segment of the polygons.
    var out = Phaser.Geom.Intersects.GetRaysFromPointToPolygon(x, y, polygons);\n
    • x, y : The point to project the rays from.
    • polygons : A single polygon, or array of polygons
    • out : An array containing all intersections
      • out[i].x, out[i].y : Intersection point
      • out[i].z : Angle of intersection
      • out[i].w : Index of the polygon
"},{"location":"geom-rectangle/","title":"Rectangle","text":""},{"location":"geom-rectangle/#introduction","title":"Introduction","text":"

Rectangle shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-rectangle/#usage","title":"Usage","text":""},{"location":"geom-rectangle/#create-shape","title":"Create shape","text":"
var rect = new Phaser.Geom.Rectangle(x, y, width, height);\n
"},{"location":"geom-rectangle/#create-from-points","title":"Create from points","text":"

All of the given points are on or within its bounds.

var rect = Phaser.Geom.Rectangle.FromPoints(points);\n// var rect = Phaser.Geom.Rectangle.FromPoints(points, rect);  // push rect\n
  • points : an array with 4 points. [x, y], or {x:0, y:0}

or

var rect = Phaser.Geom.Rectangle.FromXY(x1, y1, x2, y2);\n// var rect = Phaser.Geom.Rectangle.FromXY(x1, y1, x2, y2, rect);  // push rect\n
"},{"location":"geom-rectangle/#clone-shape","title":"Clone shape","text":"
var rect1 = Phaser.Geom.Rectangle.Clone(rect0);\n
"},{"location":"geom-rectangle/#draw-on-graphics","title":"Draw on graphics","text":"
  • Fill shape
    // graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\ngraphics.fillRectShape(rect);\n
  • Stroke shape
    // graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\ngraphics.strokeRectShape(rect);\n

Note

x with positive/negative width is left/right bound y with positive/negative height is top/bottom bound

"},{"location":"geom-rectangle/#set-properties","title":"Set properties","text":"
  • All properties
    rect.setTo(x, y, width, height);\n
    or
    Phaser.Geom.Rectangle.CopyFrom(source, dest);\n
  • Position
    rect.setPosition(x, y);\n
    or
    rect.x = 0;\nrect.y = 0;\n
    or
    rect.left = 0;       // rect.x, rect.width\nrect.top = 0;        // rect.y, rect.height\n// rect.right = 0;   // rect.x, rect.width\n// rect.bottom = 0;  // rect.y, rect.height\nrect.centerX = 0;    // rect.x\nrect.centerY = 0;    // rect.y\n
    or
    Phaser.Geom.Rectangle.Offset(rect, dx, dy); // rect.x += dx, rect.y += dy\n
    or
    Phaser.Geom.Rectangle.OffsetPoint(rect, point); // rect.x += point.x, rect.y += point.y\n
    or
    Phaser.Geom.Rectangle.CenterOn(rect, x, y);  // rect.x = x - (rect.width / 2), rect.y = y - (rect.height / 2)\n
  • Size
    rect.setSize(width, height);\n// rect.setSize(width);   // height = width\n
    or
    rect.width = 0;\nrect.height = 0;\n
    • Scale
      Phaser.Geom.Rectangle.Scale(rect, x, y); // rect.width *= x, rect.height *= y;\n// Phaser.Geom.Rectangle.Scale(rect, x);   // y = x\n
    • Extend size to include points
      Phaser.Geom.Rectangle.MergePoints(rect, points);\n
      • points : an array of points. [x, y], or {x:0, y:0}
    • Extend size to include another rectangle
      Phaser.Geom.Rectangle.MergeRect(target, source);\n
  • Inflate
    Phaser.Geom.Rectangle.Inflate(rect, x, y);\n
    1. change size to width += x*2, height += y*2
    2. center on previous position
  • Fits the target rectangle into the source rectangle
    Phaser.Geom.Rectangle.FitInside(target, source);\n
    Preserves aspect ratio, scales and centers the target rectangle to the source rectangle
  • Fits the target rectangle around the source rectangle
    Phaser.Geom.Rectangle.FitOutside(target, source);\n
    Preserves aspect ratio, scales and centers the target rectangle to the source rectangle
  • Ceil
    Phaser.Geom.Rectangle.Ceil(rect);  // ceil x, y\n
    Phaser.Geom.Rectangle.CeilAll(rect);  // ceil x, y, width, height\n
  • Floor
    Phaser.Geom.Rectangle.Floor(rect);  // floor x, y\n
    Phaser.Geom.Rectangle.FloorAll(rect);  // floor x, y, width, height\n
"},{"location":"geom-rectangle/#get-properties","title":"Get properties","text":"
  • Position
    var x = rect.x;\nvar y = rect.y;\n
    • Bound
      var top = rect.top;\nvar left = rect.left;\nvar right = rect.right;\nvar bottom = rect.bottom;\n
      or
      var points = Phaser.Geom.Rectangle.Decompose(rect);\n// var points = Phaser.Geom.Rectangle.Decompose(rect, points); // push result points\n
      • points : top-left, top-right, bottom-right, bottom-left
    • Center
      var centerX = rect.centerX;\nvar centerY = rect.centerY;\n
      or
      var point = Phaser.Geom.Rectangle.GetCenter(rect);\n// var point = Phaser.Geom.Rectangle.GetCenter(rect, point);\n
  • Size
    var width = rect.width;\nvar height = rect.height;\n
    or
    var point = Phaser.Geom.Rectangle.GetSize(rect); // {x: rect.width, y: rect.height}\n
  • Area
    var area = Phaser.Geom.Rectangle.Area(rect);\n
  • Perimeter
    var perimeter = Phaser.Geom.Rectangle.Perimeter(rect);  // 2 * (rect.width + rect.height)\n
  • Aspect ratio
    var aspectRatio = Phaser.Geom.Rectangle.GetAspectRatio(rect);  // rect.width / rect.height\n
  • Lines around rectangle
    var topLine = rect.getLineA();  // top line of this rectangle\nvar rightLine = rect.getLineB();  // right line of this rectangle\nvar bottomLine = rect.getLineC();  // bottom line of this rectangle\nvar leftLine = rect.getLineD();  // left line of this rectangle\n// var out = rect.getLineA(out);  // top line of this rectangle\n
  • Type:
    var type = rect.type; // 5\n
"},{"location":"geom-rectangle/#points-shape","title":"Point(s) & shape","text":"
  • Get point at shape's edge
    var point = rect.getPoint(t);  // t : 0 ~ 1 (0= top-left, 0.5= bottom-right, 1= top-left)\n// var point = rect.getPoint(t, point);  // modify point\n
    or
    var point = Phaser.Geom.Rectangle.PerimeterPoint(rect, angle);  // angle in degrees\n// var point = Phaser.Geom.Rectangle.PerimeterPoint(rect, angle, point);  // push point\n
  • Get points around shape's edge
    var points = rect.getPoints(quantity);\n// var points = rect.getPoints(quantity, null, points);  // push points\n
    or calculate quantity from steps
    var points = rect.getPoints(false, step);\n// var points = rect.getPoints(false, step, points);  // push points\n
    • step : width of each step, in pixels. quantity = Perimeter(rectangle) / step;
    • points : an array of point
  • Point is inside shape
    var isInside = rect.contains(x, y);\n
    or
    var isInside = Phaser.Geom.Rectangle.ContainsPoint(rect, point);\n
  • Get a random point inside shape
    var point = rect.getRandomPoint();\n// var point = rect.getRandomPoint(point);  // modify point\n
  • Get a random point outside shape
    var point = Phaser.Geom.Rectangle.RandomOutside(outer, inner);\n// var point = Phaser.Geom.Rectangle.RandomOutside(outer, inner, point); // modify point\n
  • Rectangle is inside shape
    var isInside = Phaser.Geom.Rectangle.ContainsRect(rectA, rectB);  // rectB is inside rectA\n
"},{"location":"geom-rectangle/#rectangles","title":"Rectangles","text":"
  • Is overlapping
    var isOverlapping = Phaser.Geom.Rectangle.Overlaps(rectA, rectB);\n
  • Get intersection rectangle
    var rect = Phaser.Geom.Rectangle.Intersection(rectA, rectB);\nvar rect = Phaser.Geom.Rectangle.Intersection(rectA, rectB, rect);  // push rect\n
  • Get union rectangle
    var rect = Phaser.Geom.Rectangle.Union(rectA, rectB);\nvar rect = Phaser.Geom.Rectangle.Union(rectA, rectB, rect);  // push rect\n
"},{"location":"geom-rectangle/#empty","title":"Empty","text":"
  • Set empty
    rect.setEmpty();     // rect.x = 0, rect.y = 0, rect.width = 0, rect.height = 0\n
  • Is empty
    var isEmpty = rect.isEmpty();   // rect.radius <= 0;\n
"},{"location":"geom-rectangle/#equal","title":"Equal","text":"
  • Position, width, and height are the same
    var isEqual = Phaser.Geom.Rectangle.Equals(rect0, rect1);\n
  • Width and height are the same
    var isEqual = Phaser.Geom.Rectangle.SameDimensions(rect0, rect1);\n
"},{"location":"geom-rectangle/#intersection","title":"Intersection","text":""},{"location":"geom-rectangle/#rectangle-to-circle","title":"Rectangle to circle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.CircleToRectangle(circle, rect);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetCircleToRectangle(circle, rect);\n// var out = Phaser.Geom.Intersects.GetCircleToRectangle(circle, rect, out);\n
"},{"location":"geom-rectangle/#rectangle-to-rectangle","title":"Rectangle to rectangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.RectangleToRectangle(rectA, rectB);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetRectangleToRectangle(rectA, rectB);\n// var out = Phaser.Geom.Intersects.GetRectangleToRectangle(rectA, rectB, out);\n
"},{"location":"geom-rectangle/#rectangle-to-triangle","title":"Rectangle to triangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.RectangleToTriangle(rect, triangle);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetRectangleToTriangle(rect, triangle);\n// var out = Phaser.Geom.Intersects.GetRectangleToTriangle(rect, triangle, out);\n
"},{"location":"geom-rectangle/#rectangle-to-line","title":"Rectangle to line","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.LineToRectangle(line, rect);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetLineToRectangle(line, rect);\n// var out = Phaser.Geom.Intersects.GetLineToRectangle(line, rect, out);\n
"},{"location":"geom-rhombus/","title":"Rhombus","text":""},{"location":"geom-rhombus/#introduction","title":"Introduction","text":"

Rhombus shape and methods, extends from Polygon geometry object.

  • Author: Rex
  • Geometry object
"},{"location":"geom-rhombus/#usage","title":"Usage","text":"

Sample code

"},{"location":"geom-rhombus/#install-plugin","title":"Install plugin","text":""},{"location":"geom-rhombus/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrhombusplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrhombusplugin.min.js', true);\n
  • Add rhombus geometry object
    var rhombus = scene.plugins.get('rexrhombusplugin').add(x, y, width, height);\n
"},{"location":"geom-rhombus/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RhombusPlugin from 'phaser3-rex-plugins/plugins/rhombus-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRhombus',\nplugin: RhombusPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add rhombus geometry object
    var rhombus = scene.plugins.get('rexRhombus').add(x, y, width, height);\n
"},{"location":"geom-rhombus/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Rhombus from 'phaser3-rex-plugins/plugins/rhombus.js';\n
  • Add rhombus geometry object
    var rhombus = new Rhombus(x, y, width, height);\n
"},{"location":"geom-rhombus/#create-shape","title":"Create shape","text":"

var rhombus = scene.plugins.get('rexRhombus').add(x, y, width, height);\n
or
var rhombus = scene.plugins.get('rexRhombus').add({\nx: 0,\ny: 0,\nwidth: 40,\nheight: 20\n});\n
or
var rhombus = new rexRhombus(x, y, width, height);\n// var rhombus = new Phaser.Geom.rexRhombus(x, y, width, height);\n

  • x : Top X.
  • y : Left Y.
"},{"location":"geom-rhombus/#draw-on-graphics","title":"Draw on graphics","text":"

See Polygon shape.

"},{"location":"geom-rhombus/#set-properties","title":"Set properties","text":"
  • All properties
    rhombus.setTo(x, y, width, height);\n
  • Position
    rhombus.setPosition(x, y);\n
    or
    rhombus.x = 0;\nrhombus.y = 0;\n
    or
    rhombus.left = 0;       // rhombus.x\nrhombus.top = 0;        // rhombus.y\nrhombus.right = 0;      // rhombus.x\nrhombus.bottom = 0;     // rhombus.y\n
  • Size
    rhombus.setSize(width, height);\n
    or
    rhombus.width = width;\nrhombus.height = height;\n
"},{"location":"geom-rhombus/#get-properties","title":"Get properties","text":"

See Polygon shape.

  • Position
    • Center
      var centerX = rhombus.centerX;\nvar centerY = rhombus.centerY;\n
    • Bound
      var top = rhombus.top;\nvar left = rhombus.left;\nvar right = rhombus.right;\nvar bottom = rhombus.bottom;\n
  • Width
    var width = rhombus.width;\n
  • Height
    var width = rhombus.height;\n
  • Lines around rhombus
    var edge01 = rhombus.getLineA();\nvar edge12 = rhombus.getLineB();\nvar edge23 = rhombus.getLineC();\nvar edge34 = rhombus.getLineD();\n
    or
    var edge = rhombus.getEdge(edgeIdx);\n// var out = rhombus.getEdge(edgeIdx, out);\n
"},{"location":"geom-rhombus/#points-shape","title":"Point(s) & shape","text":"

See Polygon shape.

"},{"location":"geom-triangle/","title":"Triangle","text":""},{"location":"geom-triangle/#introduction","title":"Introduction","text":"

Triangle shape and methods, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"geom-triangle/#usage","title":"Usage","text":""},{"location":"geom-triangle/#create-shape","title":"Create shape","text":"
var triangle = new Phaser.Geom.Triangle(x1, y1, x2, y2, x3, y3);\n
"},{"location":"geom-triangle/#clone-shape","title":"Clone shape","text":"
var triangle1 = Phaser.Geom.Triangle.Clone(triangle0);\n
"},{"location":"geom-triangle/#equilateral-triangle","title":"Equilateral triangle","text":"
var triangle = Phaser.Geom.Triangle.BuildEquilateral(x1, y1, length);\n
"},{"location":"geom-triangle/#right-triangle","title":"Right triangle","text":"
var triangle = Phaser.Geom.Triangle.BuildRight(x1, y1, width, height);\n
"},{"location":"geom-triangle/#polygon-to-triangles","title":"Polygon to triangles","text":"
var out = Phaser.Geom.Triangle.BuildFromPolygon(data);\n// var out = Phaser.Geom.Triangle.BuildFromPolygon(data, holes, scaleX, scaleY);\n// out = Phaser.Geom.Triangle.BuildFromPolygon(data, holes, scaleX, scaleY, out);\n
  • data : A flat array of vertice coordinates like [x0,y0, x1,y1, x2,y2, ...]
  • out : Array of triangles
"},{"location":"geom-triangle/#draw-on-graphics","title":"Draw on graphics","text":"
  • Fill shape
    // graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\ngraphics.fillTriangleShape(triangle);\n
  • Stroke shape
    // graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\ngraphics.strokeTriangleShape(triangle);\n
"},{"location":"geom-triangle/#set-properties","title":"Set properties","text":"
  • All properties
    triangle.setTo(x1, y1, x2, y2, x3, y3);\n
    or
    Phaser.Geom.Triangle.CopyFrom(source, dest);\n
  • Position
    triangle.x1 = 0;\ntriangle.y1 = 0;\ntriangle.x2 = 0;\ntriangle.y2 = 0;\ntriangle.x3 = 0;\ntriangle.y3 = 0;\n
    or
    triangle.left = 0;       // triangle.x1, triangle.x2, triangle.x3\ntriangle.top = 0;        // triangle.y1, triangle.y2, triangle.y3\n// triangle.right = 0;   // triangle.x1, triangle.x2, triangle.x3\n// triangle.bottom = 0;  // triangle.y1, triangle.y2, triangle.y3\n
    or
    Phaser.Geom.Triangle.Offset(triangle, dx, dy); // triangle.x += dx, triangle.y += dy\n
    or
    Phaser.Geom.Triangle.CenterOn(triangle, x, y);\n
  • Rotate
    • Rotate around center (incenter)
      var triangle = Phaser.Geom.Triangle.Rotate(triangle, angle);\n
      • angle : Radian
    • Rotate around point
      var triangle = Phaser.Geom.Triangle.RotateAroundPoint(triangle, point, angle);\n
      • point : {x, y}
      • angle : Radian
    • Rotate around (x,y)
      var triangle = Phaser.Geom.Triangle.RotateAroundXY(triangle, x, y, angle);\n
      • angle : Radian
"},{"location":"geom-triangle/#get-properties","title":"Get properties","text":"
  • Position
    var x1 = triangle.x1;\nvar y1 = triangle.y1;\nvar x2 = triangle.x2;\nvar y2 = triangle.y2;\nvar x3 = triangle.x3;\nvar y3 = triangle.y3;\nvar top = triangle.top;\nvar left = triangle.left;\nvar right = triangle.right;\nvar bottom = triangle.bottom;\n
    or
    var out = Phaser.Geom.Triangle.Decompose(triangle);  // out: [{x1,y1}, {x2,y2}, {x3,y3}]\n// var out = Phaser.Geom.Triangle.Decompose(triangle, out);\n
  • Perimeter
    var perimeter = Phaser.Geom.Triangle.Perimeter(triangle);\n
  • Area
    var area = Phaser.Geom.Triangle.Area(triangle);\n
  • Lines around triangle
    var line12 = rect.getLineA();     // line from (x1, y1) to (x2, y2)\nvar line23 = rect.getLineB();     // line from (x2, y2) to (x3, y3)\nvar line31 = rect.getLineC();     // line from (x3, y3) to (x1, y1)\n
  • Centroid
    var out = Phaser.Geom.Triangle.Centroid(triangle);  // out: {x,y}\n
  • Incenter
    var out = Phaser.Geom.Triangle.InCenter(triangle);  // out: {x,y}\n// var out = Phaser.Geom.Triangle.InCenter(triangle, out);\n
  • Circumcenter
    var out = Phaser.Geom.Triangle.CircumCenter(triangle);  // out: {x,y}\n// var out = Phaser.Geom.Triangle.CircumCenter(triangle, out);\n
  • Circumcircle
    var out = Phaser.Geom.Triangle.CircumCircle(triangle);  // out: a circle object\n// var out = Phaser.Geom.Triangle.CircumCircle(triangle, out);\n
  • Type:
    var type = triangle.type; // 6\n
"},{"location":"geom-triangle/#points-shape","title":"Point(s) & shape","text":"
  • Get point at shape's edge
    var point = triangle.getPoint(t);  // t : 0 ~ 1 (angle/360)\n// var point = triangle.getPoint(t, point);  // modify point\n
  • Get a random point inside shape
    var point = triangle.getRandomPoint();\n// var point = triangle.getRandomPoint(point);  // modify point\n
  • Get points around shape's edge
    var points = triangle.getPoints(quantity);\n// var points = triangle.getPoints(quantity, null, points);  // push points\n
    or calculate quantity from steps
    var points = triangle.getPoints(false, step);\n// var points = triangle.getPoints(false, step, points);  // push points\n
    • points : an array of point
  • Point is inside shape
    var isInside = triangle.contains(x, y);\n
    or
    var isInside = Phaser.Geom.Triangle.ContainsPoint(triangle, point);\n
    • Points inside shape
      var out = Phaser.Geom.Triangle.ContainsArray(triangle, points, returnFirst);\n// var out = Phaser.Geom.Triangle.ContainsArray(triangle, points, returnFirst, out);\n
      • out : Points inside triangle
      • returnFirst : True to get fist matched point
"},{"location":"geom-triangle/#equal","title":"Equal","text":"
var isEqual = Phaser.Geom.Triangle.Equals(triangle0, triangle1);\n

Position and radius are equal.

"},{"location":"geom-triangle/#intersection","title":"Intersection","text":""},{"location":"geom-triangle/#triangle-to-circle","title":"Triangle to circle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.TriangleToCircle(triangle, circle);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetTriangleToCircle(triangle, circle);\n// var out = Phaser.Geom.Intersects.GetTriangleToCircle(triangle, circle, out);\n
"},{"location":"geom-triangle/#triangle-to-rectangle","title":"Triangle to rectangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.RectangleToTriangle(rect, triangle);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetRectangleToTriangle(rect, triangle);\n// var out = Phaser.Geom.Intersects.GetRectangleToTriangle(rect, triangle, out);\n
"},{"location":"geom-triangle/#triangle-to-triangle","title":"Triangle to triangle","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.TriangleToTriangle(triangleA, triangleB);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetTriangleToTriangle(triangleA, triangleB);\n// var out = Phaser.Geom.Intersects.GetTriangleToTriangle(triangleA, triangleB, out);\n
"},{"location":"geom-triangle/#triangle-to-line","title":"Triangle to line","text":"
  • Is intersection
    var result = Phaser.Geom.Intersects.TriangleToLine(triangle, line);\n
  • Get intersection points
    var result = Phaser.Geom.Intersects.GetTriangleToLine(triangle, line);\n// var out = Phaser.Geom.Intersects.GetTriangleToLine(triangle, line, out);\n
"},{"location":"gesture-overview/","title":"Overview","text":""},{"location":"gesture-overview/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-overview/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Object factories : scene.rexGestures.add.xxx(config)
"},{"location":"gesture-overview/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Object factories : scene.rexGestures.add.xxx(config)
"},{"location":"gesture-overview/#list-of-gesture-plugins","title":"List of gesture plugins","text":""},{"location":"gesture-overview/#one-pointer-gesture","title":"One pointer gesture","text":"
  • Tap
  • Press
  • Swipe
  • Pan
"},{"location":"gesture-overview/#two-pointers-gesture","title":"Two pointers gesture","text":"
  • Pinch
  • Rotate
"},{"location":"gesture-pan/","title":"Pan","text":""},{"location":"gesture-pan/#introduction","title":"Introduction","text":"

Get pan events of a game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"gesture-pan/#live-demos","title":"Live demos","text":"
  • Camera scroll
  • Pan & rotate
"},{"location":"gesture-pan/#usage","title":"Usage","text":"

Sample code

"},{"location":"gesture-pan/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-pan/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Add pan input
    var pan = scene.rexGestures.add.pan(config);\n// var pan = scene.rexGestures.add.pan(gameObject, config);\n
"},{"location":"gesture-pan/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add pan input
    var pan = scene.rexGestures.add.pan(config);\n// var pan = scene.rexGestures.add.pan(gameObject, config);\n
"},{"location":"gesture-pan/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Pan } from 'phaser3-rex-plugins/plugins/gestures.js';\n
  • Add pan input
    var pan = new Pan(scene, config);\n// var pan = new Pan(gameObject, config);\n
"},{"location":"gesture-pan/#create-instance","title":"Create instance","text":"
  • Pan input
    var pan = scene.rexGestures.add.pan({\n// enable: true,\n// bounds: undefined,\n\n// threshold: 10,\n});\n
    • enable : Set false to disable input events.
    • bounds : Touch detecting area rectangle, if game obect is not given.
      • undefined : Ignore this feature, default behavior.
    • threshold : Minimal movement when pointer is down.
  • Pan behavior of game object
    var pan = scene.rexGestures.add.pan(gameObject, {\n// enable: true,\n\n// threshold: 10,\n});\n
"},{"location":"gesture-pan/#enable","title":"Enable","text":"
  • Get
    var enable = pan.enable;  // enable: true, or false\n
  • Set
    pan.setEnable(enable);  // enable: true, or false\n// pan.enable = enable;\n
  • Toggle
    pan.toggleEnable();\n
"},{"location":"gesture-pan/#events","title":"Events","text":""},{"location":"gesture-pan/#pan","title":"Pan","text":"
pan.on('pan', function(pan, gameObject, lastPointer){\n}, scope);\n
  • pan.dx, pan.dy : Vector from previous pointer to current pointer.
  • pan.dWorldX, pan.dWorld : Vector from previous pointer to current pointer, in world position. i.e, including camera-zoom.
  • pan.worldX, pan.worldY : World position of current pointer.
  • pan.x, pan.y : Scene position of current pointer.
  • gameObject, pan.gameObject : Parent gameobject of this pan behavior.
  • lastPointer : Last touch pointer.
"},{"location":"gesture-pan/#pan-start","title":"Pan start","text":"
pan.on('panstart', function(pan, gameObject, lastPointer){\n}, scope);\n
  • pan.startWorldX, pan.startWorldY : World position of pan-start pointer.
  • pan.startX, pan.startY : Scene position of pan-start pointer.
  • gameObject, pan.gameObject : Parent gameobject of this pan behavior.
  • lastPointer : Last touch pointer.
"},{"location":"gesture-pan/#pan-end","title":"Pan end","text":"
pan.on('panend', function(pan, gameObject, lastPointer){\n}, scope);\n
  • pan.endWorldX, pan.endWorldY : World position of pan-end pointer.
  • pan.endX, pan.endY : Scene position of pan-end pointer.
  • gameObject, pan.gameObject : Parent gameobject of this pan behavior.
  • lastPointer : Last touch pointer.
"},{"location":"gesture-pan/#is-panned","title":"Is panned","text":"
var isPanned = pan.isPanned;\n

Return true if panned.

"},{"location":"gesture-pan/#is-pointer-inside-another-game-object","title":"Is pointer inside another game object","text":"

Under any pan event,

pan.on('panend', function(pan){\nvar isPointerInsideGameObject = pan.isPointerInGameObject(anotherGameObject);\n});\n
"},{"location":"gesture-pan/#other-properties","title":"Other properties","text":"
  • Drag threshold
    • Get
      var dragThreshold = pan.dragThreshold;\n
    • Set
      pan.setDragThreshold(dragThreshold);\n// pan.dragThreshold = dragThreshold;\n
  • Detect bounds
    • Get
      var bounds = pan.bounds;\n
    • Set
      pan.setDetectBounds(bounds);\n// pan.bounds = bounds;\n
"},{"location":"gesture-pinch/","title":"Pinch","text":""},{"location":"gesture-pinch/#introduction","title":"Introduction","text":"

Get scale factor from 2 dragging touch pointers.

  • Author: Rex
  • Member of scene
"},{"location":"gesture-pinch/#live-demos","title":"Live demos","text":"

Pinch-zoom

"},{"location":"gesture-pinch/#usage","title":"Usage","text":"

Sample code

"},{"location":"gesture-pinch/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-pinch/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Add pinch input
    var pinch = scene.rexGestures.add.pinch(config);\n// var pinch = scene.rexGestures.add.pinch(gameObject, config);\n
"},{"location":"gesture-pinch/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add pinch input
    var pinch = scene.rexGestures.add.pinch(config);\n// var pinch = scene.rexGestures.add.pinch(gameObject, config);\n
"},{"location":"gesture-pinch/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Pinch } from 'phaser3-rex-plugins/plugins/gestures.js';\n
  • Add pinch input
    var pinch = new Pinch(scene, config);\n// var pinch = new Pinch(gameObject, config);\n
"},{"location":"gesture-pinch/#create-instance","title":"Create instance","text":"
  • Pinch input
    var pinch = scene.rexGestures.add.pinch({\n// enable: true,\n// bounds: undefined,\n\n// threshold: 0,\n});\n
    • enable : Set false to disable input events.
    • bounds : A rectangle object or undefined (to use game window as rectangle object), for detecting the position of cursor.
    • threshold : Fire pinch events after dragging distances of catched pointers are larger than this threshold.
  • Pinch behavior of game object
    var pan = scene.rexGestures.add.pinch(gameObject, {\n// enable: true,\n// bounds: undefined,\n\n// threshold: 0,\n});\n
    • Start pinching when pointer-down on this game object.
"},{"location":"gesture-pinch/#enable","title":"Enable","text":"
  • Get
    var enable = pinch.enable;  // enable: true, or false\n
  • Set
    pinch.setEnable(enable);  // enable: true, or false\n// pinch.enable = enable;\n
  • Toggle
    pinch.toggleEnable();\n
"},{"location":"gesture-pinch/#events","title":"Events","text":""},{"location":"gesture-pinch/#on-dragging","title":"On dragging","text":"
  • On dragging 1st touch pointer, fired when 1st touch pointer is moving
    pinch.on('drag1', function(pinch) {\n// var drag1Vector = pinch.drag1Vector; // drag1Vector: {x, y}\n}, scope);\n
    • pinch.drag1Vector : Drag vector from prevoius touch position to current touch position of 1st catched touch pointer.
  • On dragging 2 touch pointers, fired when any catched touch pointer moved.
    pinch.on('pinch', function(pinch) {\n// var scaleFactor = pinch.scaleFactor;\n// gameObject.scaleX *= scaleFactor;\n// gameObject.scaleY *= scaleFactor;\n}, scope);\n
    • pinch.scaleFactor : Rate of distance change between 2 catched touch pointers.
"},{"location":"gesture-pinch/#on-drag-start-on-drag-end","title":"On drag start, on drag end","text":"
  • On drag 1 touch pointer start, fired when catching 1st touch pointer.
    pinch.on('drag1start', function(pinch) {\n\n}, scope);\n
  • On drag 1 touch pointer end, fired when releasing the last one catched touch pointer.
    pinch.on('drag1end', function(pinch) {\n\n}, scope);\n
  • On drag 2 touch pointers start, fired when catching 2 touch pointers.
    pinch.on('pinchstart', function(pinch) {\n\n}, scope);\n
  • On drag 2 touch pointers end, fired when releasing any catched touch pointer.
    pinch.on('pinchend', function(pinch) {\n\n}, scope);\n
"},{"location":"gesture-pinch/#scale-factor","title":"Scale factor","text":"
var scaleFactor = pinch.scaleFactor;\n

Rate of distance change between 2 catched touch pointers. (i.e current distance between 2 catched touch pointers / previous distance ).

"},{"location":"gesture-pinch/#drag-vector-of-1st-touch-pointer","title":"Drag vector of 1st touch pointer","text":"
var drag1Vector = pinch.drag1Vector; // {x, y}\n
"},{"location":"gesture-pinch/#catched-touch-pointers","title":"Catched touch pointers","text":"
  • Pointer 0, available when state is 1
    var pointer0 = pinch.pointers[0];\n
    • Position of pointer
      var x = pointer0.x;\nvar y = pointer0.y;\nvar worldX = pointer0.worldX;\nvar worldY = pointer0.worldY;\n
  • Pointer 1, available when state is 2
    var pointer1 = pinch.pointers[1];\n
"},{"location":"gesture-pinch/#is-pinched","title":"Is pinched","text":"
var isPinched = pinch.isPinched;\n

Return true if pinched.

"},{"location":"gesture-pinch/#is-pointer-inside-another-game-object","title":"Is pointer inside another game object","text":"

Under any pinch event,

pinch.on('pinch', function(pinch) {\nvar isPointer0InsideGameObject = pinch.isPointer0InGameObject(anotherGameObject);\nvar isPointer1InsideGameObject = pinch.isPointer1InGameObject(anotherGameObject);\n});\n
"},{"location":"gesture-pinch/#other-properties","title":"Other properties","text":"
  • Drag threshold
    • Get
      var dragThreshold = pinch.dragThreshold;\n
    • Set
      pinch.setDragThreshold(dragThreshold);\n// pinch.dragThreshold = dragThreshold;\n
  • Detect bounds
    • Get
      var bounds = pinch.bounds;\n
    • Set
      pinch.setDetectBounds(bounds);\n// pinch.bounds = bounds;\n
"},{"location":"gesture-press/","title":"Press","text":""},{"location":"gesture-press/#introduction","title":"Introduction","text":"

Get press events of a game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"gesture-press/#live-demos","title":"Live demos","text":"
  • Press object
"},{"location":"gesture-press/#usage","title":"Usage","text":"

Sample code

"},{"location":"gesture-press/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-press/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Add press input
    var press = scene.rexGestures.add.press(config);\n// var press = scene.rexGestures.add.press(gameObject, config);\n
"},{"location":"gesture-press/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add press input
    var press = scene.rexGestures.add.press(config);\n// var press = scene.rexGestures.add.press(gameObject, config);\n
"},{"location":"gesture-press/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Press } from 'phaser3-rex-plugins/plugins/gestures.js';\n
  • Add press input
    var press = new Press(scene, config);\n// var press = new Press(gameObject, config);\n
"},{"location":"gesture-press/#create-instance","title":"Create instance","text":"
  • Press input
    var press = scene.rexGestures.add.press({\n// enable: true,\n// bounds: undefined,\n\n// time: 251,\n// threshold: 9,\n});\n
    • enable : Set false to disable input events.
    • bounds : Touch detecting area rectangle, if game obect is not given.
      • undefined : Ignore this feature, default behavior.
    • time : Minimal time of the pointer to be pressed.
    • threshold : Minimal movement when pointer is down.
  • Press behavior of game object
    var press = scene.rexGestures.add.press(gameObject, {\n// enable: true,\n\n// time: 251,\n// threshold: 9,\n});\n
"},{"location":"gesture-press/#enable","title":"Enable","text":"
  • Get
    var enable = press.enable;  // enable: true, or false\n
  • Set
    press.setEnable(enable);  // enable: true, or false\n// press.enable = enable;\n
  • Toggle
    press.toggleEnable();\n
"},{"location":"gesture-press/#events","title":"Events","text":""},{"location":"gesture-press/#pressing-start","title":"Pressing start","text":"
press.on('pressstart', function(press, gameObject, lastPointer){\n}, scope);\n
  • press.gameObject : Parent gameobject of this press behavior.
  • press.worldX, press.worldY : World position of pressing start.
  • press.x, press.y : Scene position of pressing start.
  • gameObject, press.gameObject : Parent gameobject of this press behavior.
  • lastPointer : Last touch pointer.
"},{"location":"gesture-press/#pressing-end","title":"Pressing end","text":"
press.on('pressend', function(press, gameObject, lastPointer){\n}, scope);\n
"},{"location":"gesture-press/#is-pressed","title":"Is pressed","text":"
var isPressed = press.isPressed;\n

Return true if pressed.

"},{"location":"gesture-press/#is-pointer-inside-another-game-object","title":"Is pointer inside another game object","text":"

Under any press event,

press.on('pressstart', function(press){\nvar isPointerInsideGameObject = press.isPointerInGameObject(anotherGameObject);\n});\n
"},{"location":"gesture-press/#other-properties","title":"Other properties","text":"
  • Hold time
    • Get
      var holdTime = press.holdTime;\n
    • Set
      press.setHoldTime(holdTime);\n// press.holdTime = holdTime;\n
  • Drag threshold
    • Get
      var dragThreshold = press.dragThreshold;\n
    • Set
      press.setDragThreshold(dragThreshold);\n// press.dragThreshold = dragThreshold;\n
  • Detect bounds
    • Get
      var bounds = press.bounds;\n
    • Set
      press.setDetectBounds(bounds);\n// press.bounds = bounds;\n
"},{"location":"gesture-rotate/","title":"Rotate","text":""},{"location":"gesture-rotate/#introduction","title":"Introduction","text":"

Get spin angle from 2 dragging touch pointers.

  • Author: Rex
  • Member of scene
"},{"location":"gesture-rotate/#live-demos","title":"Live demos","text":"
  • Rotate & rotate
"},{"location":"gesture-rotate/#usage","title":"Usage","text":"

Sample code

"},{"location":"gesture-rotate/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-rotate/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Add rotate input
    var rotate = scene.rexGestures.add.rotate(config);\n// var rotate = scene.rexGestures.add.rotate(gameObject, config);\n
"},{"location":"gesture-rotate/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add rotate input
    var rotate = scene.rexGestures.add.rotate(config);\n// var rotate = scene.rexGestures.add.rotate(gameObject, config);\n
"},{"location":"gesture-rotate/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Rotate } from 'phaser3-rex-plugins/plugins/gestures.js';\n
  • Add rotate input
    var rotate = new Rotate(scene, config);\n// var rotate = new Rotate(gameObject, config);\n
"},{"location":"gesture-rotate/#create-instance","title":"Create instance","text":"
  • Rotate input
    var rotate = scene.rexGestures.add.rotate({\n// enable: true,\n// bounds: undefined,\n\n// threshold: 0,\n});\n
    • enable : Set false to disable input events.
    • bounds : A rectangle object or undefined (to use game window as rectangle object), for detecting the position of cursor.
    • threshold : Fire rotate events after dragging distances of catched pointers are larger than this threshold.
  • Rotate behavior of game object
    var rotate = scene.rexGestures.add.rotate(gameObject, {\n// enable: true,\n// bounds: undefined,\n\n// threshold: 0,\n});\n
    • Start rotation when pointer-down on this game object.
"},{"location":"gesture-rotate/#enable","title":"Enable","text":"
  • Get
    var enable = rotate.enable;  // enable: true, or false\n
  • Set
    rotate.setEnable(enable);  // enable: true, or false\n// rotate.enable = enable;\n
  • Toggle
    rotate.toggleEnable();\n
"},{"location":"gesture-rotate/#events","title":"Events","text":""},{"location":"gesture-rotate/#on-dragging","title":"On dragging","text":"
  • On dragging 1st touch pointer, fired when 1st touch pointer is moving
    rotate.on('drag1', function(rotate) {\n// var drag1Vector = rotate.drag1Vector; // drag1Vector: {x, y}\n}, scope);\n
    • rotate.drag1Vector : Drag vector from prevoius touch position to current touch position of 1st catched touch pointer.
  • On dragging 2 touch pointers, fired when any catched touch pointer moved.
    rotate.on('rotate', function(rotate) {\n// rotate.spinObject(gameObejects);\n// var angle = rotate.rotation;\n}, scope);\n
    • rotate.spinObject(gameObejects) : Drag and spin an array of game object, or a game object around current center of 2 dragging pointers.
    • rotate.rotation : Return spin angle of 2 dragging pointers, in radius.
"},{"location":"gesture-rotate/#on-drag-start-on-drag-end","title":"On drag start, on drag end","text":"
  • On drag 1 touch pointer start, fired when catching 1st touch pointer.
    rotate.on('drag1start', function(rotate) {\n\n}, scope);\n
  • On drag 1 touch pointer end, fired when releasing the last one catched touch pointer.
    rotate.on('drag1end', function(rotate) {\n\n}, scope);\n
  • On drag 2 touch pointers start, fired when catching 2 touch pointers.
    rotate.on('rotatestart', function(rotate) {\n\n}, scope);\n
  • On drag 2 touch pointers end, fired when releasing any catched touch pointer.
    rotate.on('rotateend', function(rotate) {\n\n}, scope);\n
"},{"location":"gesture-rotate/#spin-game-object","title":"Spin game object","text":"
rotate.spinObject(gameObejects);\n

Drag and spin game objects around current center of 2 dragging pointers. Uses this function under 'rotate' event.

  • gameObejects : An array of game object, or a game object.
"},{"location":"gesture-rotate/#spin-angle","title":"Spin angle","text":"
var angle = rotate.rotation;\n

Spin angle of 2 dragging pointers, in radius.

"},{"location":"gesture-rotate/#drag-vector-of-1st-touch-pointer","title":"Drag vector of 1st touch pointer","text":"
var drag1Vector = rotate.drag1Vector; // {x, y}\n
"},{"location":"gesture-rotate/#catched-touch-pointers","title":"Catched touch pointers","text":"
  • Pointer 0, available when state is 1
    var pointer0 = rotate.pointers[0];\n
    • Position of pointer
      var x = pointer0.x;\nvar y = pointer0.y;\nvar worldX = pointer0.worldX;\nvar worldY = pointer0.worldY;\n
  • Pointer 1, available when state is 2
    var pointer0 = rotate.pointers[1];\n
"},{"location":"gesture-rotate/#is-rotated","title":"Is rotated","text":"
var isRotated = rotate.isRotated;\n

Return true if pinched.

"},{"location":"gesture-rotate/#is-pointer-inside-another-game-object","title":"Is pointer inside another game object","text":"

Under any rotate event,

rotate.on('rotate', function(rotate) {\nvar isPointer0InsideGameObject = rotate.isPointer0InGameObject(anotherGameObject);\nvar isPointer1InsideGameObject = rotate.isPointer1InGameObject(anotherGameObject);\n});\n
"},{"location":"gesture-rotate/#other-properties","title":"Other properties","text":"
  • Drag threshold
    • Get
      var dragThreshold = rotate.dragThreshold;\n
    • Set
      rotate.setDragThreshold(dragThreshold);\n// rotate.dragThreshold = dragThreshold;\n
  • Detect bounds
    • Get
      var bounds = rotate.bounds;\n
    • Set
      rotate.setDetectBounds(bounds);\n// rotate.bounds = bounds;\n
"},{"location":"gesture-swipe/","title":"Swipe","text":""},{"location":"gesture-swipe/#introduction","title":"Introduction","text":"

Get swipe events of a game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"gesture-swipe/#live-demos","title":"Live demos","text":"
  • Swipe
"},{"location":"gesture-swipe/#usage","title":"Usage","text":"

Sample code

"},{"location":"gesture-swipe/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-swipe/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Add swipe input
    var swipe = scene.rexGestures.add.swipe(config);\n// var swipe = scene.rexGestures.add.swipe(gameObject, config);\n
"},{"location":"gesture-swipe/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add swipe input
    var swipe = scene.rexGestures.add.swipe(config);\n// var swipe = scene.rexGestures.add.swipe(gameObject, config);\n
"},{"location":"gesture-swipe/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Swipe } from 'phaser3-rex-plugins/plugins/gestures.js';\n
  • Add swipe input
    var swipe = new Swipe(scene, config);\n// var swipe = new Swipe(gameObject, config);\n
"},{"location":"gesture-swipe/#create-instance","title":"Create instance","text":"
  • Swipe input
    var swipe = scene.rexGestures.add.swipe({\n// enable: true,\n// bounds: undefined,\n\n// threshold: 10,\n// velocityThreshold: 1000,\n// dir: '8dir',\n});\n
    • enable : Set false to disable input events.
    • bounds : Touch detecting area rectangle, if game obect is not given.
      • undefined : Ignore this feature, default behavior.
    • time : Max time of the pointer to be down.
    • threshold : Minimal movement when pointer is down.
    • velocityThreshold : Minimal dragging speed.
    • dir :
      • 'up&down', or 0 : Get up or down state only.
      • 'left&right', or 1 : Get left or right state only.
      • '4dir', or 2 : Get up, down, left or right state.
      • '8dir', or 3 : Get up, up/left, up/right, down, down/left, down/right, left, or right state.
  • Swipe behavior of game object
    var swipe = scene.rexGestures.add.swipe(gameObject, {\n// enable: true,\n\n// threshold: 10,\n// velocityThreshold: 1000,\n// direction: '8dir',\n});\n
"},{"location":"gesture-swipe/#enable","title":"Enable","text":"
  • Get
    var enable = swipe.enable;  // enable: true, or false\n
  • Set
    swipe.setEnable(enable);  // enable: true, or false\n// swipe.enable = enable;\n
  • Toggle
    swipe.toggleEnable();\n
"},{"location":"gesture-swipe/#events","title":"Events","text":""},{"location":"gesture-swipe/#swipe","title":"Swipe","text":"
swipe.on('swipe', function(swipe, gameObject, lastPointer){\n}, scope);\n
  • swipe.left, swipe.right, swipe.up, swipe.down : Swipe direction states.
  • swipe.worldX, swipe.worldY : World position of swiping start.
  • swipe.x, swipe.y : Scene position of swiping start.
  • swipe.dragVelocity : Velocity of dragging.
  • gameObject, swipe.gameObject : Parent gameobject of this pan behavior.
  • lastPointer : Last touch pointer.
"},{"location":"gesture-swipe/#is-swiped","title":"Is swiped","text":"
var isSwiped = swipe.isSwiped;\n

Return true if panning.

"},{"location":"gesture-swipe/#is-pointer-inside-another-game-object","title":"Is pointer inside another game object","text":"

Under any swipe event,

swipe.on('swipe', function(swipe){\nvar isPointerInsideGameObject = swipe.isPointerInGameObject(anotherGameObject);\n});\n
"},{"location":"gesture-swipe/#other-properties","title":"Other properties","text":"
  • Drag threshold
    • Get
      var dragThreshold = swipe.dragThreshold;\n
    • Set
      swipe.setDragThreshold(dragThreshold);\n// swipe.dragThreshold = dragThreshold;\n
  • Velocity threshold
    • Get
      var velocityThreshold = swipe.velocityThreshold;\n
    • Set
      swipe.setVelocityThreshold(velocityThreshold);\n// swipe.velocityThreshold = velocityThreshold;\n
  • Direction mode
    • Get
      var dirMode = swipe.dirMode;  // 0,1,2,3\n
    • Set
      swipe.setDirectionMode(dirMode);  // 0,1,2,3,'up&down','left&right','4dir','8dir'\n// swipe.dirMode = dirMode;  // 0,1,2,3\n
  • Detect bounds
    • Get
      var bounds = swipe.bounds;\n
    • Set
      swipe.setDetectBounds(bounds);\n// swipe.bounds = bounds;\n
"},{"location":"gesture-tap/","title":"Tap","text":""},{"location":"gesture-tap/#introduction","title":"Introduction","text":"

Get tap/multi-taps events of a game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"gesture-tap/#live-demos","title":"Live demos","text":"
  • Tap object
"},{"location":"gesture-tap/#usage","title":"Usage","text":"

Sample code

"},{"location":"gesture-tap/#install-plugin","title":"Install plugin","text":""},{"location":"gesture-tap/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexgesturesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgesturesplugin.min.js', 'rexGestures', 'rexGestures');\n
  • Add tap input
    var tap = scene.rexGestures.add.tap(config);\n// var tap = scene.rexGestures.add.tap(gameObject, config);\n
"},{"location":"gesture-tap/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GesturesPlugin from 'phaser3-rex-plugins/plugins/gestures-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexGestures',\nplugin: GesturesPlugin,\nmapping: 'rexGestures'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add tap input
    var tap = scene.rexGestures.add.tap(config);\n// var tap = scene.rexGestures.add.tap(gameObject, config);\n
"},{"location":"gesture-tap/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Tap } from 'phaser3-rex-plugins/plugins/gestures.js';\n
  • Add tap input
    var tap = new Tap(scene, config);\n// var tap = new Tap(gameObject, config);\n
"},{"location":"gesture-tap/#create-instance","title":"Create instance","text":"
  • Tap input
    var tap = scene.rexGestures.add.tap({\n// enable: true,\n// bounds: undefined,\n\n// time: 250,\n// tapInterval: 200,\n// threshold: 9,\n// tapOffset: 10,\n\n// taps: undefined,\n// minTaps: undefined,\n// maxTaps: undefined,\n});\n
    • enable : Set false to disable input events.
    • bounds : Touch detecting area rectangle, if game obect is not given.
      • undefined : Ignore this feature, default behavior.
    • time : Max time of the pointer to be down.
    • tapInterval : Max time between the multi-tap taps.
    • threshold : Minimal movement when pointer is down.
    • tapOffset : A multi-tap can be a bit off the initial position.
    • taps : Fire tap event only when taps count reaches this value.
      • undefined : Fire tap event only when tapped end. i.e pointer-up time exceeds tapInterval.
    • minTaps : Fire tap event only when taps count is larger than this value.
      • undefined : Don't check taps count.
    • maxTaps : Fire tap event only when taps count is less than this value.
      • undefined : Don't check taps count.
  • Tap behavior of game object
    var tap = scene.rexGestures.add.tap(gameObject, {\n// enable: true,\n\n// time: 250,\n// tapInterval: 200,\n// threshold: 9,\n// tapOffset: 10,\n\n// taps: undefined,\n// minTaps: undefined,\n// maxTaps: undefined,\n});\n
"},{"location":"gesture-tap/#enable","title":"Enable","text":"
  • Get
    var enable = tap.enable;  // enable: true, or false\n
  • Set
    tap.setEnable(enable);  // enable: true, or false\n// tap.enable = enable;\n
  • Toggle
    tap.toggleEnable();\n
"},{"location":"gesture-tap/#events","title":"Events","text":""},{"location":"gesture-tap/#tap","title":"Tap","text":"
tap.on('tap', function(tap, gameObject, lastPointer){\n}, scope);\n
  • tap.tapsCount : Taps count.
  • gameObject, tap.gameObject : Parent gameobject of this tap behavior.
  • tap.worldX, tap.worldY : World position of first tapping.
  • tap.x, tap.y : Scene position of first tapping.
  • lastPointer : Last touch pointer.
tap.on(tapsCount + 'tap', function(tap, gameObject, lastPointer){\n}, scope);\n
  • tapsCount + 'tap' : 1tap, 2tap, 3tap, etc ...
"},{"location":"gesture-tap/#tapping-start","title":"Tapping start","text":"

Each pointer-down will increase taps count and fire tappingstart event.

tap.on('tappingstart', function(tap, gameObject, lastPointer){\n}, scope);\n
"},{"location":"gesture-tap/#is-tapped","title":"Is tapped","text":"
var isTapped = tap.isTapped;\n

Return true if tapped end.

"},{"location":"gesture-tap/#is-pointer-inside-another-game-object","title":"Is pointer inside another game object","text":"

Under any tap event,

tap.on('tap', function(tap){\nvar isPointerInsideGameObject = tap.isPointerInGameObject(anotherGameObject);\n});\n
"},{"location":"gesture-tap/#other-properties","title":"Other properties","text":"
  • Hold time
    • Get
      var holdTime = tap.holdTime;\n
    • Set
      tap.setHoldTime(holdTime);\n// tap.holdTime = holdTime;\n
  • Tap interval
    • Get
      var tapInterval = tap.tapInterval;\n
    • Set
      tap.setTapInterval(tapInterval);\n// tap.tapInterval = tapInterval;\n
  • Drag threshold
    • Get
      var dragThreshold = tap.dragThreshold;\n
    • Set
      tap.setDragThreshold(dragThreshold);\n// tap.dragThreshold = dragThreshold;\n
  • Tap offset
    • Get
      var tapOffset = tap.tapOffset;\n
    • Set
      tap.setTapOffset(tapOffset);\n// tap.tapOffset = tapOffset;\n
  • Max taps
    • Get
      var maxTaps = tap.maxTaps;\n
    • Set
      tap.setMaxTaps(maxTaps);\n// tap.maxTaps = maxTaps;\n
  • Min taps
    • Get
      var minTaps = tap.minTaps;\n
    • Set
      tap.setMinTaps(minTaps);\n// tap.minTaps = minTaps;\n
  • Taps
    taps.setTaps(taps);\n// taps.setTaps(minTaps, maxTaps);\n
  • Detect bounds
    • Get
      var bounds = taps.bounds;\n
    • Set
      taps.setDetectBounds(bounds);\n// taps.bounds = bounds;\n
"},{"location":"graphics/","title":"Graphics","text":""},{"location":"graphics/#introduction","title":"Introduction","text":"

Drawing on webgl or canvas, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"graphics/#usage","title":"Usage","text":""},{"location":"graphics/#add-graphics-object","title":"Add graphics object","text":"
var graphics = scene.add.graphics();\n

or

var graphics = scene.add.graphics({\nx: 0,\ny: 0,\n\n// lineStyle: {\n//     width: 1,\n//     color: 0xffffff,\n//     alpha: 1\n// },\n// fillStyle: {\n//     color: 0xffffff,\n//     alpha: 1\n// },\n\nadd: true\n});\n
"},{"location":"graphics/#custom-class","title":"Custom class","text":"
  • Define class
    class MyGraphics extends Phaser.GameObjects.Graphics {\nconstructor(scene, options) {\nsuper(scene, options);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var graphics = new MyGraphics(scene, options);\n
"},{"location":"graphics/#drawing-commands","title":"Drawing commands","text":""},{"location":"graphics/#set-style","title":"Set style","text":"
  • Set default line style and fill style
    graphics.setDefaultStyles({\nlineStyle: {\nwidth: 1,\ncolor: 0xffffff,\nalpha: 1\n},\nfillStyle: {\ncolor: 0xffffff,\nalpha: 1\n}\n});\n
  • Set line style
    graphics.lineStyle(lineWidth, color, alpha);   // color: 0xRRGGBB\n
  • Set fill style
    • Fill color
      graphics.fillStyle(color, alpha);   // color: 0xRRGGBB\n
    • Fill gradient color (WebGL only)
      graphics.fillGradientStyle(topLeft, topRight, bottomLeft, bottomRight, alpha);  // alpha= 1\n// graphics.fillGradientStyle(topLeft, topRight, bottomLeft, bottomRight, alphaTopLeft, alphaTopRight, alphaBottomLeft, alphaBottomRight);\n
      • topLeft : The tint being applied to the top-left of the Game Object.
      • topRight : The tint being applied to the top-right of the Game Object.
      • bottomLeft : The tint being applied to the bottom-left of the Game Object.
      • bottomRight : The tint being applied to the bottom-right of the Game Object.
      • alphaTopLeft : The top left alpha value.
      • alphaTopRight : The top right alpha value.
      • alphaBottomLeft : The bottom left alpha value.
      • alphaBottomRight : The bottom right alpha value.
"},{"location":"graphics/#clear","title":"Clear","text":"
graphics.clear();\n
"},{"location":"graphics/#path","title":"Path","text":"
graphics.beginPath();\ngraphics.closePath();\ngraphics.fillPath(); // = graphics.fill()\ngraphics.strokePath(); // = graphics.stroke()\n
"},{"location":"graphics/#rectangle","title":"Rectangle","text":"
graphics.fillRectShape(rect); // rect: {x, y, width, height}\ngraphics.fillRect(x, y, width, height);\ngraphics.strokeRectShape(rect);  // rect: {x, y, width, height}\ngraphics.strokeRect(x, y, width, height);\n
"},{"location":"graphics/#rounded-rectangle","title":"Rounded rectangle","text":"
graphics.fillRoundedRect(x, y, width, height, radius);\ngraphics.strokeRoundedRect(x, y, width, height, radius);\n
  • radius : number or an object {tl, tr, bl, br},
    • Positive value : Convex corner.
    • Negative value : Concave corner.
"},{"location":"graphics/#triangle","title":"Triangle","text":"
graphics.fillTriangleShape(triangle); // triangle: {x1, y1, x2, y2, x3, y3}\ngraphics.fillTriangle(x1, y1, x2, y2, x3, y3);\ngraphics.strokeTriangleShape(triangle); // triangle: {x1, y1, x2, y2, x3, y3}\ngraphics.strokeTriangle(x1, y1, x2, y2, x3, y3);\n
"},{"location":"graphics/#point","title":"Point","text":"
graphics.fillPointShape(point, size); // point: {x, y}\ngraphics.fillPoint(x, y, size);\n
"},{"location":"graphics/#line","title":"Line","text":"
graphics.strokeLineShape(line); // line: {x1, y1, x2, y2}\ngraphics.lineBetween(x1, y1, x2, y2);\ngraphics.lineTo(x, y);\ngraphics.moveTo(x, y);\n
"},{"location":"graphics/#lines","title":"Lines","text":"
graphics.strokePoints(points, closeShape, closePath, endIndex);  // points: [{x, y}, ...]\ngraphics.fillPoints(points, closeShape, closePath, endIndex);  // points: [{x, y}, ...]\n
  • points : Array of {x, y}
  • closeShape : When true, the shape is closed by joining the last point to the first point.
  • closePath : When true, the path is closed before being stroked.
  • endIndex : The index of points to stop drawing at. Defaults to points.length.
"},{"location":"graphics/#circle","title":"Circle","text":"
graphics.fillCircleShape(circle); // circle: {x, y, radius}\ngraphics.fillCircle(x, y, radius);\ngraphics.strokeCircleShape(circle);  // circle: {x, y, radius}\ngraphics.strokeCircle(x, y, radius);\n

Draw or fill circle shape by points.

"},{"location":"graphics/#ellipse","title":"Ellipse","text":"
graphics.strokeEllipseShape(ellipse, smoothness);   // ellipse: Phaser.Geom.Ellipse\ngraphics.strokeEllipse(x, y, width, height, smoothness);\ngraphics.fillEllipseShape(ellipse, smoothness);    // ellipse: Phaser.Geom.Ellipse\ngraphics.fillEllipse(x, y, width, height, smoothness);\n

Draw or fill ellipse shape by points.

"},{"location":"graphics/#arc","title":"Arc","text":"
graphics.arc(x, y, radius, startAngle, endAngle, anticlockwise);\ngraphics.arc(x, y, radius, startAngle, endAngle, anticlockwise, overshoot);\n

Draw arc curve by points.

"},{"location":"graphics/#pie-chart-slice","title":"Pie-chart slice","text":"
graphics.slice(x, y, radius, startAngle, endAngle, anticlockwise);\ngraphics.slice(x, y, radius, startAngle, endAngle, anticlockwise, overshoot);\n

Draw pie-chart slice shape by points.

Fill this shape

graphics.fillPath();\n
"},{"location":"graphics/#clear-pattern","title":"Clear pattern","text":"
graphics.setTexture();\n
"},{"location":"graphics/#transfer","title":"Transfer","text":"
graphics.save();\ngraphics.restore();\ngraphics.translateCanvas(x, y);\ngraphics.scaleCanvas(x, y);\ngraphics.rotateCanvas(radians);\n
"},{"location":"graphics/#generate-texture","title":"Generate texture","text":"
graphics.generateTexture(key, width, height);  // key: texture key\n
"},{"location":"graphics/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"graphics/#create-mask","title":"Create mask","text":"
var mask = graphics.createGeometryMask();\n

See mask

"},{"location":"graphics/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"gridalign/","title":"Quad/Hexagon grid align","text":""},{"location":"gridalign/#introduction","title":"Introduction","text":"

Align objects on quadrilateral or hexagon grid.

See also built-in grid-align.

  • Author: Rex
  • Methods
"},{"location":"gridalign/#usage","title":"Usage","text":"

Sample code

"},{"location":"gridalign/#install-plugin","title":"Install plugin","text":""},{"location":"gridalign/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexgridalignplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgridalignplugin.min.js', true);\n
  • Grid-align objects
    scene.plugins.get('rexgridalignplugin').quad(gameObjects, config);\nscene.plugins.get('rexgridalignplugin').hexagon(gameObjects, config);\n
"},{"location":"gridalign/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GridAlignPlugin from 'phaser3-rex-plugins/plugins/gridalign-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGridAlign',\nplugin: GridAlignPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Grid-align objects
    scene.plugins.get('rexGridAlign').quad(gameObjects, config);\nscene.plugins.get('rexGridAlign').hexagon(gameObjects, config);\n
"},{"location":"gridalign/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { QuadGridAlign, HexagonGridAlign } from 'phaser3-rex-plugins/plugins/gridalign.js';\n
  • Grid-align objects
    QuadGridAlign(gameObjects, config);\nHexagonGridAlign(gameObjects, config);\n
"},{"location":"gridalign/#quadrilateral-grid","title":"Quadrilateral grid","text":"
scene.plugins.get('rexGridAlign').quad(gameObjects, {\nwidth: -1,\nheight: -1,\ncellWidth: 1,\ncellHeight: 1,\ntype: 0,\nposition: Phaser.Display.Align.CENTER,\nx: 0,\ny: 0\n});\n
  • width : The width of the grid in items (not pixels). -1 means lay all items out horizontally, regardless of quantity.
  • height : The height of the grid in items (not pixels). -1 means lay all items out vertically, regardless of quantity.
  • cellWidth : The width of the cell, in pixels.
  • cellHeight : The height of the cell, in pixels.
  • type
    • 0, or orthogonal
    • 1, or isometric
  • position : The alignment position.
    • 0, or Phaser.Display.Align.TOP_LEFT
    • 1, or Phaser.Display.Align.TOP_CENTER
    • 2, or Phaser.Display.Align.TOP_RIGHT
    • 3, or Phaser.Display.Align.LEFT_TOP
    • 4, or Phaser.Display.Align.LEFT_CENTER
    • 5, or Phaser.Display.Align.LEFT_BOTTOM
    • 6, or Phaser.Display.Align.CENTER
    • 7, or Phaser.Display.Align.RIGHT_TOP
    • 8, or Phaser.Display.Align.RIGHT_CENTER
    • 9, or Phaser.Display.Align.RIGHT_BOTTOM
    • 10, or Phaser.Display.Align.BOTTOM_LEFT
    • 11, or Phaser.Display.Align.BOTTOM_CENTER
    • 12, or Phaser.Display.Align.BOTTOM_RIGHT
  • x, y : Position of first item.
"},{"location":"gridalign/#hexagon-grid","title":"Hexagon grid","text":"
scene.plugins.get('rexGridAlign').hexagon(gameObjects, {\nwidth: -1,\nheight: -1,\ncellWidth: 1,\ncellHeight: 1,\nstaggeraxis: 'x',\nstaggerindex: 'odd',\nposition: Phaser.Display.Align.CENTER,\nx: 0,\ny: 0\n});\n
  • width : The width of the grid in items (not pixels). -1 means lay all items out horizontally, regardless of quantity.
  • height : The height of the grid in items (not pixels). -1 means lay all items out vertically, regardless of quantity.
  • cellWidth : The width of the cell, in pixels.
  • cellHeight : The height of the cell, in pixels.
  • staggeraxis
    • 0, or y
    • 1, or x
  • staggerindex
    • 0, or even
    • 1, or odd
  • position : The alignment position.
    • 0, or Phaser.Display.Align.TOP_LEFT
    • 1, or Phaser.Display.Align.TOP_CENTER
    • 2, or Phaser.Display.Align.TOP_RIGHT
    • 3, or Phaser.Display.Align.LEFT_TOP
    • 4, or Phaser.Display.Align.LEFT_CENTER
    • 5, or Phaser.Display.Align.LEFT_BOTTOM
    • 6, or Phaser.Display.Align.CENTER
    • 7, or Phaser.Display.Align.RIGHT_TOP
    • 8, or Phaser.Display.Align.RIGHT_CENTER
    • 9, or Phaser.Display.Align.RIGHT_BOTTOM
    • 10, or Phaser.Display.Align.BOTTOM_LEFT
    • 11, or Phaser.Display.Align.BOTTOM_CENTER
    • 12, or Phaser.Display.Align.BOTTOM_RIGHT
  • x, y : Position of first item.
"},{"location":"gridalign/#types-of-hexagon-grid","title":"Types of hexagon grid","text":"

Reference

  • odd-r : staggeraxis = x, staggerindex = odd
  • even-r : staggeraxis = x, staggerindex = even
  • odd-q : staggeraxis = y, staggerindex = odd
  • even-q :staggeraxis = y, staggerindex = even
"},{"location":"gridcutimage/","title":"Grid cut image","text":""},{"location":"gridcutimage/#introduction","title":"Introduction","text":"

Grid cut image texture to frames, then create image game objects from these frames.

  • Author: Rex
  • Methods
"},{"location":"gridcutimage/#live-demos","title":"Live demos","text":"
  • Cut image
  • Cut rendertexture
"},{"location":"gridcutimage/#usage","title":"Usage","text":"

Sample code

"},{"location":"gridcutimage/#install-plugin","title":"Install plugin","text":""},{"location":"gridcutimage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexgridcutimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgridcutimageplugin.min.js', true);\n
  • Create images
    var images = scene.plugins.get('rexgridcutimageplugin').gridCut(gameObjects, columns, rows, config);\n
"},{"location":"gridcutimage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GridCutImagePlugin from 'phaser3-rex-plugins/plugins/gridcutimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGridCutImage',\nplugin: GridCutImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create images
    var images = scene.plugins.get('rexGridCutImage').gridCut(gameObjects, columns, rows, config);\n
"},{"location":"gridcutimage/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import GridCutImage from 'phaser3-rex-plugins/plugins/gridcutimage.js';\n
  • Create images
    var images = GridCutImage(gameObjects, columns, rows, config);\n
"},{"location":"gridcutimage/#grid-cut","title":"Grid cut","text":"
var cellImages = scene.plugins.get('rexGridCutImage').gridCut(gameObjects, columns, rows, {\n// createImageCallback: undefined,\n// ImageClass: Phaser.GameObjects.Image,\n\n// originX: 0.5,\n// originY: 0.5,\n// add: true,\n// align: true,\n// objectPool: undefined\n})\n
  • gameObjects : Target game object which has a texture, ex Image, RenderTexture.
  • columns, rows : Cut texture in columns x rows grids
  • createImageCallback : Custom callback to return an image game object, optional.
    function(scene, texture, frame) {\nreturn gameObject;\n}\n
    • texture : A texture object.
    • frame : Frame name.
  • ImageClass : Create image game object from this class. Default value is built-in Image class. Used when createImageCallback is undefined.
  • originX, originY : Origin of created image game objects
  • add :
    • true : Add these created image game objects to scene. Default value.
    • false : Don't add created image game objects to scene.
  • align :
    • true : Align position of created image game objects to target game object (gameObjects). Default value when add is set to true.
    • false : Don't set position of created image game objects. Default value when add is set to false.
  • objectPool : An array of image game objects, will reuse image game objects from this pool. Optional.
  • cellImages : Return image game objects.
"},{"location":"gridtable/","title":"Grid table","text":""},{"location":"gridtable/#introduction","title":"Introduction","text":"

Viewer of grid table, to manipulate game object of each visible cell.

  • Author: Rex
  • Game object
"},{"location":"gridtable/#live-demos","title":"Live demos","text":"
  • Grid table
  • Grid table & slider
  • Grid table & scroller
  • Grid table & slider & scroller
  • Horizontal scrolling
  • Varying cell height
"},{"location":"gridtable/#usage","title":"Usage","text":"

Sample code

"},{"location":"gridtable/#install-plugin","title":"Install plugin","text":""},{"location":"gridtable/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexgridtableplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgridtableplugin.min.js', true);\n
  • Add table object
    var table = scene.add.rexGridTable(x, y, width, height, config);\n
"},{"location":"gridtable/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GridTablePlugin from 'phaser3-rex-plugins/plugins/gridtable-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGridTablePlugin',\nplugin: GridTablePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add table object
    var table = scene.add.rexGridTable(x, y, width, height, config);\n
"},{"location":"gridtable/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import GridTable from 'phaser3-rex-plugins/plugins/gridtable.js';\n
  • Add table object
    var table = new GridTable(scene, x, y, width, height, config);\nscene.add.existing(table);\n
"},{"location":"gridtable/#create-instance","title":"Create instance","text":"
var table = scene.add.rexGridTable(x, y, width, height, {\nscrollMode: 0,        // 0|'v'|'vertical'|1|'h'|'horizontal'\ncellsCount: 0,\ncolumns: 1,\n// rows: 1,\ncellHeight: 30,\ncellWidth: 30,\n// fixedCellSize: false,\n\ncellVisibleCallback: null,\n// cellVisibleCallback: function (cell, cellContainer, table) {},\ncellVisibleCallbackScope: undefined,\nreuseCellContainer: false,\n\ncellInvisibleCallback: null,\n// cellInvisibleCallback: function(cell) {},\ncellInvisibleCallbackScope: undefined,\nclampTableOXY: true,\n\nmask: {\npadding: 0, // or {left, right, top, bottom}\n// updateMode: 0,\n// layer: undefined,\n},\n// enableLayer: false\n});\n
  • scrollMode :
    • 0, or 'v', or 'vertical' : Scroll table vertically.
    • 1, or 'h', or 'horizontal' : Scroll table horizontally.
  • cellsCount : Total cells count.
  • columns : Columns count of each row. Can be used in vertical or horizontal scroll mode.
  • rows : Rows count of each column. Can be used in horizontal scroll mode.
  • cellHeight : Default height of each cell.
    • Expand cell height to fit table height : set cellHeight to undefined, and scrollMode is 'horizontal'.
  • cellWidth : Width of each cell.
    • Expand cell width to fit table width : set cellWidth to undefined, and scrollMode is 'vertical'.
  • fixedCellSize : Assign columns according to cellWidth (if scrollMode is 0) or cellHeight (if scrollMode is 1) , when initialize and resizing. \u3000\u3000- false : Ignore this parameter. Default behavior.
    • true : Set columns according to cellWidth/cellHeight.
  • cellVisibleCallback , cellVisibleCallbackScope : Callback when cell begins visible.
    function (cell, cellContainer, table) {\nif (cellContainer === null) { // No reusable cell container, create a new one\nvar scene = cell.scene;\n// cellContainer = scene.add.container();\n}\n// Set child properties of cell container ...\ncell.setContainer(cellContainer); // Assign cell container\n}\n
  • reuseCellContainer : Set true to reuse cell container when cell is visible.
  • cellInvisibleCallback, cellInvisibleCallbackScope: Callback when cell begins invisible
    function (cell) {\n// var container = cell.popContainer();\n}\n
  • clampTableOXY : Set true to clamp tableOX, tableOY when out-of-bound,
    • Set false when dragging by scroller
  • mask : A rectangle mask of cells
    • mask.padding :
      • A number : Extra left/right/top/bottom padding spacing of this rectangle mask. Default value is 0.
      • A plain object {left, right, top, bottom}
    • mask.updateMode : When to update cells mask
      • 0, or update : Apply mask to cell container only when table.updateTable() is invoked. Default behavior.
      • 1, or everyTick : Apply mask to cell container every tick. Use this mode if game objects of cell are moved after table.updateTable() and still been masked.
    • mask.layer :
      • undefined, false, null : Disable this feature, default behavior
      • Layer game object : Draw children game object of panel on this layer game object, then apply mask on this layer game object.
    • false : No mask.
  • enableLayer :
    • false : Add cell game objects into scene's display list. Default behavior.
    • true : Add cell game objects into an internal layer game object. See also.

Add grid table from JSON

var table = scene.make.rexGridTable({\nx: 0,\ny: 0,\nwidth: 256,\nheight: 256,\n\n// cellsCount: 0,   // total cells count\n// ...\n// origin: {x: 0.5, y: 0.5},\n});\n
"},{"location":"gridtable/#custom-class","title":"Custom class","text":"
  • Define class
    class MyGridTable extends GridTable {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var table = new MyGridTable(scene, x, y, width, height, config);\n
"},{"location":"gridtable/#cell-begins-visible","title":"Cell begins visible","text":"

Add container of cell when it begins visible in event cellvisible.

table.on('cellvisible', function(cell, cellContainer, table){\nif (cellContainer === null) { // No reusable cell container, create a new one\nvar scene = cell.scene;\n// cellContainer = scene.add.container();\n}\n// Set child properties of cell container ...\ncell.setContainer(cellContainer); // Assign cell container\n})\n

It is equal to cellVisibleCallback in configuration.

{\n// ...\ncellVisibleCallback: function(cell, cellContainer, table) {\ncell.setContainer(cellContainer); // Assign cell container\n},\n// ...\n}\n
  • cell
    • Scene object of grid table.
      var scene = cell.scene;\n
    • Index of cell.
      var index = cell.index;\n
    • Size of cell.
      var cellWidth = cell.width;\nvar cellHeight = cell.height;\n
      • Change size of cell :
        • Change cell height in scoll-vertical mode.
          cell.setHeight(newHeight);\n// cell.height = newHeight;\n
          or
          cell.setDeltaHeight(deltaHeight);\n// cell.deltaHeight = deltaHeight;\n
        • Reset cell height in scoll-vertical mode.
          cell.setDeltaHeight(0);\n// cell.deltaHeight = 0;\n
        • Change cell width in scroll-horizontal mode.
          cell.setWidth(newWidth);\n// cell.width = newWidth;\n
          or
          cell.setDeltaWidth(deltaWidth);\n// cell.deltaWidth = deltaWidth;\n
        • Reset cell height in scroll-horizontal mode.
          cell.setDeltaWidth(0);\n// cell.deltaWidth = 0;\n
    • Assign cell container. Set origin point of this cell container to (0,0).
      cell.setContainer(cellContainer);\n
    • Alignment of cellContainer :
      cell.setCellContainerAlign(align);\n
      • align :
        • undefined : Set position of cellContainer to left-top of cell space. Default behavior.
        • 'center', or Phaser.Display.Align.CENTER : Align game object at center of cell space.
        • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center of cell space.
        • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center of cell space.
        • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game object at top-center of cell space.
        • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at bottom-center of cell space.
  • cellContainer : Cell container picked from object pool for reusing. Set reuseCellContainer to true to enable this feature.
    • null : No cell container available.
    • Game object : Reusable cell container.
  • table : Grid table.

Each cell only has one container gameObject, old container will be destroyed when assigning a new container.

"},{"location":"gridtable/#cell-begins-invisible","title":"Cell begins invisible","text":"

Container of an invisible cell will be destroyed automatically.

To resue container gameObject

  • Set reuseCellContainer to true to put invisible cell container into object pool.
  • Or, pop that container by cell.popContainer() in event cellinvisible.
table.on('cellinvisible', function(cell){\n// var container = cell.popContainer();\n})\n

It is equal to cellInvisibleCallback in configuration.

{\n// ...\ncellInvisibleCallback: function(cell) {\n// var container = cell.popContainer();\n},\n// ...\n}\n
"},{"location":"gridtable/#scroll-table-content","title":"Scroll table content","text":"
  • Set
    table.setTableOY(oy).updateTable();\ntable.addTableOY(dy).updateTable();\n
    table.setTableOX(ox).updateTable();\ntable.addTableOX(dx).updateTable();\n
    table.setTableOXY(ox, oy).updateTable();\ntable.addTableOXY(dx, dy).updateTable();\n
    or
    table.tableOY = oy;  // include table.updateTable()\ntable.tableOX = ox;\n
    • These will trigger cellvisible, or cellinvisible events.
  • Get
    var tableOY = table.tableOY;\nvar tableOX = table.tableOX;\n

Use case

Scroll table by scroller behavior.

"},{"location":"gridtable/#scroll-by-percentage","title":"Scroll by percentage","text":"
  • Set
    table.setTableOYByPercentage(t).updateTable();  // t: 0~1\n
    or
    table.t = t;  // include table.updateTable()\n
  • Get
    var t = table.getTableOYPercentage();\n//var t = table.t;\n

Use case

Scroll table by slider behavior.

"},{"location":"gridtable/#scroll-to-bottom","title":"Scroll to bottom","text":"
table.scrollToBottom();\n
"},{"location":"gridtable/#scroll-to-row","title":"Scroll to row","text":"
  • Scroll to next row
    table.scrollToNextRow();\n
  • Scroll to next n row
    table.scrollToNextRow(n);\n
  • Scroll to row
    table.scrollToRow(rowIndex);\n
  • Get current row index
    var rowIndex = table.startRowIndex;\n
"},{"location":"gridtable/#refresh-table-content","title":"Refresh table content","text":"
  • Refresh all visible cells.
    table.updateTable(true);\n
  • Update a visible cell
    table.updateVisibleCell(cellIndex);\n
"},{"location":"gridtable/#table-size-in-cells","title":"Table size in cells","text":"
  • Set table size
    table.setGridSize(colCount, rowCount).updateTable();\n
"},{"location":"gridtable/#total-cells-count","title":"Total cells count","text":"
  • Get
    var count = table.cellsCount;\n
  • Set
    table.setCellsCount(count).updateTable();\n
"},{"location":"gridtable/#columns-count","title":"Columns count","text":"
  • Get
    var columnCount = table.columnCount;\n
  • Set
    table.setColumnCount(count).updateTable(true);\n
"},{"location":"gridtable/#table-size-in-pixels","title":"Table size in pixels","text":"
  • Table height in pixels
    var tableHeight = table.tableHeight;\n
  • Table width in pixels
    var tableWidth = table.tableWidth;\n
"},{"location":"gridtable/#bounds-of-tableox-tableoy","title":"Bounds of tableOX, tableOY","text":"
  • Top bound of tableOY
    var topTableOY = table.topTableOY;  // 0\n
  • Bottom bound of tableOY
    var bottomTableOY = table.bottomTableOY; // A negative number\n
  • Left bound of tableOX
    var leftTableOX = table.leftTableOX;  // 0\n
  • Right bound of tableOX
    var rightTableOX = table.rightTableOX; // A negative number\n

Use case

Set bounds of scroller

"},{"location":"gridtable/#resize-table","title":"Resize table","text":"
table.resize(width, height);\n
"},{"location":"gridtable/#cell","title":"Cell","text":""},{"location":"gridtable/#get-cell","title":"Get cell","text":"
var cell = table.getCell(cellIndex);\n
"},{"location":"gridtable/#get-cell-from-position","title":"Get cell from position","text":"
var cellIndex = table.pointToCellIndex(x, y);\nvar cell = table.getCell(cellIndex);\n
"},{"location":"gridtable/#cell-height","title":"Cell height","text":"
  • Get
    var height = cell.height;\n
  • Set cell height, only worked in scoll-vertical mode.
    cell.height = height;\n// cell.setHeight(height);\n
    or
    table.setCellHeight(cellIndex, cellHeight);\n
    • Refresh table after the cell size is changed.
      table.updateTable(true);\n
    • Emit 'cellheightchange' event.
      table.on('cellheightchange', function (cell, cellContainer, table) {\n});\n
"},{"location":"gridtable/#cell-width","title":"Cell width","text":"
  • Get
    var width = cell.width;\n
  • Set cell width, only worked in scoll-horizontal mode.
    cell.width = width;\n// cell.setWidth(width);\n
    or
    table.setCellWidth(cellIndex, cellWidth);\n
    • Refresh table after the cell size is changed.
      table.updateTable(true);\n
    • Emit 'cellwidthchange' event.
      table.on('cellwidthchange', function (cell, cellContainer, table) {\n});\n
"},{"location":"gridtable/#reset-size-of-all-cells","title":"Reset size of all cells","text":"
table.resetAllCellsSize(width, height);\n
"},{"location":"gridtable/#fore-each-visible-cell","title":"Fore each visible cell","text":"
  • For when you absolutely know this Set won't be modified during the iteration
    table.iterateVisibleCell(function(cell){\n// ...\n});\n
  • For when you know this Set will be modified during the iteration.
    table.eachVisibleCell(function(cell){\n// ...\n});\n
"},{"location":"gridtable/#container","title":"Container","text":"
  • Get
    var container = cell.getContainer();\n
  • Pop (get and remove)
    var container = cell.popContainer();\n
  • Set
    cell.setContainer(container);\n
  • Remove
    cell.destroyContainer();\n
"},{"location":"gridtable/#properties","title":"Properties","text":"
var cellIndex = cell.index;\n
"},{"location":"gridtable/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"group/","title":"Group","text":""},{"location":"group/#introduction","title":"Introduction","text":"

Objects pool, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"group/#usage","title":"Usage","text":""},{"location":"group/#add-group-object","title":"Add group object","text":"
var group = scene.add.group(config);\n// var group = scene.add.group(gameObjects, config);  // Add game objects into group\n
  • config
    {\nclassType: Phaser.GameObjects.Sprite,\ndefaultKey: null,\ndefaultFrame: null,\nactive: true,\nmaxSize: -1,\nrunChildUpdate: false,\ncreateCallback: null,\nremoveCallback: null,\ncreateMultipleCallback: null\n}\n
    • classType :
      • Sprite : Phaser.GameObjects.Sprite
      • Image : Phaser.GameObjects.Image
    • runChildUpdate : Set true to run gameObject.update() every tick.
    • createCallback : A function to be called when adding or creating group members.
      var callback = function(gameObject) {\n}\n
    • removeCallback : A function to be called when removing group members.
      var callback = function(gameObject) {\n}\n
    • createMultipleCallback : A function to be called when creating several group members at once.
      var callback = function(gameObjects) {\n}\n
"},{"location":"group/#add-game-object","title":"Add game object","text":"
group.add(gameObject);\n// group.add(gameObject, true);  // add this game object to display and update list of scene\n
group.addMultiple(gameObjects);   // array of game objects\n// group.addMultiple(gameObjects, true);\n
  • Game object will only be added once.
  • Game object will be removed automatically when destroyed.
"},{"location":"group/#remove-game-object","title":"Remove game object","text":"
group.remove(gameObject);\n// group.remove(gameObject, true);  // also remove this game object from display and update list of scene\n

Remove all game objects

group.clear();\n// group.clear(removeFromScene, destroyChild);\n
"},{"location":"group/#get-game-objects","title":"Get game objects","text":"
  • Get all game objects.
    var gameObjects = group.getChildren();  // array of game objects\n
  • Get all matching game objects
    var gameObjects = group.getMatching(property, value);\n// var gameObjects = group.getMatching(property, value, startIndex, endIndex);\n
  • Amount of game objects.
    var len = group.getLength();\n
  • Group is full. Maximun size is set in maxSize.
    var isFull = group.isFull();\n
  • Game object is in group.
    var isInGroup = group.contains(child);\n
"},{"location":"group/#group-actions","title":"Group actions","text":""},{"location":"group/#property","title":"Property","text":"
  • Set property
    group.propertyValueSet(key, value);\n// group.propertyValueSet(key, value, step, index, direction);\n
    • direction :
      • 1 : From beginning to end
      • -1 : From end to beginning
  • Increase property
    group.propertyValueInc(key, value);\n// group.propertyValueInc(key, value, step, index, direction);\n
    • direction :
      • 1 : From beginning to end
      • -1 : From end to beginning
"},{"location":"group/#position","title":"Position","text":"
  • Set Position
    group.setX(value);\n// group.setX(value, step);\ngroup.setX(value);\n// group.setY(value, step);\ngroup.setXY(x, y);\n// group.setXY(x, y, stepX, stepY);\n
  • Increase Position
    group.incX(value);\n// group.incX(value, step);\ngroup.incY(value);\n// group.incY(value, step);\ngroup.incXY(x, y);\n// group.incXY(x, y, stepX, stepY);\n
  • Shift position
    group.shiftPosition(x, y);\n// group.shiftPosition(x, y, direction);\n
    • direction :
      • 0 : First to last
      • 1 : Last to first
"},{"location":"group/#angle","title":"Angle","text":"
  • Set angle
    group.angle(value);\n// group.angle(value, step);\n
    group.rotate(value);\n// group.rotate(value, step);\n
  • Rotate around
    group.rotateAround(point, angle);\n
    group.rotateAroundDistance(point, angle, distance);\n
"},{"location":"group/#visible","title":"Visible","text":"
  • Set visible
    group.setVisible(value);\n// group.setVisible(value, index, direction);\n
    • index : An optional offset to start searching from within the items array.
    • direction : The direction to iterate through the array.
      • 1 : From beginning to end
      • -1 : From end to beginning
  • Toggle visible
    group.toggleVisible();\n
"},{"location":"group/#alpha","title":"Alpha","text":"
  • Set alpha
    group.setAlpha(value);\n// group.setAlpha(value, step);\n
"},{"location":"group/#tint","title":"Tint","text":"
  • Set tint
    group.setTint(value);\n// group.setTint(topLeft, topRight, bottomLeft, bottomRight);\n
"},{"location":"group/#blend-mode","title":"Blend mode","text":"
  • Set blend mode
    group.setBlendMode(value);\n
"},{"location":"group/#scale","title":"Scale","text":"
  • Set scale
    group.scaleX(value);\n// group.scaleX(value, step);\ngroup.scaleY(value);\n// group.scaleY(value, step);\ngroup.scaleXY(scaleX, scaleY);\n// group.scaleXY(scaleX, scaleY, stepX, stepY);\n
"},{"location":"group/#origin","title":"Origin","text":"
  • Set origin
    group.setOrigin(originX, originY);\n// group.setOrigin(originX, originY, stepX, stepY);\n
"},{"location":"group/#depth","title":"Depth","text":"
  • Set depth
    group.setDepth(value, step);\n
"},{"location":"group/#animation","title":"Animation","text":"
  • Play animation
    group.playAnimation(key, startFrame);\n
"},{"location":"group/#hit-area","title":"Hit area","text":"
  • Set hit-area
    group.setHitArea();\n// group.setHitArea(hitArea, hitAreaCallback);\n
"},{"location":"group/#shuffle","title":"Shuffle","text":"
  • Shuffle array
    group.shuffle();\n
"},{"location":"group/#activeinactive-game-objects","title":"Active/inactive game objects","text":"
  • Set inactive
    group.kill(gameObject);         // gameObject.setActive(false)\ngroup.killAndHide(gameObject);  // gameObject.setActive(false).setVisible(false)\n
  • Amount of active game objects
    var activeCount = group.countActive();\n
    or
    var activeCount = group.getTotalUsed();\n
  • Amount of active game objects
    var inactiveCount = group.countActive(false);\n
  • Amount of free (maxSize - activeCount) game objects
    var freeCount = group.getTotalFree();  // group.maxSize - group.getTotalUsed()\n
  • Get first active/inactive game object,
    • Return null if no game object picked.
      var gameObject = group.getFirst(active);  // active = true/false\nvar gameObject = group.getFirstAlive(); // Equal to group.getFirst(true, ...)\nvar gameObject = group.getFirstDead(); // Equal to group.getFirst(false, ...)\n
    • Create one if no game object picked.
      var gameObject = group.getFirst(active, true, x, y, key, frame, visible);  // active = true/false\nvar gameObject = group.getFirstAlive(true, x, y, key, frame, visible); // Equal to group.getFirst(true, ...)\nvar gameObject = group.getFirstDead(true, x, y, key, frame, visible); // Equal to group.getFirst(false, ...)\nvar gameObject = group.get(x, y, key, frame, visible); // Equal to group.getFirst(false, true, ...)\n
      • Use (x, y, key, frame) to create Image/Sprite game object.
        var newGameObject = new GameObjectClass(x, y, key, frame);\n
"},{"location":"group/#create-game-objects","title":"Create game objects","text":"
var gameObjects = group.createFromConfig(config);\nvar gameObjects = group.createMultiple(config);    // config in array\n
  • config
    {\nclassType: this.classType,\nkey: undefined,             // Required\nframe: null,\nvisible: true,\nactive: true,\nrepeat: 0,                  // Create (1 + repeat) game objects\ncreateCallback: undefined,  // Override this.createCallback if not undefined\n\n// Position\nsetXY: {\nx:0,\ny:0,\nstepX:0,\nstepY:0\n},\n// Actions.SetXY(gameObjects, x, y, stepX, stepY)\ngridAlign: false,\n// {\n//     width: -1,\n//     height: -1,\n//     cellWidth: 1,\n//     cellHeight: 1,\n//     position: Phaser.Display.Align.TOP_LEFT,\n//     x: 0,\n//     y: 0\n// }\n// Actions.GridAlign(gameObjects, gridAlign)\n\n// Angle\nsetRotation: {\nvalue: 0,\nstep:\n},\n// Actions.SetRotation(gameObjects, value, step)\n\n// Scale\nsetScale: {\nx:0,\ny:0,\nstepX:0,\nstepY:0\n},\n// Actions.SetScale(gameObjects, x, y, stepX, stepY)\n\n// Alpha\nsetAlpha: {\nvalue: 0,\nstep:\n},\n// Actions.SetAlpha(gameObjects, value, step)\n\nsetOrigin: {\nx:0,\ny:0,\nstepX:0, stepY:0\n},\n\n// Input\nhitArea: null,\nhitAreaCallback: null,\n// Actions.SetHitArea(gameObjects, hitArea, hitAreaCallback)\n}\n
    • classType :
      • Sprite: Phaser.GameObjects.Sprite
      • Image: Phaser.GameObjects.Image
"},{"location":"group/#destroy","title":"Destroy","text":"
  • Destroy group only
    group.destroy();\n
  • Destroy group and children
    group.destroy(true);\n
"},{"location":"groupactions/","title":"Group actions","text":""},{"location":"groupactions/#introduction","title":"Introduction","text":"

Set properties of game objects, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"groupactions/#usage","title":"Usage","text":""},{"location":"groupactions/#call-function","title":"Call function","text":"
Phaser.Actions.Call(gameObjects, function(gameObject) {\n\n}, scope);\n
"},{"location":"groupactions/#set-any-property","title":"Set any property","text":"
Phaser.Actions.PropertyValueSet(gameObjects, key, value, step, index, direction);\n
  • gameObjects : An array of game objects.
  • key : The property to be updated.
  • value : The amount to be added to the property.
  • step : This is added to the value amount, multiplied by the iteration counter.
  • index : An optional offset to start searching from within the items array.
  • direction :
    • 1 : from beginning to end.
    • -1: from end to beginning.
Phaser.Actions.PropertyValueInc(gameObjects, key, value, step, index, direction);\n
Phaser.Actions.SmootherStep(gameObjects, key, min, max, inc));\n
Phaser.Actions.SmoothStep(gameObjects, key, min, max, inc));\n
Phaser.Actions.Spread(gameObjects, key, min, max, inc));\n
"},{"location":"groupactions/#position","title":"Position","text":"
Phaser.Actions.SetX(gameObjects, value, step, index, direction);\n
Phaser.Actions.IncX(gameObjects, value, step, index, direction);\n
Phaser.Actions.SetY(gameObjects, value, step, index, direction);\n
Phaser.Actions.IncY(gameObjects, value, step, index, direction);\n
Phaser.Actions.SetXY(gameObjects, x, y, stepX, stepY, index, direction);\n
Phaser.Actions.IncXY(gameObjects, x, y, stepX, stepY, index, direction);\n
"},{"location":"groupactions/#shift-position","title":"Shift position","text":"

Set the position of first game object to (x, y), others to the position of previous game object.

Phaser.Actions.ShiftPosition(gameObjects, x, y, direction, output);\n
"},{"location":"groupactions/#position-on-shape","title":"Position on shape","text":""},{"location":"groupactions/#grid-align","title":"Grid align","text":"
Phaser.Actions.GridAlign(gameObjects, {\nwidth: -1,\nheight: -1,\ncellWidth: 1,\ncellHeight: 1,\nposition: Phaser.Display.Align.TOP_LEFT,\nx: 0,\ny: 0\n});\n
  • width : The width of the grid in items (not pixels). -1 means lay all items out horizontally, regardless of quantity.
  • height : The height of the grid in items (not pixels). -1 means lay all items out vertically, regardless of quantity.
  • cellWidth : The width of the cell, in pixels.
  • cellHeight : The height of the cell, in pixels.
  • position : The alignment position.
    • 0, or Phaser.Display.Align.TOP_LEFT
    • 1, or Phaser.Display.Align.TOP_CENTER
    • 2, or Phaser.Display.Align.TOP_RIGHT
    • 3, or Phaser.Display.Align.LEFT_TOP
    • 4, or Phaser.Display.Align.LEFT_CENTER
    • 5, or Phaser.Display.Align.LEFT_BOTTOM
    • 6, or Phaser.Display.Align.CENTER
    • 7, or Phaser.Display.Align.RIGHT_TOP
    • 8, or Phaser.Display.Align.RIGHT_CENTER
    • 9, or Phaser.Display.Align.RIGHT_BOTTOM
    • 10, or Phaser.Display.Align.BOTTOM_LEFT
    • 11, or Phaser.Display.Align.BOTTOM_CENTER
    • 12, or Phaser.Display.Align.BOTTOM_RIGHT
  • x, y : Position of first item.
"},{"location":"groupactions/#line","title":"Line","text":"

Line :

var line = new Phaser.Geom.Line(x1, y1, x2, y2);\n
Phaser.Actions.PlaceOnLine(gameObjects, line);\n// Phaser.Actions.PlaceOnLine(gameObjects, line, ease);\n
  • ease :
    • A string
    • A function object.
Phaser.Actions.RandomLine(gameObjects, line);\n
"},{"location":"groupactions/#circle","title":"Circle","text":"

Circle :

var circle = new Phaser.Geom.Circle(x, y, radius);\nPhaser.Actions.PlaceOnCircle(gameObjects, circle, startAngle, endAngle);\n
Phaser.Actions.RandomCircle(gameObjects, circle);\n
"},{"location":"groupactions/#ellipse","title":"Ellipse","text":"

Ellipse :

var ellipse = new Phaser.Geom.Ellipse(x, y, width, height);\nPhaser.Actions.PlaceOnEllipse(gameObjects, ellipse, startAngle, endAngle);\n
"},{"location":"groupactions/#triangle","title":"Triangle","text":"

Triangle :

var triangle = new Phaser.Geom.Triangle(x1, y1, x2, y2, x3, y3);\nPhaser.Actions.PlaceOnTriangle(gameObjects, triangle, stepRate);\n
Phaser.Actions.RandomTriangle(gameObjects, triangle);\n
"},{"location":"groupactions/#rectangle","title":"Rectangle","text":"

Rectangle :

var rect = new Phaser.Geom.Rectangle(x, y, width, height);\nPhaser.Actions.PlaceOnRectangle(gameObjects, rect, shift;\n
Phaser.Actions.RandomRectangle(gameObjects, rect);\n
Phaser.Actions.WrapInRectangle(gameObjects, rect, padding);\n
"},{"location":"groupactions/#angle","title":"Angle","text":"
Phaser.Actions.Angle(gameObjects, value, step, index, direction);\n// value: angle in radians\n
Phaser.Actions.Rotate(gameObjects, value, step, index, direction);\n// value: angle in degree\n
Phaser.Actions.RotateAround(gameObjects, point, angle);\n// point: {x, y}, angle: angle in radians\n
Phaser.Actions.RotateAroundDistance(gameObjects, point, angle, distance);\n// point: {x, y}, angle: angle in radians\n
"},{"location":"groupactions/#visible","title":"Visible","text":"
Phaser.Actions.SetVisible(gameObjects, value, index, direction);\n
Phaser.Actions.ToggleVisible(gameObjects);\n
"},{"location":"groupactions/#alpha","title":"Alpha","text":"
Phaser.Actions.SetAlpha(gameObjects, value, step, index, direction);\n
"},{"location":"groupactions/#tint","title":"Tint","text":"
Phaser.Actions.setTint(gameObjects, value);\n//Phaser.Actions.setTint(gameObjects, topLeft, topRight, bottomLeft, bottomRight);\n
"},{"location":"groupactions/#origin","title":"Origin","text":"
Phaser.Actions.SetOrigin(gameObjects, originX, originY, stepX, stepY, index, direction);\n
"},{"location":"groupactions/#scale","title":"Scale","text":"
Phaser.Actions.ScaleX(gameObjects, value, step, index, direction);\n
Phaser.Actions.ScaleY(gameObjects, value, step, index, direction);\n
Phaser.Actions.ScaleXY(gameObjects, x, y, stepX, stepY, index, direction);\n
"},{"location":"groupactions/#scroll-factor","title":"Scroll factor","text":"
Phaser.Actions.SetScrollFactorX(gameObjects, value, step, index, direction);\n
Phaser.Actions.SetScrollFactorY(gameObjects, value, step, index, direction);\n
Phaser.Actions.SetScrollFactor(gameObjects, x, y, stepX, stepY, index, direction);\n
"},{"location":"groupactions/#depth","title":"Depth","text":"
Phaser.Actions.SetDepth(gameObjects, value, step, index, direction);\n
"},{"location":"groupactions/#hit-area","title":"Hit area","text":"
Phaser.Actions.SetHitArea(gameObjects, hitArea, hitAreaCallback);\n
"},{"location":"groupactions/#blend-mode","title":"Blend mode","text":"
Phaser.Actions.SetBlendMode(gameObjects, blendMode, index, direction);\n
  • blendMode : Blend mode
"},{"location":"groupactions/#play-animation","title":"Play animation","text":"
Phaser.Actions.PlayAnimation(gameObjects, key, ignoreIfPlaying);\n
"},{"location":"groupactions/#shuffle","title":"Shuffle","text":"
Phaser.Actions.Shuffle(gameObjects);\n
"},{"location":"groupnavigator/","title":"Group navigator","text":""},{"location":"groupnavigator/#introduction","title":"Introduction","text":"

Navigate between existing game objects, focus on next/previous/next-row/previous row game object.

  • Author: Rex
  • Member of scene
"},{"location":"groupnavigator/#live-demos","title":"Live demos","text":"
  • 1D targets
  • 2D targets
"},{"location":"groupnavigator/#usage","title":"Usage","text":"

Sample code

"},{"location":"groupnavigator/#install-plugin","title":"Install plugin","text":""},{"location":"groupnavigator/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexgroupnavigatorplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgroupnavigatorplugin.min.js', true);\n
  • Create navigator
    var navigator = scene.plugins.get('rexgroupnavigatorplugin').add(config);\n
"},{"location":"groupnavigator/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GroupNavigatorPlugin from 'phaser3-rex-plugins/plugins/groupnavigator-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGroupNavigator',\nplugin: GroupNavigatorPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create navigator
    var navigator = scene.plugins.get('rexGroupNavigator').add(config);\n
"},{"location":"groupnavigator/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import GroupNavigator from 'phaser3-rex-plugins/plugins/groupnavigator.js';\n
  • Create navigator
    var navigator = new GroupNavigator(config);\n
"},{"location":"groupnavigator/#create-navigator","title":"Create navigator","text":"
var navigator = scene.plugins.get('rexGroupNavigator').add({\n// enable: true,\n\ntargets: gameObjects,\n// columns: undefined,\n\n// getFocusEnableCallback(gameObject) { \n//     return focusEnable;\n// }\n// focusEnableDataKey: undefined,\n// focusEnableKey: undefined\n});\n
  • enable :
    • true : Can navigate between game objects. Default behavior.
    • false : Ignore navigation actions (navigator.next(), navigator.previous(), navigator.nextRow(), navigator.previousRow())
  • targe1ts :
    • 1D array of game objects for navigator.next(), or navigator.previous()
    • 2D array of game objects for navigator.next(), navigator.previous(), navigator.nextRow(), navigator.previousRow()
  • columns : A number : Convert 1D targets array to 2D array, each row has columns game objects.
    • undefined : Ignore this parameter. Default behavior.
  • Focus enable : Get focus enable of game object by one of these parameter.
    • getFocusEnableCallback : A callback to return focus enable of this game object.
      function(gameObject) {\nreturn focusEnable;\n}\n
    • focusEnableDataKey : Get focus enable from private data of this game object.
    • focusEnableKey : Get focus enable from property of this game object.
    • Focus enable is always true if none of these parameter is given. Default behavior.
"},{"location":"groupnavigator/#enable","title":"Enable","text":"
  • Get
    var enable = navigator.enable;\n
  • Set
    navigator.setEnable(enable);\n
"},{"location":"groupnavigator/#navigate","title":"Navigate","text":"
  • Focus on next/previous game object, for 1D and 2D array of targets
    navigator.next();\n
    navigator.previous();\n
    Will fire blur and focus events
  • Focus on next row/previous row game object, for 2D array of targets
    navigator.nextRow();\n
    navigator.previousRow();\n
    Will fire blur and focus events
  • Focus on first/last game object
    navigator.first();\n
    navigator.last();\n
    Will fire blur and focus events
"},{"location":"groupnavigator/#current-focused-game-object","title":"Current focused game object","text":"
  • Get current focused game object
    var gameObject = navigator.getFocusedTarget();\n// var gameObject = navigator.focusedTarget;\n
  • Focus on game object. Do nothing if that game object is not focus-enable.
    navigator.focus(gameObject);\n
    Will fire blur and focus events.
  • Blur
    navigator.blur();\n
    Will fire blur event.
"},{"location":"groupnavigator/#target-game-objects","title":"Target game objects","text":"
  • Get
    var gameObjects = navigator.targets;\n
    • gameObjects : 1D/2D array of game objects
  • Set
    navigator.setTargets(targets);\n// navigator.setTargets(targets, columns);\n
  • Modify
    navigator.targets.push(newGameObject);    
    Phaser.Utils.Array.AddAt(navigator.targets, newGameObject, index);\n
    Phaser.Utils.Array.Remove(navigator.targets, gameObject);\n
"},{"location":"groupnavigator/#events","title":"Events","text":"
  • On focus
    navigator.on('focus', function(gameObject){\n\n})\n
  • On blur
    navigator.on('blur', function(gameObject){\n\n})\n
"},{"location":"handlebars/","title":"Handlebars","text":""},{"location":"handlebars/#introduction","title":"Introduction","text":"

Format string with variables, largely compatible with Mustache templates. Reference

"},{"location":"handlebars/#usage","title":"Usage","text":"
var template = 'hello, {{name}}';\nvar view = {\nname: 'rex'\n};\nvar result = Mustache.render(template, view);\n
"},{"location":"handlebars/#pre-compile","title":"Pre-compile","text":"
const template = Handlebars.compile(\"{{foo}}\");\ntemplate({}, {\n// allowProtoPropertiesByDefault: false,\n// allowProtoMethodsByDefault: false\n});\n
"},{"location":"hiddeninputtext/","title":"Hidden edit","text":""},{"location":"hiddeninputtext/#introduction","title":"Introduction","text":"

An invisible Input DOM element to receive character input and display on text, bbocodetext, or tagtext.

Inspirited from CanvasInput.

  • Author: Rex
  • Behavior of text object
"},{"location":"hiddeninputtext/#live-demos","title":"Live demos","text":"
  • With Text
  • With BBCodeText
  • With rexui-Label
  • With bitmaptext
  • Number input
"},{"location":"hiddeninputtext/#usage","title":"Usage","text":"

Sample code

"},{"location":"hiddeninputtext/#install-plugin","title":"Install plugin","text":""},{"location":"hiddeninputtext/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexhiddeninputtextplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexhiddeninputtextplugin.min.js', true);\n
  • Add text-edit behavior
    var hiddenInputText = scene.plugins.get('rexhiddeninputtextplugin').add(textGameObject, config);\n
"},{"location":"hiddeninputtext/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import HiddenInputTextPlugin from 'phaser3-rex-plugins/plugins/hiddeninputtext-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexHiddenInputTextPlugin',\nplugin: HiddenInputTextPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text-edit behavior
    var hiddenInputText = scene.plugins.get('rexHiddenInputTextPlugin').add(textGameObject, config);\n
"},{"location":"hiddeninputtext/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import HiddenInputText from 'phaser3-rex-plugins/plugins/hiddeninputtext.js';\n
  • Add text-edit behavior
    var hiddenInputText = new HiddenInputText(textGameObject, config);\n
"},{"location":"hiddeninputtext/#add-input-text-object","title":"Add input text object","text":"
var hiddenInputText = scene.plugins.get('rexHiddenInputTextPlugin').add(textGameObject, {\n// inputType: 'text',    // 'text'|'password'|'textarea'|...\n// type: 'text',    // 'text'|'password'|'textarea'|...\n\ncursor: '|',\ncursorFlashDuration: 1000,\n\n// enterClose: true,\n\n// onOpen: function (textObject, hiddenInputText) {   // Or onFocus:\n// },\n// onClose: function (textObject, hiddenInputText) {  // Or onBlur:\n// },\n// onUpdate: function (text, textObject, hiddenInputText) {\n//     return text;\n// },\n});\n
  • textGameObject :
  • inputType, or type : Type of element
    • 'text', 'password', 'textarea', ...
  • cursor : Cursor character used in default update text callback.
    • null, or '' : Don't insert cursor character.
  • cursorFlashDuration : Display cursor character or a space string to create a flash cursor.
  • enterClose :
    • true : Close input text when enter-key was pressed. Default value is true if inputType is not 'textarea'.
    • false : If inputType is set to 'textarea', default value will be false.
  • onOpen, or onFocuse : Callback invoked when focus on this hidden input text.
    function (textObject, hiddenInputText) {\n}\n
  • onClose, or onBlur : Callback invoked when blur.
    function (textObject, hiddenInputText) {\n}\n
  • onUpdate :
    • A callback invoked in each tick of editing.
      function (text, textObject, hiddenInputText) {\n// return text;\n}\n
      • Can return a new string for text game object displaying.
    • 'number' : Only output number string.

Note

This hiddenInputText will be destroyed when textGameObject is destroyed.

"},{"location":"hiddeninputtext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyHiddenText extends HiddenInputText {\nconstructor(textGameObject, config) {\nsuper(textGameObject, config) {\n// ...            \n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var hiddenInputText = new MyHiddenText(textGameObject, config);\n
"},{"location":"hiddeninputtext/#cursor","title":"Cursor","text":"
  • Set
    hiddenInputText.setCursor(s);\n
  • Get
    var cursor = hiddenInputText.cursor;\n
"},{"location":"hiddeninputtext/#open-editor","title":"Open editor","text":"
hiddenInputText.open();\n
"},{"location":"hiddeninputtext/#close-editor","title":"Close editor","text":"
hiddenInputText.close();\n
"},{"location":"hiddeninputtext/#is-opened","title":"Is opened","text":"
var isOpened = hiddenInputText.isOpened;\n
"},{"location":"hiddeninputtext/#select-text","title":"Select text","text":"

This feature does not support.

"},{"location":"hiddeninputtext/#bypass-key-input","title":"Bypass key input","text":"

Registered keyboard events might capture key input.

var keyObj = scene.input.keyboard.addKey('W', enableCapture, emitOnRepeat);\n

Set enableCapture to false to bypass key input to this input-text game objecct.

"},{"location":"hiddeninputtext/#event","title":"Event","text":"
  • On text change
    hiddenInputText.on('textchange', function(text, textGameObject){\n})\n
  • Not a number input
    hiddenInputText.on('nan', function(text){\n\n})\n
  • Close editor by ENTER key down
    hiddenInputText.on('keydown-ENTER', function(){\n})\n
"},{"location":"i18next/","title":"i18next","text":""},{"location":"i18next/#introduction","title":"Introduction","text":"

i18next is a very popular internationalization framework for browser or any other javascript environment.

  • Author: i18next
  • Application plugin : Text translation
"},{"location":"i18next/#usage","title":"Usage","text":""},{"location":"i18next/#import-class","title":"Import class","text":"
  • Install i18next, i18next-http-backend from npm
    npm i i18next\nnpm i i18next-http-backend\n
  • Import i18next
    import i18next from 'i18next';\nimport Backend from 'i18next-http-backend';\n
  • Initialize
    i18next.use(Backend).init(config);\n
  • Translation
    var result = i18next.t(key);\n
"},{"location":"i18next/#initialize","title":"Initialize","text":"
i18next\n.use(Backend)\n.init({\nlng: 'dev',\nfallbackLng: 'dev',\nns: 'translation',\n\n// resources: {\n//     'dev': {\n//         'translation': {\n//             key: value,  \n//         }\n//     }\n// }\n\n// debug: true,\n})\n
  • lng : Language to use. Will fallback to 'dev'.
  • ns : String or array of namespaces to load. Default value is 'translation'.
  • debug : Logs info level to console output. Helps finding issues with loading not working. Default value is false.
  • resources : Resources to initialize with.
  • backend.loadPath : Path where resources get loaded from, or a function returning a path.
    function(lngs, namespaces) { return customPath; }\n
  • backend.parse : Parse data after it has been fetched. Optional.
    function(data) { return JSON.parse(data); }\n

See also Configuration Options, and Backend Options

"},{"location":"i18next/#change-language","title":"Change language","text":"
i18next.changeLanguage(\"en\");\n

Fire event 'languageChanged'.

"},{"location":"i18next/#set-default-namespace","title":"Set default namespace","text":"
i18next.setDefaultNamespace(namespace);\n
"},{"location":"i18next/#translate","title":"Translate","text":"
var result = i18next.t(key);\n// var result = i18next.t(key, interpolation);\n
"},{"location":"i18next/#events","title":"Events","text":"
  • On language changed, triggered by i18next.changeLanguage(lng).
    i18next.on('languageChanged', function (lng) {\n});\n
"},{"location":"image/","title":"Image","text":""},{"location":"image/#introduction","title":"Introduction","text":"

Display of static images, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"image/#usage","title":"Usage","text":""},{"location":"image/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"image/#add-image-object","title":"Add image object","text":"
var image = scene.add.image(x, y, key);\n// var image = scene.add.image(x, y, key, frame);\n

Add image from JSON

var image = scene.make.image({\nx: 0,\ny: 0,\nkey: '',\n// frame: '',\n\n// angle: 0,\n// alpha: 1,\n// flipX: true,\n// flipY: true,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
  • key, frame :
    • A string
    • An array of string to pick one element at random
  • x, y, scale.x, scale.y :
    • A number
    • A callback to get return value
      function() { return 0; }\n
    • Random integer between min and max
      { randInt: [min, max] }\n
    • Random float between min and max
      { randFloat: [min, max] }\n
"},{"location":"image/#custom-class","title":"Custom class","text":"
  • Define class
    class MyImage extends Phaser.GameObjects.Image {\nconstructor(scene, x, y, texture, frame) {\nsuper(scene, x, y, texture, frame);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyImage(scene, x, y, key);\n
"},{"location":"image/#texture","title":"Texture","text":"

See game object - texture

"},{"location":"image/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"image/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"image/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"imagebox/","title":"Image box","text":""},{"location":"imagebox/#introduction","title":"Introduction","text":"

Keep aspect ratio of image game object when scale-down resizing. A containerLite game object with 1 image game object.

  • Author: Rex
  • Game object
"},{"location":"imagebox/#live-demos","title":"Live demos","text":"
  • Resize
"},{"location":"imagebox/#usage","title":"Usage","text":"

Sample code

"},{"location":"imagebox/#install-plugin","title":"Install plugin","text":""},{"location":"imagebox/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('reximageboxplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/reximageboxplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexImageBox(x, y, texture, frame, config);\n
"},{"location":"imagebox/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ImageBoxPlugin from 'phaser3-rex-plugins/plugins/imagebox-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexImageBoxPlugin',\nplugin: ImageBoxPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexImageBox(x, y, texture, frame, config);\n
"},{"location":"imagebox/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ImageBox from 'phaser3-rex-plugins/plugins/imagebox.js';\n
  • Add image object
    var image = new ImageBox(scene, x, y, texture, frame, config);\nscene.add.existing(image);\n
"},{"location":"imagebox/#create-instance","title":"Create instance","text":"
var image = scene.add.rexImageBox(x, y, texture, frame, {\n// scaleUp: false,\n// width: undefined,\n// height: undefined,\n\n// background: undefined,\n// image: undefined\n});\n
  • scaleUp : Scale up or keep original size of image when size of imageBox is larger.
    • true : Scale up image when size of imageBox is larger.
    • false : Keep original size of image size of imageBox is larger. Default behavior.
  • width, height : Resize this game object.
    • undefined : Use original size. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of imageBox.
  • image : Custom image game object instance.
    • undefined : Use built-in image game object. Default behavior.

Add imagebox from JSON

var image = scene.make.rexImageBox({\nx: 0,\ny: 0,\nkey: null,\nframe: null,\n\n// width: undefined,\n// height: undefined,\n\n// background: undefined,\n// image: undefined\n\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
"},{"location":"imagebox/#custom-class","title":"Custom class","text":"
  • Define class
    class MyImageBox extends ImageBox {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyImageBox(scene, x, y, texture, frame, config);\n
"},{"location":"imagebox/#resize","title":"Resize","text":"
image.resize(width, height);\n

Note

  • If new size is bigger than original size, uses original size. (i.e won't scale up)
  • If new size is smaller than original size, scales down and keeps aspect ratio.
"},{"location":"imagebox/#set-texture","title":"Set texture","text":"
image.setTexture(key, frame);\n
"},{"location":"imagebox/#current-texture","title":"Current texture","text":"
var textureKey = image.texture.key;\nvar frameName = image.frame.name;\n
"},{"location":"imagebox/#clear-texture","title":"Clear texture","text":"
image.setTexture();\n

Will set internal image game object to invisible.

"},{"location":"imagebox/#scale-image","title":"Scale image","text":"
image.scaleImage();\n

image.resize(width, height), or image.setTexture(key, frame) will invoke this method internally.

"},{"location":"imagebox/#internal-image-game-object","title":"Internal image game object","text":"
var internalImageGO = image.image;\n
"},{"location":"imagebox/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"imagebox/#create-mask","title":"Create mask","text":"

Create mask from internal image game object (image.image).

var mask = image.image.createBitmapMask();\n

See mask

"},{"location":"imagebox/#shader-effects","title":"Shader effects","text":"

Internal image game object (image.image) support preFX and postFX effects

"},{"location":"imageuriloader/","title":"Imageuriloader","text":"

Note

Phaser3.80 can load image by uri (base64 string) in preload stage.

"},{"location":"imageuriloader/#introduction","title":"Introduction","text":"

Load image by uri (base64 string) in preload stage.

Built-in image loader dosen't support loading local image uri.

  • Author: Rex
  • Custom File of loader
"},{"location":"imageuriloader/#usage","title":"Usage","text":"

Sample code

"},{"location":"imageuriloader/#install-plugin","title":"Install plugin","text":""},{"location":"imageuriloader/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    var sceneConfig = {\n// ....\npack: {\nfiles: [{\ntype: 'plugin',\nkey: 'reximageuriloaderplugin',\nurl: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/reximageuriloaderplugin.min.js',\nstart: true\n}]\n}\n};\nclass MyScene extends Phaser.Scene {\nconstructor() {\nsuper(sceneConfig)\n}\n// ....\n\npreload() {\n// reximageuriloaderplugin will be installed before preload(), but not added to loader yet\n// Call addToScene(scene) to add this await loader to loader of this scene\nthis.plugins.get('reximageuriloaderplugin').addToScene(this);\n\nthis.load.rexImageURI(key, uri);\n}\n}\n
"},{"location":"imageuriloader/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ImageURILoaderPlugin from 'phaser3-rex-plugins/plugins/imageuriloader-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexImageURILoader',\nplugin: ImageURILoaderPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • In preload stage
    scene.load.rexImageURI(key, uri);\n
"},{"location":"imageuriloader/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ImageURILoader from 'phaser3-rex-plugins/plugins/imageuriloader.js';\n
  • Start loading task
    ImageURILoader.call(scene.load, key, uri);\n
"},{"location":"imageuriloader/#load-image","title":"Load image","text":"

In preload stage:

this.load.rexImageURI(key, uri);\n
  • key : Texture key.
  • uri : URI, a base64 string.
"},{"location":"imageuriloader/#load-sprite-sheet","title":"Load sprite sheet","text":"

In preload stage:

this.load.rexImageURI(key, uri, frameConfig);\n
  • key : Texture key.
  • uri : URI, a base64 string.
  • frameConfig :
    • frameWidth : The width of the frame in pixels.
    • frameHeight : The height of the frame in pixels. Uses the frameWidth value if not provided.
    • startFrame : The first frame to start parsing from.
    • endFrame : The frame to stop parsing at. If not provided it will calculate the value based on the image and frame dimensions.
    • margin : The margin in the image. This is the space around the edge of the frames.
    • spacing : The spacing between each frame in the image.
"},{"location":"input-to-camera/","title":"Control by input","text":""},{"location":"input-to-camera/#introduction","title":"Introduction","text":"

Control camera's scroll by pan/cursor-at-bounds(scroll), and zoom by pinch/mouse-wheel.

  • Author: Rex
  • Member of scene
"},{"location":"input-to-camera/#live-demos","title":"Live demos","text":"
  • Camera controller
"},{"location":"input-to-camera/#usage","title":"Usage","text":"

Sample code

"},{"location":"input-to-camera/#install-plugin","title":"Install plugin","text":""},{"location":"input-to-camera/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcameracontrollerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcameracontrollerplugin.min.js', true);\n
  • Add camera-controller object
    var cameraController = scene.plugins.get('rexcameracontrollerplugin').add(scene, config);\n
"},{"location":"input-to-camera/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CameraControllerPlugin from 'phaser3-rex-plugins/plugins/cameracontroller-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCameraController',\nplugin: CameraControllerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add camera-controller object
    var cameraController = scene.plugins.get('rexCameraController').add(scene, config);\n
"},{"location":"input-to-camera/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CameraController from 'phaser3-rex-plugins/plugins/cameracontroller.js';\n
  • Add camera-controller object
    var cameraController = new CameraController(scene, config);\n
"},{"location":"input-to-camera/#create-instance","title":"Create instance","text":"
var cameraController = scene.plugins.get('rexCameraController').add(scene, {\n// camera: scene.cameras.main,\n// minZoom: undefined,\n// maxZoom: undefined,\n\n// panScroll: true,\n// panScrollEnable: true,\n\n// pinchZoom: true,\n// pinchZoomEnable: true,\n// pinchZoomMin: undefined,\n// pinchZoomMax: undefined,\n\n// inputTarget: undefined,\n\n// boundsScroll: true,\n// boundsScrollEnable: true,\n\n// mouseWheelZoom: truem\n// mouseWheelZoomEnable: true,\n// mouseWheelZoomStep: 0.01,\n// mouseWheelZoomMin: undefined,\n// mouseWheelZoomMax: undefined,\n\n// enable: true\n});\n
  • scene : Target scene.
  • camera :
    • undefined : Default camera of this scene.
    • A camera object : Control this camera object.
  • minZoom, maxZoom : Minumun/maximum camera zoom value for pinchZoom and mouseWheelZoom behaviors.
    • undefined : No max/min constraint. Default behavior.
  • Pan scroll:
    • panScroll : Set to false will discard pan-scroll controller. Default is true.
    • panScrollEnable : Set to true to enable pan-scroll behavior. Default value is true.
    • inputTarget :
      • undefined : Receive pan/pinch input by scene's input event. Default behavior.
      • A game object : Receive pan/pinch input only on this game object.
  • Pinch zoom:
    • pinchZoom : Set to false will discard pinch-zoom controller. Default is true.
    • pinchZoomEnable : Set to true to enable pinch-zoom behavior. Default value is true.
    • pinchZoomMin, pinchZoomMax : Minumun/maximum camera zoom value. Default value is minZoom, maxZoom.
    • inputTarget :
      • undefined : Receive pan/pinch input by scene's input event. Default behavior.
      • A game object : Receive pan/pinch input only on this game object.
  • cursor-at-bounds scroll :
    • boundsScroll : Set to false will discard cursor-at-bounds-scroller controller. Default is true.
    • boundsScrollEnable : Set to true to enable bounds-scroll behavior. Default value is true.
  • mouse-wheel zoom :
    • mouseWheelZoom : Set to false will discard mouse-wheel-zoom controller. Default is true.
    • mouseWheelZoomEnable : Set to true to enable mouse-wheel-zoom behavior. Default value is true.
    • mouseWheelZoomStep : Camera zoom incremental. Default value is 0.1.
    • mouseWheelZoomMin, mouseWheelZoomMax : Minumun/maximum camera zoom value. Default value is minZoom, maxZoom.
  • enable :
    • false : Disable all camera-controller temporary.
    • true : Restore all camera-controller's enable state to previous value. Default behavior.
"},{"location":"input-to-camera/#set-target-camera","title":"Set target camera","text":"
cameraController.setCamera(camera);\n
"},{"location":"input-to-camera/#enable-controller-behavior","title":"Enable controller behavior","text":"
  • Pan-scroll
    cameraController.setPanScrollEnable(enable);\n// cameraController.panScrollEnable = enable;\n
  • Pinch-zoom
    cameraController.setPinchZoomEnable(enable);\n// cameraController.pinchZoomEnable = enable;\n
  • Bounds-scroll
    cameraController.setBoundsScrollEnable(enable);\n// cameraController.boundsScrollEnable = enable;\n
  • Wheel-zoom
    cameraController.setMouseWheelZoomEnable(enable);\n// cameraController.mouseWheelZoomEnable = enable;\n
  • Disable all behaviors
    cameraController.setEnable(false);\n// cameraController.enable = false;\n
  • Restore enable state of all behaviors
    cameraController.setEnable();\n// cameraController.enable = true;\n
  • Toggle enable state
    cameraController.toggleEnable();\n// cameraController.enable = !cameraController.enable;\n
"},{"location":"input/","title":"Input","text":""},{"location":"input/#introduction","title":"Introduction","text":"

Input system of each scene, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"input/#usage","title":"Usage","text":""},{"location":"input/#enabledisable","title":"Enable/disable","text":"
scene.input.enabled = enabled; // enabled: true/false\n
"},{"location":"inputtext/","title":"Input text","text":""},{"location":"inputtext/#introduction","title":"Introduction","text":"

Input DOM element.

  • Author: Rex
  • DOM Game object
"},{"location":"inputtext/#live-demos","title":"Live demos","text":"
  • Input text
  • Number input
  • In fullscreen
"},{"location":"inputtext/#usage","title":"Usage","text":"

Sample code

"},{"location":"inputtext/#install-plugin","title":"Install plugin","text":""},{"location":"inputtext/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexinputtextplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexinputtextplugin.min.js', true);\n
  • Add input-text object
    var inputText = scene.add.rexInputText(x, y, width, height, config);\n
"},{"location":"inputtext/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import InputTextPlugin from 'phaser3-rex-plugins/plugins/inputtext-plugin.js';\nvar config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexInputTextPlugin',\nplugin: InputTextPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add input-text object
    var inputText = scene.add.rexInputText(x, y, width, height, config);\n
"},{"location":"inputtext/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import InputText from 'phaser3-rex-plugins/plugins/inputtext.js';\n
  • Add input-text object
    var inputText = new InputText(scene, x, y, width, height, config);\nscene.add.existing(inputText);\n
"},{"location":"inputtext/#add-input-text-object","title":"Add input text object","text":"
var inputText = scene.add.rexInputText(x, y, width, height, config);\n// var inputText = scene.add.rexInputText(x, y, config);\n// var inputText = scene.add.rexInputText(config);\n

Default configuration

{\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\n\ntype: 'text',    // 'text'|'password'|'textarea'|'number'|'color'|...\n\n// Element properties\nid: undefined,\ntext: undefined,\nmaxLength: undefined,\nminLength: undefined,    placeholder: undefined,\ntooltip: undefined,\nreadOnly: false,\nspellCheck: false,\nautoComplete: 'off',\n\n// Style properties\nalign: undefined,\npaddingLeft: undefined,\npaddingRight: undefined,\npaddingTop: undefined,\npaddingBottom: undefined,\nfontFamily: undefined,\nfontSize: undefined,\ncolor: '#ffffff',\nborder: 0,\nbackgroundColor: 'transparent',\nborderColor: 'transparent',\nborderRadius: undefined,\noutline: 'none',\ndirection: 'ltr',\n\nselectAll: false\n}\n
  • x, y : Position
  • width, height : Size of element
  • type : Type of element
    • 'text', 'password', 'textarea', 'number', 'color', ...
  • Element properties
    • id : id element property.
    • text : value element property.
    • maxLength : maxLength element property.
    • minLength : minLength element property.
    • placeholder : placeholder element property.
    • tooltip : title element property.
    • readOnly : readonly element property.
    • spellCheck : spellcheck element property.
    • autoComplete : autocomplete element property.
  • Element style properties
    • align : text-align style property.
    • paddingLeft, paddingRight, paddingTop, paddingBottom : padding-left, padding-right, padding-top, padding-bottom style property.
    • fontFamily : font-family style property.
    • fontSize : font-size style property.
    • color : color style property.
    • backgroundColor : backgroundColor style property.
    • border, borderColor, borderRadius : border, borderColor, border-radius style property.
    • outline : outline style property.
    • direction : direction style property.
  • selectAll : Set true to select all text.
"},{"location":"inputtext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyText extends InputText {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config) {\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var inputText = new MyText(scene, x, y, width, height, config);\n
"},{"location":"inputtext/#text","title":"Text","text":"
  • Get
    var text = inputText.text;\n
  • Set
    inputText.setText(text);\n// inputText.text = text;\n
  • Scroll to bottom
    inputText.scrollToBottom();\n
"},{"location":"inputtext/#style","title":"Style","text":"
  • Get
    var value = inputText.getStyle(key);\n
  • Set
    inputText.setStyle(key, value)\n
"},{"location":"inputtext/#focus","title":"Focus","text":"
  • Focus
    inputText.setFocus();\n
  • Blur
    inputText.setBlur();\n
  • Is focused
    var isFocused = inputText.isFocused;\n
"},{"location":"inputtext/#font-color","title":"Font color","text":"
  • Get
    var color = inputText.fontColor;\n// var color = inputText.node.style.color;\n
  • Set
    inputText.fontColor = color;  // CSS color string\n// inputText.node.style.color = color;\n
    or
    inputText.setFontColor(color);  // CSS color string\n
"},{"location":"inputtext/#max-length","title":"Max length","text":"
  • Get
    var value = inputText.maxLength;\n
  • Set
    inputText.maxLength = value;\n
    or
    inputText.setMaxLength(value);\n
"},{"location":"inputtext/#min-length","title":"Min length","text":"
  • Get
    var value = inputText.minLength;\n
  • Set
    inputText.minLength = value;\n
    or
    inputText.setMinLength(value);\n
"},{"location":"inputtext/#placeholder","title":"Placeholder","text":"
  • Get
    var value = inputText.placeholder;\n
  • Set
    inputText.placeholder = value;\n
    or
    inputText.setPlaceholder(value);\n
"},{"location":"inputtext/#tooltip","title":"Tooltip","text":"
  • Get
    var value = inputText.tooltip;\n
  • Set
    inputText.tooltip = value;\n
    or
    inputText.setTooltip(value);\n
"},{"location":"inputtext/#readonly","title":"Readonly","text":"
  • Get
    var readOnly = inputText.readOnly;\n
  • Set
    inputText.readOnly = value;\n
    inputText.setReadOnly();\n// inputText.setReadOnly(value);\n
"},{"location":"inputtext/#resize","title":"Resize","text":"
inputText.resize(width, height);\n
"},{"location":"inputtext/#select-text","title":"Select text","text":"
  • Select all text
    inputText.selectText();\n// inputText.selectAll();\n
  • Select sub-string
    inputText.selectText(selectionStart, selectionEnd);\n
"},{"location":"inputtext/#cursor-position","title":"Cursor position","text":"
  • Get
    var cursorPosition = inputText.cursorPosition;\n
    • Equal to inputText.selectionStart.
  • Set
    inputText.setCursorPosition(cursorPosition);\ninputText.cursorPosition = cursorPosition;\n
    • Equal to inputText.setSelectionRange(cursorPosition, cursorPosition)
"},{"location":"inputtext/#events","title":"Events","text":"
  • On text changed
    inputText.on('textchange', function(inputText, e){ }, scope);\n
  • On focus
    inputText.on('focus', function(inputText, e){ }, scope);\n
  • On blur
    inputText.on('blur', function(inputText, e){ }, scope);\n
  • On click, double click
    inputText.on('click', function(inputText, e){ }, scope);\n
    inputText.on('dblclick', function(inputText, e){ }, scope);\n
    • Touch/mouse events on input text object won't be propagated to game canvas.
  • On keydown, keyup
    inputText.on('keydown', function(inputText, e){ }, scope);\n
    inputText.on('keyup', function(inputText, e){ }, scope);\n
    • Keyboard events on input text object won't be propagated to game canvas.
  • On pointerdown, pointermove, pointerup
    inputText.on('pointerdown', function(inputText, e){ }, scope);\n
    inputText.on('pointermove', function(inputText, e){ }, scope);\n
    inputText.on('pointerup', function(inputText, e){ }, scope);\n
    • Mouse/touch events on input text object won't be propagated to game canvas.
  • On select
    inputText.on('select', function(inputText, e){ var selectedString = inputText.selectedText;\nvar selectionStart = inputText.selectionStart;\nvar selectionEnd = inputText.selectionEnd;\n}, scope);\n
  • On composition inpit
    inputText.on('compositionStart', function(inputText, e){ }, scope);\n
    inputText.on('compositionEnd', function(inputText, e){ }, scope);\n
    inputText.on('compositionUpdate', function(inputText, e){ }, scope);\n
"},{"location":"inputtext/#bypass-key-input","title":"Bypass key input","text":"

Registered keyboard events might capture key input.

var keyObj = scene.input.keyboard.addKey('W', enableCapture, emitOnRepeat);\n

Set enableCapture to false to bypass key input to this input-text game objecct.

"},{"location":"inputtext/#other-properties","title":"Other properties","text":"

See dom game object, game object

"},{"location":"inputtext/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"

See dom-element's Interactive with other game objects

"},{"location":"inputtext/#close-editing","title":"Close editing","text":"
  • Close editing (set blur) when pointerdown outside
    scene.input.on('pointerdown', function () {\ninputText.setBlur();\n})\n
  • Close editing (set blur) when ENTER key press
    inputText.on('keydown', function (inputText, e) {\nif ((inputText.inputType !== 'textarea') && (e.key === 'Enter')) {\ninputText.setBlur();\n}\n})\n
    • inputType : 'text', 'textarea', ...
"},{"location":"interception/","title":"Interception","text":""},{"location":"interception/#introduction","title":"Introduction","text":"

Predict the intersection position of two game objects with constant moving speed.

  • Author: Rex
  • Behavior of game object
"},{"location":"interception/#usage","title":"Usage","text":"

Sample code

"},{"location":"interception/#install-plugin","title":"Install plugin","text":""},{"location":"interception/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexinterceptionplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexinterceptionplugin.min.js', true);\n
  • Add interception behavior
    var interception = scene.plugins.get('rexinterceptionplugin').add(gameObject, config);\n
"},{"location":"interception/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import InterceptionPlugin from 'phaser3-rex-plugins/plugins/interception-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexInterception',\nplugin: InterceptionPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add interception behavior
    var interception = scene.plugins.get('rexInterception').add(gameObject, config);\n
"},{"location":"interception/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Interception from 'phaser3-rex-plugins/plugins/interception.js';\n
  • Add interception behavior
    var interception = new Interception(gameObject, config);\n
"},{"location":"interception/#create-instance","title":"Create instance","text":"
var interception = scene.plugins.get('rexInterception').add(gameObject, {\n// target: undefined,\n// enable: true\n});\n
  • target : Game object.
  • enable : Set true to enable predicting.
"},{"location":"interception/#target","title":"Target","text":"
  • Set
    interception.setTarget(gameObject);\n
    or
    interception.target = gameObject;\n
  • Disalbe
    interception.setTarget(undefined);\n
    or
    interception.target = undefined;\n
  • Get
    var target = interception.target;\n
"},{"location":"interception/#enable-predicting","title":"Enable predicting","text":"
  • Enable
    interception.setEnable();\n
  • Disable, uses target position as predicted position
    interception.setEnable(false);\n
"},{"location":"interception/#predicted-result","title":"Predicted result","text":"
  • Predicted position
    var position = interception.predictedPosition; // {x, y}\n
  • Angle to predicted position
    var rotation = interception.predictedAngle; // Angle in radian\n
"},{"location":"interpolation/","title":"Interpolation","text":""},{"location":"interpolation/#introduction","title":"Introduction","text":"

Calculates interpolation value over t (0~1), built-in method of phaser.

  • Author: Richard Davey
"},{"location":"interpolation/#usage","title":"Usage","text":"
  • Linear interpolation (lerp) two values
    var result = Phaser.Math.Linear(p0, p1, t);\n
  • Linear interpolation (lerp) two Vectors
    var result = Phaser.Math.LinearXY(vector0, vector1, t);\n
    • vector0, vector1 : Phaser.Math.Vector2
  • Smooth interpolation
    var result = Phaser.Math.Interpolation.SmoothStep(t, min, max);\n
    • t : 0~1
  • Smoother interpolation
    var result = Phaser.Math.Interpolation.SmootherStep(t, min, max);\n
    • t : 0~1
  • Quadratic bezier interpolation
    var result = Phaser.Math.Interpolation.QuadraticBezier(t, p0, p1, p2);\n
    • t : 0~1
    • p0 : The start point.
    • p1 : The control point.
    • p2 : The end point.
  • Cubic bezier interpolation
    var result = Phaser.Math.Interpolation.CubicBezier(t, p0, p1, p2, p3);\n
    • t : 0~1
    • p0 : The start point.
    • p1 : The first control point.
    • p2 : The second control point.
    • p3 : The end point.
"},{"location":"intouching/","title":"In touching","text":""},{"location":"intouching/#introduction","title":"Introduction","text":"

Fires 'intouch' event every tick when pressing on a game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"intouching/#live-demos","title":"Live demos","text":"
  • Cooldown
  • Is in touching
"},{"location":"intouching/#usage","title":"Usage","text":"

Sample code

"},{"location":"intouching/#install-plugin","title":"Install plugin","text":""},{"location":"intouching/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexintouchingplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexintouchingplugin.min.js', true);\n
  • Add intouching behavior
    var intouching = scene.plugins.get('rexintouchingplugin').add(gameObject, config);\n
"},{"location":"intouching/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import InTouchingPlugin from 'phaser3-rex-plugins/plugins/intouching-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexInTouchingn',\nplugin: InTouchingPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add intouching behavior
    var intouching = scene.plugins.get('rexInTouchingn').add(gameObject, config);\n
"},{"location":"intouching/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import InTouching from 'phaser3-rex-plugins/plugins/intouching.js';\n
  • Add intouching behavior
    var intouching = new InTouching(gameObject, config);\n
"},{"location":"intouching/#create-instance","title":"Create instance","text":"
var intouching = scene.plugins.get('rexInTouching').add(gameObject, {\n// enable: true,\n// cooldown: undefined\n});\n
  • enable : Can touch.
  • cooldown : Fire 'intouch' event every tick, or periodically.
    • undefined : Fire 'intouch' event every tick.
"},{"location":"intouching/#events","title":"Events","text":"
  • In-touching
    intouching.on('intouch', function (intouching, gameObject, pointer) {\n// ...\n}, scope);\n
  • Touching-start
    intouching.on('touchstart', function (intouching, gameObject) {\n// ...\n}, scope);\n
  • Touching-end
    intouching.on('touchend', function (intouching, gameObject) {\n// ...\n}, scope);\n
"},{"location":"intouching/#in-touching","title":"In touching","text":"
var isInTouching = intouching.isInTouching;\n
"},{"location":"intouching/#enable","title":"Enable","text":"
  • Get
    var enabled = intouching.enable;  // enabled: true, or false\n
  • Set
    intouching.setEnable(enabled);  // enabled: true, or false\n// intouching.enable = enabled;\n
  • Toggle
    intouching.toggleEnable();\n
"},{"location":"intouching/#cooldown","title":"Cooldown","text":"
  • Get
    var cooldownTime = intouching.cooldownTime;\n
  • Set
    intouching.setCooldown(time);\n
    or
    intouching.cooldownTime = cooldownTime;\n
"},{"location":"keyboardcombo/","title":"Combo events","text":""},{"location":"keyboardcombo/#introduction","title":"Introduction","text":"

Combo-keys events.

  • Author: Richard Davey
"},{"location":"keyboardcombo/#usage","title":"Usage","text":"
  1. Create combo
    var keyCombo = scene.input.keyboard.createCombo(keys, {\n// resetOnWrongKey: true,\n// maxKeyDelay: 0,\n// resetOnMatch: false,\n// deleteOnMatch: false,\n});\n
    • keys : Array of keyCodes
      • In strings. ex: ['up', 'up', 'down', 'down'], or ['UP', 'UP', 'DOWN', 'DOWN']
      • In key map. ex: [Phaser.Input.Keyboard.KeyCodes.UP, ... ]
      • In numbers. ex: [38, 38, 40, 40]
    • resetOnWrongKey : Set true to reset the combo when press the wrong key.
    • maxKeyDelay : The max delay in ms between each key press. Set 0 to disable this feature.
    • resetOnMatch : Set true to reset the combo when previously matched.
    • deleteOnMatch : Set true to delete this combo when matched.
  2. Listen combo matching event
    scene.input.keyboard.on('keycombomatch', function (keyCombo, keyboardEvent) { /* ... */ });\n
"},{"location":"keyboardevents/","title":"Keyboard events","text":""},{"location":"keyboardevents/#introduction","title":"Introduction","text":"

Built-in keyboard events of phaser.

  • Author: Richard Davey
"},{"location":"keyboardevents/#usage","title":"Usage","text":""},{"location":"keyboardevents/#quick-start","title":"Quick start","text":"
  • Is key-down/is key-up
    var keyObject = scene.input.keyboard.addKey('W');  // Get key object\nvar isDown = keyObject.isDown;\nvar isUp = keyObject.isUp;\nvar shiftKey = keyObject.shiftKey;\n
  • Key is down after a duration
    var keyObject = scene.input.keyboard.addKey('W');  // Get key object\nvar isDown = scene.input.keyboard.checkDown(keyObject, duration);\n
  • On key-down/on key-up
    var keyObject = scene.input.keyboard.addKey('W');  // Get key object\nkeyObject.on('down', function(event) { /* ... */ });\nkeyObject.on('up', function(event) { /* ... */ });\n
    or
    scene.input.keyboard.on('keydown-' + 'W', function (event) { /* ... */ });\nscene.input.keyboard.on('keyup-' + 'W', function (event) { /* ... */ });\n
  • Any key-down/any key-up
    scene.input.keyboard.on('keydown', function (event) { /* ... */ });\nscene.input.keyboard.on('keyup', function (event) { /* ... */ });\n
    • event : KeyboardEvent
      • event.code : 'Key' + 'W'
"},{"location":"keyboardevents/#key-object","title":"Key object","text":"
  • Get key object
    var keyObject = scene.input.keyboard.addKey('W');  // see `Key map` section\n// var keyObject = scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.W);\n
    or
    var keyObject = scene.input.keyboard.addKey('W', enableCapture, emitOnRepeat);\n
    • enableCapture : Automatically call preventDefault on the native DOM browser event for the key codes being added.
    • emitOnRepeat : Controls if the Key will continuously emit a 'down' event while being held down (true), or emit the event just once (false, the default).
  • Get key objects
    var keyObjects = scene.input.keyboard.addKeys('W,S,A,D');  // keyObjects.W, keyObjects.S, keyObjects.A, keyObjects.D\n// var keyObjects = scene.input.keyboard.addKeys('W,S,A,D', enableCapture, emitOnRepeat);\n
    or
    var keyObjects = scene.input.keyboard.addKeys({\nup: 'W',\ndown: 'S',\nleft: 'A',\nright: 'D'\n});  // keyObjects.up, keyObjects.down, keyObjects.left, keyObjects.right\n
  • Remove key object
    scene.input.keyboard.removeKey('W');\n// scene.input.keyboard.removeKey(Phaser.Input.Keyboard.KeyCodes.W);\n// scene.input.keyboard.removeKey(key, destroy, removeCapture);\n
    • destroy : Call Key.destroy on each removed Key object
    • removeCapture : Remove all key captures for Key objects owened by this plugin?
  • Remove all key objects
    scene.input.keyboard.removeAllKeys(true);\n// scene.input.keyboard.removeAllKeys(destroy, removeCapture);\n
    • destroy : Call Key.destroy on each removed Key object
    • removeCapture : Remove all key captures for Key objects owened by this plugin?
  • Key-down/key-up state
    var isDown = keyObject.isDown;\nvar isUp = keyObject.isUp;\n
  • Duration of key-down
    var duration = keyObject.getDuration(); // ms\n
  • Enable/disable
    keyObject.enabled = enabled; // Set false to disable key event\n
"},{"location":"keyboardevents/#key-object-of-cursorkeys","title":"Key object of cursorkeys","text":"
  1. Get key state object
    var cursorKeys = scene.input.keyboard.createCursorKeys();\n
  2. Get key state
    var isUpDown = cursorKeys.up.isDown;\nvar isDownDown = cursorKeys.down.isDown;\nvar isLeftDown = cursorKeys.left.isDown;\nvar isRightDown = cursorKeys.right.isDown;\nvar isSpaceDown = cursorKeys.space.isDown;\nvar isShiftDown = cursorKeys.shift.isDown;\n
"},{"location":"keyboardevents/#order-of-key-downkey-up-events","title":"Order of key-down/key-up events","text":"
  1. Key-down/key-up events of key object
    var keyObject = scene.input.keyboard.addKey('W');  // Get key object\nkeyObject.on('down', function(event) { /* ... */ });\nkeyObject.on('up', function(event) { /* ... */ });\n
    • event.stopImmediatePropagation() : Stop any further listeners from being invoked in the current Scene.
    • event.stopPropagation() : Stop it reaching any other Scene.
  2. On key-down/on key-up
    scene.input.keyboard.on('keydown-' + 'W', function (event) { /* ... */ });\nscene.input.keyboard.on('keyup-' + 'W', function (event) { /* ... */ });\n
    • event.stopImmediatePropagation() : Stop any further listeners from being invoked in the current Scene.
    • event.stopPropagation() : Stop it reaching any other Scene.
    • Invoke event.preventDefault() to stop event propagation to native DOM.
  3. Any key-down/on key-up
    scene.input.keyboard.on('keydown', function (event) { /* ... */ });\nscene.input.keyboard.on('keyup', function (event) { /* ... */ });\n
    • event.key : 'a'
    • event.keyCode : 65
    • event.code : 'KeyA'
    • event.stopImmediatePropagation() : Stop any further listeners from being invoked in the current Scene.
    • event.stopPropagation() : Stop it reaching any other Scene.
"},{"location":"keyboardevents/#destroy-key-object","title":"Destroy key object","text":"
keyObject.destroy();\n
"},{"location":"keyboardevents/#key-map","title":"Key map","text":"
  • A ~ Z
  • F1 ~ F12
  • BACKSPACE
  • TAB
  • ENTER
  • SHIFT
  • CTRL. ALT
  • PAUSE
  • CAPS_LOCK
  • ESC
  • SPACE
  • PAGE_UP, PAGE_DOWN
  • END, HOME
  • LEFT, UP, RIGHT,DOWN
  • PRINT_SCREEN
  • INSERT, DELETE
  • ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE
  • NUMPAD_ZERO, NUMPAD_ONE, NUMPAD_TWO, NUMPAD_THREE, NUMPAD_FOUR, NUMPAD_FIVE, NUMPAD_SIX, NUMPAD_SEVEN, NUMPAD_EIGHT, NUMPAD_NINE, NUMPAD_ADD, NUMPAD_SUBTRACT
  • OPEN_BRACKET, CLOSED_BRACKET
  • SEMICOLON_FIREFOX, COLON, COMMA_FIREFOX_WINDOWS, COMMA_FIREFOX, BRACKET_RIGHT_FIREFOX, BRACKET_LEFT_FIREFOX
"},{"location":"keyshub/","title":"Keys hub","text":""},{"location":"keyshub/#introduction","title":"Introduction","text":"

Key object interface mapping from multiple source of key objects.

  • Author: Rex
  • Member of scene
"},{"location":"keyshub/#live-demos","title":"Live demos","text":"
  • Multiple mode
  • Single mode
  • Define key
"},{"location":"keyshub/#usage","title":"Usage","text":"

Sample code

"},{"location":"keyshub/#install-plugin","title":"Install plugin","text":""},{"location":"keyshub/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexkeyshubplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexkeyshubplugin.min.js', true);\n
  • Add keys-hub object
    var keysHub = scene.plugins.get('rexkeyshubplugin').add(scene, config);\n
"},{"location":"keyshub/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import KeysHubPlugin from 'phaser3-rex-plugins/plugins/keyshub-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexKeysHub',\nplugin: KeysHubPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add keys-hub object
    var keysHub = scene.plugins.get('rexKeysHub').add(scene, config);\n
"},{"location":"keyshub/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import KeysHub from 'phaser3-rex-plugins/plugins/keyshub.js';\n
  • Add keys-hub object
    var keysHub = new KeysHub(scene, config);\n
"},{"location":"keyshub/#create-instance","title":"Create instance","text":"
var keysHub = scene.plugins.get('rexKeysHub').add(scene, {\n// singleMode: false,\n});\n
  • singleMode :
    • true : Unplug old key object then plug new key object.
    • false : Plug new key object without unplug previous key object. Default behavior.
"},{"location":"keyshub/#destroy","title":"Destroy","text":"
keysHub.destroy();\n
"},{"location":"keyshub/#plug-key-object","title":"Plug key object","text":"
  • Plug a set of key objects
    keysHub.plugKeyObject({\nkeyCode0: keyObject0,\nkeyCode1: keyObject1,\n// ...\n});\n
    for example :
    var keyObjects = scene.input.keyboard.addKeys({\nup: 'W',\ndown: 'S',\nleft: 'A',\nright: 'D'\n});\nkeysHub.plugKeyObject(keyObjects);\n
    var keyObjects = scene.input.keyboard.createCursorKeys();\nkeysHub.plugKeyObject(keyObjects);\n
    or
    var keyObjects = joystick.createCursorKeys();\nkeysHub.plugKeyObject(keyObjects);\n
    • keyObjects : {keyCode : keyObject}
    • joystick : Virtual joystick
  • Plug a key object
    keysHub.plugKeyObject(keyObject, keyCode);\n
"},{"location":"keyshub/#unplug-key-object","title":"Unplug key object","text":"
  • Unplug a set of key objects
    keysHubunplugKeyObjects(keyObjects);\n
    • keyObjects : {keyCode : keyObject}
  • Unplugin a key object
    keysHub.unplugKeyObject(keyObject);\n
"},{"location":"keyshub/#key-object-interfacee","title":"Key object interfacee","text":"
  • Get key object
    var keyObject = keysHub.addKey('W');  // see `Key map` section\n// var keyObject = keysHub.addKey(Phaser.Input.Keyboard.KeyCodes.W);\n
    or
    var keyObject = keysHub.addKey('W');\n
  • Get key objects
    var keyObjects = keysHub.addKeys('W,S,A,D');  // keyObjects.W, keyObjects.S, keyObjects.A, keyObjects.D\n
    or
    var keyObjects = keysHub.addKeys({\nup: 'W',\ndown: 'S',\nleft: 'A',\nright: 'D'\n});  // keyObjects.up, keyObjects.down, keyObjects.left, keyObjects.right\n
  • Get curor key objects
    var cursorKeys = keysHub.createCursorKeys();\n
"},{"location":"keyshub/#get-plugged-key-objects","title":"Get plugged key objects","text":"
var keyObject = keysHub.getKeyObjects(key);\n
  • key : Key string, or keyCode number.
  • keyObject :
    • A key object if singleMode is set to true
    • A list of key objects if if singleMode is set to false
"},{"location":"keyshub/#re-define-key-map","title":"Re-define key map","text":"

Set singleMode to ture when creating keysHub instance.

"},{"location":"keyshub/#start-definition-task","title":"Start definition task","text":"
keysHub.defineKeyStart(key);  // key: key string\n
  • Fire 'definekey.start' event
"},{"location":"keyshub/#listen-key-input","title":"Listen key input","text":"
  • From keyboard
    keysHub.listenFromKeyboard();\n
"},{"location":"keyshub/#cancel-definition-task","title":"Cancel definition task","text":"
keysHub.defineKeyCancel();\n
  • Fire 'definekey.complete' event.
"},{"location":"keyshub/#complete-definition-task","title":"Complete definition task","text":"

Complete when any key input

  • Fire 'definekey.complete' event.
"},{"location":"keyshub/#events","title":"Events","text":"
  • On key object plug
    keysHub.on('plug', function(key, keyObject) {\n\n})\n
  • On key object unplug
    keysHub.on('unplug', function(key, keyObject) {\n\n})\n
  • On define-key start
    keysHub.on('definekey.start', function(key) {\n\n})\n
  • On define-key complete
    keysHub.on('definekey.complete', function(key, keyObject) {\n\n})\n
    • key :
      • A string : Plug new key object to that Key object interface.
      • undefined : Cancel define-key task.
    • keyObject :
      • A key object : New plugged key object.
      • undefined : Remove current plugged key.
"},{"location":"layer/","title":"Layer","text":""},{"location":"layer/#introduction","title":"Introduction","text":"

A local display list, built-in game object of phaser.

Layers have no position or size

Layers have no position or size within the Scene

  • Cannot enable a Layer for physics or input.
  • Cannot change the position, rotation or scale of a Layer.
  • No scroll factor, texture, tint, origin, crop or bounds.

Layers cannot be added to Containers

Containers can be added to Layers, but Layers cannot be added to Containers.

  • Author: Richard Davey
"},{"location":"layer/#usage","title":"Usage","text":""},{"location":"layer/#add-layer","title":"Add layer","text":"
var layer = scene.add.layer();\n// var layer = scene.add.layer(children);\n
  • children : Array of game objects added to this layer.
"},{"location":"layer/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLayer extends Phaser.GameObjects.Layer {\nconstructor(scene, children) {\nsuper(scene, children);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var layer = new MyLayer(scene, children);\n
"},{"location":"layer/#add-child","title":"Add child","text":"
  • Add child
    layer.add(gameObject);\n// layer.add(gameObjects);\n
    • gameObject : A game object, or an array of game objects.
  • Add child at
    layer.addAt(gameObject, index);\n
  • Replace child
    layer.replace(oldGameObject, newGameObject);\n
"},{"location":"layer/#remove-child","title":"Remove child","text":"
  • Remove child
    var removed = layer.remove(gameObject);\n
  • Remove child at
    var removed = layer.removeAt(index);\n
  • Remove children between indexes
    var removed = layer.removeBetween(startIndex, endIndex);\n
  • Remove all children
    layer.removeAll();\n

Removed game object won't be added to display list of scene, use

gameObject.addToDisplayList();\n

to add it back to scene's display list.

"},{"location":"layer/#get-child","title":"Get child","text":"
  • Get child at
    var gameObject = layer.getAt(index);\n
  • Get first child by name
    var gameObject = layer.getByName(name);\n
  • Get first child by property
    var gameObject = layer.getFirst(property, value);\n// var gameObject = layer.getFirst(property, value, startIndex, endIndex);\n
  • Get random child
    var gameObject = layer.getRandom();\n// var gameObject = layer.getRandom(startIndex, length);\n
  • Get all children
    var gameObjects = layer.getAll();\n
  • Get index of child
    var index = layer.getIndex(gameObject);\n
  • Get child count
    var count = layer.count(property, value);\n
  • Get total children count
    var count = layer.length;\n
  • Has child
    var hasChild = layer.exists(gameObject);\n
"},{"location":"layer/#iterate","title":"Iterate","text":"
  • Get first child (set iterator index to 0)
    var gameObject = layer.first;\n
  • Get last child (set iterator index to last)
    var gameObject = layer.last;\n
  • Get next child (increase iterator index, until last)
    var gameObject = layer.next;\n
  • Get previous child (decrease iterator index, until 0)
    var gameObject = layer.previous;\n
"},{"location":"layer/#move-child","title":"Move child","text":"
  • Swap
    layer.swap(gameObject1, gameObject2);\n
  • Move to
    layer.moveTo(gameObject, index);\n
  • Bring to top
    layer.bringToTop(gameObject);\n
  • Send to back
    layer.sendToBack(gameObject);\n
  • Move up
    layer.moveUp(gameObject);\n
  • Move down
    layer.moveDown(gameObject);\n
  • Move child1 above child2
    layer.moveAbove(child1, child2);\n
  • Move child1 below child2
    layer.moveBelow(child1, child2);\n
  • Sort
    layer.sort(property);\n
    or
    layer.sort('', function(gameObject1, gameObject2) { return 1; // 0, or -1\n});\n
  • Reverse
    layer.reverse();\n
  • Shuffle
    layer.shuffle();\n

Note

Children game objects also sort by depth.

"},{"location":"layer/#for-each-child","title":"For each child","text":"
layer.each(function(gameObject) {\n\n}, scope);\n
"},{"location":"layer/#set-property","title":"Set property","text":"
layer.setAll(property, value);\n// layer.setAll(property, value, startIndex, endIndex);\n
"},{"location":"layer/#events","title":"Events","text":"
  • On add game object
    layer.events.on('addedtoscene', function(gameObject, scene) {\n\n})\n
  • On remove game object
    layer.events.on('removedfromscene', function(gameObject, scene) {\n\n})\n

layer.events references to scene.events.

"},{"location":"layer/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"layer/#create-mask","title":"Create mask","text":"
var mask = layer.createBitmapMask();\n

See mask

"},{"location":"layer/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"layermanager/","title":"Layer manager","text":""},{"location":"layermanager/#introduction","title":"Introduction","text":"

A dictionary to store Layer game objects. Each layer can have a dedicate camera.

  • Author: Rex
  • Container of game objects
"},{"location":"layermanager/#relationship-diagram","title":"Relationship diagram","text":"

Camera - layer - game object

graph RL\n\n    subgraph Cameras\n      cameraBG[BG]\n      cameraGO[GO]\n      cameraUI[UI]\n    end\n\n    subgraph Layers\n      subgraph BG\n        layerBGBottom[BG-bottom]\n        layerBG[BG]\n        layerBGTop[BG-top]\n      end\n\n      subgraph GO\n        layerGOBottom[GO-bottom]\n        layerGO[GO]\n        layerGOTop[GO-top]\n      end\n\n      subgraph UI\n        layerUIBottom[UI-bottom]\n        layerUI[UI]\n        layerUITop[UI-top]\n      end\n    end\n\n    layerBGBottom --> cameraBG\n    layerBG --> cameraBG\n    layerBGTop --> cameraBG\n\n    layerGOBottom --> cameraGO\n    layerGO --> cameraGO\n    layerGOTop --> cameraGO\n\n    layerUIBottom --> cameraUI\n    layerUI --> cameraUI\n    layerUITop --> cameraUI\n\n    subgraph GameObjects\n      goBG0[\"Background\"] --> layerBG\n      goBG1[\"Background\"] --> layerBG\n\n      go0[GameObject] --> layerGO\n      go1[GameObject] --> layerGO\n      go2[GameObject] --> layerGO\n      go3[GameObject] --> layerGO\n\n      goUI0[Panel] --> layerUI\n      goUI1[Panel] --> layerUI\n      goSYSUI[System dialog] --> layerUITop\n    end
"},{"location":"layermanager/#usage","title":"Usage","text":"

Sample code

"},{"location":"layermanager/#install-plugin","title":"Install plugin","text":""},{"location":"layermanager/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlayermanagerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlayermanagerplugin.min.js', true);\n
  • Add layer manager
    var layerManager = scene.plugins.get('rexlayermanagerplugin').add(scene, config);\n
"},{"location":"layermanager/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LayerManagerPlugin from 'phaser3-rex-plugins/plugins/layermanager-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLayerManager',\nplugin: LayerManagerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add layer manager
    var layerManager = scene.plugins.get('rexLayerManager').add(scene, config);\n
"},{"location":"layermanager/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LayerManager from 'phaser3-rex-plugins/plugins/layermanager.js';\n
  • Add move-to behavior
    var layerManager = new LayerManager(scene, config);\n
"},{"location":"layermanager/#create-instance","title":"Create instance","text":"
var layerManager = scene.plugins.get('rexLayerManager').add(scene, {\n// layers: ['layer0', 'layer1', ...]\n// layers: [{name, cameraName, scrollFactor}, ...]\n\n// depth: undefined,\n// rootLayer: undefined,\n});\n

or

var layerManager = scene.plugins.get('rexLayerManager').add(scene, ['layer0', 'layer1', ...]\n// [{name, cameraName, scrollFactor}, ...]\n);\n
  • layers : Add some initial layers
    • A string array : Add layers by string name
    • A array of plain object { name, cameraName, scrollFactor }
      1. Add layer by string name
      2. Apply scroll factor to all children of this layer.
      3. Bind this layer to dedicate camera (indexed by cameraName), ignore other cameras Add a new camera if this target camera is not existing
  • depth : Set depth to each layer game object.
    • undefined : Keep default depth value (0)
  • rootLayer : Add all layer game objects created by this layer-manager into this root layer.
"},{"location":"layermanager/#destroy","title":"Destroy","text":"
layerManager.destroy()\n

Also destroy all layers in this layer manager.

"},{"location":"layermanager/#add-layer","title":"Add layer","text":"
layerManager.add(name);\n// layerManager.add(name, depth);\n
"},{"location":"layermanager/#add-game-object-to-layer","title":"Add game object to layer","text":"
layerManager.addToLayer(name, gameObject);\n
  • name : Name of layer
  • gameObject : Any kind of game object, include containerLite and related game objects.

Note

Print a warn message if specific layer is not existed.

"},{"location":"layermanager/#get-layer","title":"Get layer","text":"
  • Get layer by name
    var layer = layerManager.getLayer(name);\n
  • Get all layers in this layer manager
    var layers = layerManager.getLayers();\n// var out = layerManager.getLayers(out);\n
"},{"location":"layermanager/#has-layer","title":"Has layer","text":"
var hasLayer = layerManager.has(name);\n// var hasLayer = layerManager.exists(name);\n
"},{"location":"layermanager/#clear-layer","title":"Clear layer","text":"
  • Destroy all children at layer
    layerManager.clearLayer(name);\n
  • Move all children from layer to scene's display list
    layerManager.clearLayer(name, false);\n
"},{"location":"layermanager/#change-depth","title":"Change depth","text":"
  • Bring a layer (layerName) to top of displayList
    layerManager.bringLayerToTop(layerName);\n
  • Send a layer (layerName) to bottom of displayList
    layerManager.sendLayerToBack(layerName);\n
  • Move a layer (layerName) above another layer (baseLayerName)
    layerManager.moveLayerAbove(layerName, baseLayerName)\n
  • Move a layer (layerName) below another layer (baseLayerName)
    layerManager.moveLayerBelow(layerName, baseLayerName)\n
"},{"location":"layermanager/#set-scroll-factor","title":"Set scroll factor","text":"
layerManager.setScrollFactor(scrollFactor);\n// layerManager.setScrollFactor(scrollFactorX, scrollFactorY);\n

Apply scroll factor to all children of this layer.

"},{"location":"layermanager/#bind-camera","title":"Bind camera","text":"
  • Set camera
    layerManager.setCamera(layerName, cameraName);\n
    Bind this layer to dedicate camera (indexed by cameraName), ignore other cameras Add a new camera if this target camera is not existing
  • Get camera
    var camera = layerManager.getCamera(layerName);\n
"},{"location":"levelcounter/","title":"Level counter","text":""},{"location":"levelcounter/#introduction","title":"Introduction","text":"

Map level value from experience value, by callback or a number array.

  • Author: Rex
  • Object
"},{"location":"levelcounter/#live-demos","title":"Live demos","text":"
  • Exp-bar
"},{"location":"levelcounter/#usage","title":"Usage","text":"

Sample code

"},{"location":"levelcounter/#install-plugin","title":"Install plugin","text":""},{"location":"levelcounter/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlevelcounterplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlevelcounterplugin.min.js', true);\n
  • Add level-counter object
    var levelCounter = scene.plugins.get('rexlevelcounterplugin').add(config);\n
"},{"location":"levelcounter/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LevelCounterPlugin from 'phaser3-rex-plugins/plugins/levelcounter-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLevelCounter',\nplugin: LevelCounterPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add level-counter object
    var levelCounter = scene.plugins.get('rexLevelCounter').add(config);\n
"},{"location":"levelcounter/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LevelCounter from 'phaser3-rex-plugins/plugins/levelcounter.js';\n
  • Add level-counter object
    var levelCounter = new LevelCounter(config);\n
"},{"location":"levelcounter/#create-instance","title":"Create instance","text":"
var levelCounter = scene.plugins.get('rexLevelCounter').add({\ntable: function(level) { return level * 100; },\n// table: [0, 100, 200, 300,],\n\n// maxLevel: -1,\n\n// exp: 0,\n});\n
  • table : Level table, return experience value from level value. Level value starts from 0.
    • A callback
      function(level) {\nreturn experience;\n}\n
    • A number array : Experience value of each level.
  • maxLevel :
    • undefined : Default value
      • No upper limit for callback level table.
      • (table.length - 1) for number array level table.
    • A number : Maximum level value
  • exp : Initial experience value. Default value is 0.
"},{"location":"levelcounter/#accumulate-experience","title":"Accumulate experience","text":"
  • Accumulate experience
    levelCounter.gainExp(incExp);\n// levelCounter.exp += incExp;\n
    or
    levelCounter.gainExp(incExp, callback, scope);\n
    • Will fire 'levelup' event, or invoke callback many times.
      function(level, fromExp, toExp, levelStartExp, levelEndExp){        }\n
      • level : To next level
      • fromExp, toExp : Experience increment from fromExp to toExp.
      • levelStartExp, levelEndExp : Range of this level.
  • Reset experience value
    levelCounter.resetExp(exp);\n
    • Won't fire 'levelup' event.
  • Force level up
    levelCounter.setLevel(level);\n
    or
    levelCounter.setLevel(level, callback, scope);\n
    • Will fire 'levelup' event, or invoke callback many times.
      function(level, fromExp, toExp, levelStartExp, levelEndExp){        }\n
      • level : To next level
      • fromExp, toExp : Experience increment from fromExp to toExp.
      • levelStartExp, levelEndExp : Range of this level.
"},{"location":"levelcounter/#level-and-experience","title":"Level and experience","text":"
  • Get current experience
    var exp = levelCounter.getExp();\n// var exp = levelCounter.exp;\n
  • Get current level
    var level = levelCounter.getLevel();\n// var level = levelCounter.level;\n
  • Get current required experience to next level
    var exp = levelCounter.requiredExp;\n
  • Get experience of level
    var exp = levelCounter.getExp(level);\n
  • Get level from experience
    var level = levelCounter.getLevel(exp);\n
  • Get required experience to level
    var exp = levelCounter.getRequiredExpToNextLevel(level);\n// var exp = levelCounter.getRequiredExpToNextLevel(level, exp);\n
"},{"location":"levelcounter/#events","title":"Events","text":"
  • Level-up when accumulating experience
    levelCounter.on('levelup', function(level, fromExp, toExp, levelStartExp, levelEndExp){        }, scope);\n
    • level : To next level
    • fromExp, toExp : Experience increment from fromExp to toExp.
    • levelStartExp, levelEndExp : Range of this level.
"},{"location":"lifetime/","title":"Life time","text":""},{"location":"lifetime/#introduction","title":"Introduction","text":"

Destroy game object when time-out.

  • Author: Rex
  • Behavior of game object
"},{"location":"lifetime/#usage","title":"Usage","text":"

Sample code

"},{"location":"lifetime/#install-plugin","title":"Install plugin","text":""},{"location":"lifetime/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlifetimeplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlifetimeplugin.min.js', true);\n
  • Add life-time behavior
    var lifeTime = scene.plugins.get('rexlifetimeplugin').add(gameObject, config);\n
"},{"location":"lifetime/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LifeTimePlugin from 'phaser3-rex-plugins/plugins/lifetime-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLifeTime',\nplugin: LifeTimePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add life-time behavior
    var lifeTime = scene.plugins.get('rexLifeTime').add(gameObject, config);\n
"},{"location":"lifetime/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LifeTime from 'phaser3-rex-plugins/plugins/lifetime.js';\n
  • Add life-time behavior
    var lifeTime = new LifeTime(gameObject, config);\n
"},{"location":"lifetime/#create-instance","title":"Create instance","text":"
var lifeTime = scene.plugins.get('rexLifeTime').add(gameObject, {\nlifeTime: 1000,\n// destroy: true,\n// start: true\n});\n
  • lifeTime : Life time in ms.
  • destroy : Set true to destroy game object when time-out.
  • start: Set true to starting counting now.
"},{"location":"lifetime/#events","title":"Events","text":"
  • On time-out
    lifeTime.on('complete', function(gameObject, lifeTime){});\n// lifeTime.once('complete', function(gameObject, lifeTime){});\n
"},{"location":"lifetime/#life-time","title":"Life-time","text":"
  • Set
    lifeTime.setLifeTime(time);\n
  • Add to
    lifeTime.addToLifeTime(time);\n
  • Get life-time
    var time = lifeTime.lifeTime;\n
  • Get remainder time
    var time = lifeTime.remainder;\n
  • Is alive
    var isAlive = lifeTime.isAlive;\n
"},{"location":"lifetime/#startstoppauseresume","title":"Start/Stop/Pause/Resume","text":"
  • Start
    lifeTime.start();\n
  • Stop
    lifeTime.stop();\n
  • Pause
    lifeTime.pause();\n
  • Resume
    lifeTime.resume();\n
"},{"location":"light/","title":"Light","text":""},{"location":"light/#introduction","title":"Introduction","text":"

lighting system from normal map.

  • Author: Richard Davey

WebGL only

It only works in WebGL render mode.

"},{"location":"light/#usage","title":"Usage","text":""},{"location":"light/#light-system","title":"Light system","text":""},{"location":"light/#enable","title":"Enable","text":"
  • Enable
    scene.lights.enable();\n
  • Disable
    scene.lights.disable();\n
    or
    scene.lights.active = false;\n
"},{"location":"light/#ambient-color","title":"Ambient color","text":"
scene.lights.setAmbientColor(color);\n
  • color : Integer color value.
"},{"location":"light/#light","title":"Light","text":"
  • Add
    var light = scene.lights.addLight(x, y, radius);\n// var light = scene.lights.addLight(x, y, radius, color, intensity);\n
    • x, y : The horizontal/vertical position of the Light.
    • radius : The radius of the Light.
    • color : The integer RGB color of the light. Default is 0xffffff.
    • intensity : The intensity of the Light.
  • Remove
    scene.lights.removeLight(light);\n
"},{"location":"light/#position","title":"Position","text":"
  • Set
    light.setPosition(x, y);\n
    or
    light.x = x;\nlight.y = y;\n
  • Get
    var x = light.x;\nvar y = light.y;\n
"},{"location":"light/#color","title":"Color","text":"
  • Set
    • Red, green, blue
      light.color.set(red, green, blue);\n
      or
      light.color.r = red;\nlight.color.g = green;\nlight.color.b = blue;\n
    • Integer value
      light.setColor(colorInteger);\n
  • Get
    • Red, green, blue
      var red = light.color.r;\nvar green = light.color.g;\nvar blue = light.color.b;\n
"},{"location":"light/#size","title":"Size","text":"
  • Set
    light.setRadius(radius);\n// light.radius = radius;\n
    or
    light.diameter = diameter;\n// light.width = diameter;\n// light.height = diameter;\n// light.displayWidth = diameter;\n// light.displayHeight = diameter;\n
  • Get
    var radius = light.radius;\n
    or
    var diameter = light.diameter;\n// var diameter = light.displayWidth;\n// var diameter = light.displayHeight;\n// var diameter = light.width;\n// var diameter = light.height;\n
"},{"location":"light/#intensity","title":"Intensity","text":"
  • Set
    light.setIntensity(intensity);\n
    or
    light.intensity = intensity;\n
  • Get
    var intensity = light.intensity;\n
"},{"location":"light/#game-object","title":"Game object","text":""},{"location":"light/#load-texture-with-normal-map","title":"Load texture with normal map","text":"
scene.load.image(key, [url, normalMapUrl]);\n
  • url : Url of texture.
  • url : Url of texture.
  • normalMapUrl : Url of normal map.
"},{"location":"light/#apply-light-pipeline","title":"Apply light pipeline","text":"
gameObject.setPipeline('Light2D');\n
"},{"location":"line/","title":"Line","text":""},{"location":"line/#introduction","title":"Introduction","text":"

Draw a line with start/end/body textures, extended from RenderTexture game object.

  • Author: Rex
  • Game object
"},{"location":"line/#live-demos","title":"Live demos","text":"
  • Line
"},{"location":"line/#usage","title":"Usage","text":"

Sample code

"},{"location":"line/#install-plugin","title":"Install plugin","text":""},{"location":"line/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlineplugin.min.js', true);\n
  • Add line object
    var line = scene.add.rexLine(config);\n
"},{"location":"line/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LinePlugin from 'phaser3-rex-plugins/plugins/line-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLinePlugin',\nplugin: LinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add line object
    var line = scene.add.rexLine(config);\n
"},{"location":"line/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Line from 'phaser3-rex-plugins/plugins/line.js';\n
  • Add line object
    var line = new Line(scene, config);\nscene.add.existing(line);\n
"},{"location":"line/#create-instance","title":"Create instance","text":"
var line = scene.add.rexLine({\nstart: {\nx: 0, y: 0,\nkey: undefined, frame: undefined, origin: 0.5,\n},\n// start: key,\n// start: undefined,\n\nend: {\nx: 0, y: 0,\nkey: undefined, frame: undefined, origin: 1,\n},\n// end: key,\n// end: undefined,\n\nbody: {\nkey: undefined, frame: undefined, extendMode: 1,\nwidth: undefined,\n},\n// body: key,\n});\n
  • start : Configuration of line-start. Or texture key of line-start.
    • start.x, start.y : Position of line-start.
    • start.key, start.frame : Texrure of line-start.
    • start.origin : Origin of line-start. Default is 0.5.
  • end : Configuration of line-end. Or texture key of line-end.
    • end.x, end.y : Position of line-end.
    • end.key, end.frame : Texrure of line-end.
    • end.origin : Origin of line-end. Default is 1.
  • body : Configuration of line-body. Or texture key of line-body.
    • body.key, body.frame : Texrure of line-body. Line-body will be drawn repeatedly.
    • body.extendMode : Extend mode of line-body.
      • 0, or 'scale' : Draw line-body with scaled image game object.
      • 1, or 'repeat' : Draw line-body with tile-sprute game object. (Default value)
    • body.width : Line width.
"},{"location":"line/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLine extends Line {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var line = new MyLine(scene, config);\n
"},{"location":"line/#position-of-line-startline-end","title":"Position of line-start/line-end","text":"
  • Line start
    • Get
      var x0 = line.x0;\nvar y0 = line.y0;\n
    • Set
      line.setLineStartPosition(x, y);\n
      or
      line.x0 = x;\nline.y0 = y;\n
  • Line end
    • Get
      var x1 = line.x1;\nvar y1 = line.y1;\n
    • Set
      line.setLineEndPosition(x, y);\n
      or
      line.x1 = x;\nline.y1 = y;\n
"},{"location":"line/#set-textures","title":"Set textures","text":"
  • Line-start
    • Set line-start texture
      line.setLineStartTexture(key, frameName);\n
    • Set origin of line-start texture
      line.setLineStartOrigin(origin);\n
      • origin : 0~1. Default is 0, to align the left side of line-start texture with start position.
  • Line-end
    • Set line-end texture
      line.setLineEndTexture(key, frameName);\n
    • Set origin of line-end texture
      line.setLineEndOrigin(origin);\n
      • origin : 0~1. Default is 1, to align the right side of line-end texture with end position.
  • Line-body
    • Set line-body texture
      line.setLineBodyTexture(key, frameName);\n
    • Set line-body extend mode
      line.setLineBodyExtendMode(mode);\n
      • mode :
        • 0, or 'scale' : Draw line-body with scaled image game object.
        • 1, or 'repeat' : Draw line-body with tile-sprute game object.
    • Set line-body width
      line.setLineBodyWidth(width);\n
"},{"location":"line/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"line/#create-mask","title":"Create mask","text":"
var mask = line.createBitmapMask();\n

See mask

"},{"location":"line/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"list-inputtext/","title":"Input text","text":"

Solutions of single or multiple line(s) input text.

  • Input text game object (Display: dom / Edit: dom) :
    • Demo
      • type or inputType :
        • 'text' : Single line input.
        • 'textarea' : Multiple line input.
  • Text game object with Text edit behavior (Display: text / Edit: dom) :
    • Demo
      • type :
        • 'text' : Single line input.
        • 'textarea' : Multiple line input.
  • Text game object with Hidden text edit behavior (Display: text / Edit: text, invisible dom) :
    • Demo
      • type or inputType :
        • 'text' : Single line input.
        • 'textarea' : Multiple line input.
  • Canvas input game object (Display: canvas-input / Edit: canvas-input, invisible dom) :
    • Single line input
    • Multiple line input, Text area input
      • textArea : Set true for multiple line input.
"},{"location":"live2d/","title":"Live2d","text":""},{"location":"live2d/#introduction","title":"Introduction","text":"

Display live2d model.

  • Author: Rex
  • Game object
"},{"location":"live2d/#live-demos","title":"Live demos","text":"
  • Transform and hit area
  • Change model

The example Live2D models, Haru and Hiyori, are redistributed under Live2D's Free Material License.

"},{"location":"live2d/#usage","title":"Usage","text":"

Sample code

"},{"location":"live2d/#install-plugin","title":"Install plugin","text":""},{"location":"live2d/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlive2dplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlive2dplugin.min.js', true);\n
  • Load live2d core script, in preload stage
    scene.load.rexLive2dCoreScript(coreScriptURL);\n
  • Load model assets, in preload stage
    scene.load.rexLive2d(key, modelSettingURL);\n
  • Add live2d object
    var live2dGameObject = scene.add.rexLive2d(x, y, key, config);\n
"},{"location":"live2d/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import Live2dPlugin from 'phaser3-rex-plugins/plugins/live2d-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLive2dPlugin',\nplugin: Live2dPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Load live2d core script, in preload stage
    scene.load.rexLive2dCoreScript(coreScriptURL);\n
  • Load model assets, in preload stage
    scene.load.rexLive2d(key, modelSettingURL);\n
  • Add live2d object
    var live2dGameObject = scene.add.rexLive2d(x, y, key, config);\n
"},{"location":"live2d/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import {\nLive2dCoreScriptFileCallback,\nLive2dFileCallback,\nLive2dGameObject\n} from 'phaser3-rex-plugins/plugins/live2d.js';\n
  • Load live2d core script, in preload stage
    Live2dCoreScriptFileCallback.call(scene.load, coreScriptURL);\n
  • Load model assets, in preload stage
    Live2dFileCallback.call(scene.load, key, modelSettingURL);\n
  • Add live2d object
    var live2dGameObject = new Live2dGameObject(scene, x, y, key, config);\nscene.add.existing(live2dGameObject);\n
"},{"location":"live2d/#create-instance","title":"Create instance","text":"
var live2dGameObject = scene.add.rexLive2d(x, y, key, {\n// autoPlayIdleMotion: motionGroupName\n});\n
  • autoPlayIdleMotion : Start motion when idle (i.e. all motions are finished).

Add live2d from JSON

var live2d = scene.make.rexLive2d({\nx: 0,\ny: 0,\nkey: 256,\n// autoPlayIdleMotion: motionGroupName,\n\nadd: true\n});\n
"},{"location":"live2d/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLive2d extends Live2d {\nconstructor(scene, x, y, key, config) {\nsuper(scene, x, y, key, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var live2dGameObject = new MyLive2d(scene, x, y, key, config);\n
"},{"location":"live2d/#change-model","title":"Change model","text":"
live2dGameObject.setModel(key);\n

or

live2dGameObject.setModel(key, {\n// autoPlayIdleMotion: motionGroupName\n})\n
"},{"location":"live2d/#expression","title":"Expression","text":"
  • Set expression
    live2dGameObject.setExpression(name);\n
  • Get expression names
    var names = live2dGameObject.getExpressionNames();\n
    • names : Array of expression names
"},{"location":"live2d/#motion","title":"Motion","text":"
  • Start motion
    live2dGameObject.startMotion(group, no);\n// live2dGameObject.startMotion(group, no, priority);\n
    • group : Group name of motion
    • no : Number of motion in group
    • priority : Priority of this motion
      • 'idle', or 1
      • 'normal', or 2, default value
      • 'force' or 3
  • Start random motion
    live2dGameObject.startMotion(group);\n// live2dGameObject.startMotion(group, undefined, priority);\n
  • Stop all motions
    live2dGameObject.stopAllMotions();\n
  • Get motion names
    var names = live2dGameObject.getMotionNames();\n
  • Get motion names of a group
    var names = live2dGameObject.getMotionNames(group);\n
    • group : Group name of motion
  • Get motion group names
    var names = live2dGameObject.getMotionGroupNames();\n
  • Get current playing motion names
    var names = live2dGameObject.getPlayinigMotionNames();\n
  • Is any motion playing?
    var isPlaying = live2dGameObject.isAnyMotionPlaying();\n
  • Start motion when idle (i.e. all motions are finished)
    live2dGameObject.autoPlayIdleMotion(group);\n
    • group : Group name of motion
  • Set time-scale
    live2dGameObject.setTimeScale(timeScale);\n
    or
    live2dGameObject.timeScale = timeScale;\n
"},{"location":"live2d/#look-at","title":"Look at","text":"
  • Look at
    live2dGameObject.lookAt(x, y, {\n// camera: scene.cameras.main,\n\n// eyeBallX: 1, eyeBallY: 1,\n// angleX: 30, angleY: 30, angleZ: 30,\n// bodyAngleX: 10\n})\n
    • x, y : Look at position.
    • camera : Default value is scene.cameras.main.
    • eyeBallX, eyeBallY : Weight of parameter ParamEyeBallX, ParamEyeBallY.
    • angleX, angleY, angleZ : Weight of parameter ParamAngleX, ParamAngleY, ParamAngleZ.
    • bodyAngleX : Weight of parameter ParamBodyAngleX.
  • Look forward
    live2dGameObject.lookForward();\n
"},{"location":"live2d/#lip-sync","title":"Lip sync","text":"
  • Set lip sync value
    live2dGameObject.setLipSyncValue(value);\n
    or
    live2dGameObject.lipSyncValue = value;\n
  • Get lip sync value
    var value = live2dGameObject.lipSyncValue;\n
"},{"location":"live2d/#hit-test","title":"Hit test","text":""},{"location":"live2d/#touch-events","title":"Touch events","text":"
  1. Set interactive
    live2dGameObject.setInteractive();\n
  2. Register touch events of hit area
    • On pointer down
      live2dGameObject.on('pointerdown-' + hitAreaName, function(pointer, localX, localY, event){\n\n}, scope);\n
      or
      live2dGameObject.on('pointerdown', function(pointer, localX, localY, event){\nvar hitTestResult = live2dGameObject.getHitTestResult(); // {hitAreaName: isHit}\n}, scope);\n
    • On pointer up
      live2dGameObject.on('pointerup-' + hitAreaName, function(pointer, localX, localY, event){\n\n}, scope);\n
      or
      live2dGameObject.on('pointerup', function(pointer, localX, localY, event){\nvar hitTestResult = live2dGameObject.getHitTestResult(); // {hitAreaName: isHit}\n}, scope);\n
    • On pointer move
      live2dGameObject.on('pointermove-' + hitAreaName, function(pointer, localX, localY, event){\n\n}, scope);\n
      or
      live2dGameObject.on('pointermove', function(pointer, localX, localY, event){\nvar hitTestResult = live2dGameObject.getHitTestResult(); // {hitAreaName: isHit}\n}, scope);\n
"},{"location":"live2d/#is-hit","title":"Is hit","text":"
var isHit = live2dGameObject.hitTest(hitAreaName, x, y);\n// var isHit = live2dGameObject.hitTest(hitAreaName, x, y, camera);\n
"},{"location":"live2d/#parameter","title":"Parameter","text":"
  1. Register parameter
    live2dGameObject.registerParameter(name);\n
    • name : Register parameter id = Param + capitalize(name)
  2. Reset and add value
    live2dGameObject\n.resetParameterValue(name)\n.addParameterValue(name, value);\n
    or
    var parameters = live2dGameObject.getParameters();  // {name: value}\nparameters[name] = value;\n
"},{"location":"live2d/#limitation","title":"Limitation","text":"
  • alpha, tint properties does not work
  • Can't apply any post-fx effect or blend mode.
"},{"location":"loader/","title":"Loader","text":""},{"location":"loader/#introduction","title":"Introduction","text":"

Load assets, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"loader/#usage","title":"Usage","text":""},{"location":"loader/#loading-in-preload-stage","title":"Loading in preload stage","text":"
scene.load.image(key, url);\n// scene.load.image(config); // config: {key, url}\n

Loader in preload stage will start loading automatically by scene.

"},{"location":"loader/#loading-after-preload-stage","title":"Loading after preload stage","text":"
scene.load.image(key, url);   // add task\n// scene.load.image(config); // config: {key, url}\nscene.load.once('complete', callback, scope);  // add callback of 'complete' event\nscene.load.start();                     // start loading\n
"},{"location":"loader/#set-path","title":"Set path","text":"
scene.load.setPath(path)\n
"},{"location":"loader/#more-configurations","title":"More configurations","text":"

More configurations in game config

loader:{\nbaseURL: '',\npath: '',\nenableParallel: true,\nmaxParallelDownloads: 4,\ncrossOrigin: undefined,\nresponseType: '',\nasync: true,\nuser: '',\npassword: '',\ntimeout: 0,\nmaxRetries: 2,\nwithCredentials: false,\nimageLoadType: 'XHR',    // 'HTMLImageElement' \nlocalScheme: [ 'file://', 'capacitor://' ]\n},\n
"},{"location":"loader/#events","title":"Events","text":"
  • Load file complete event
    scene.load.on('filecomplete', function(key, type, data) {}, scope);\n
    scene.load.on('filecomplete-' + type + '-' + key, function(key, type, data) {}, scope);\n
  • Add loading file event
    scene.load.on('addfile', function(key, type, file) {}, scope);\n
  • Start loading
    scene.load.once('start', function(){}, scope);\n
  • Loading progressing
    scene.load.on('progress', function(progress){}, scope);\n
    • progress value will increase when a file is loaded, and decrease when a new file loading request is added.
      var loader = scene.load;\nvar total = loader.totalToLoad;\nvar remainder = loader.list.size + loader.inflight.size;\nvar progress = 1 - (remainder / total);\n
  • Loading file progressing
    scene.load.on('fileprogress', function(file, progress){\n// var key = file.key;\n}, scope);\n
  • Loading a file object successful
    scene.load.once('load', function(fileObj){}, scope);\n
  • Loading a file object failed
    scene.load.once('loaderror', function(fileObj){}, scope);\n
  • All loading completed
    • Before releasing resources
      scene.load.once('postprocess', function(loader){}, scope);\n
    • After releasing resources
      scene.load.once('complete', function(loader){}, scope);\n
  • Scene's 'preupdate', 'update', 'postupdate', 'render' events will be triggered during preload stage.
"},{"location":"loader/#status-of-loader","title":"Status of loader","text":"
  • Ready to start loading
    var isReady = scene.load.isReady();\n
  • Is loading
    var isLoading = scene.load.isLoading();\n
"},{"location":"loader/#file-types","title":"File types","text":""},{"location":"loader/#image","title":"Image","text":"
  • Image
    scene.load.image(key, url);\n// scene.load.image(key, url, xhrSettings);\n
    • url : Url of texture, or base64 string of Uri.
  • Image and normal map
    scene.load.image(key, [url, normalMapUrl]);\n// scene.load.image(key, [url, normalMapUrl], xhrSettings);\n
    • url : Url of texture, or base64 string of Uri.
    • normalMapUrl : Url of normal map.
  • SVG
    scene.load.svg(key, url);\n// scene.load.svg(key, url, svgConfig);\n// scene.load.svg(key, url, svgConfig, xhrSettings);\n
    • svgConfig : {width, height}, or {scale}
  • Html texture
    scene.load.htmlTexture(key, url, width, height);\n// scene.load.htmlTexture(key, url, width, height, xhrSettings);\n

Get data from texture cache

var cache = scene.textures;\nvar data = cache.get(key);\n
"},{"location":"loader/#sprite-sheet","title":"Sprite sheet","text":"
scene.load.spritesheet(key, url, {\n// frameWidth: frameWidth,\n// frameHeight: frameHeight,\n// startFrame: startFrame,\n// endFrame: endFrame,\n// margin: margin,\n// spacing: spacing\n});\n// scene.load.spritesheet(key, url, frameConfig, xhrSettings);\n

Get data from texture cache

var cache = scene.textures;\nvar data = cache.get(key);\n
"},{"location":"loader/#texture-atlas","title":"Texture atlas","text":"
scene.load.atlas(key, textureURL, atlasURL);\n// scene.load.atlas(key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings);\n

Get data from texture cache

var cache = scene.textures;\nvar data = cache.get(key);\n

On load complete

scene.load.on('filecomplete-atlasjson-' + key, function(key, type, data) {}, scope);\n
"},{"location":"loader/#multi-file-texture-atlas","title":"Multi file texture atlas","text":"
scene.load.multiatlas(key, atlasURL);\n// scene.load.multiatlas(key, atlasURL, path, baseURL, atlasXhrSettings);\n
  • atlasURL : The absolute or relative URL to load the texture atlas json data file from.
  • path : Optional path to use when loading the textures defined in the atlas data.
  • baseURL : Optional Base URL to use when loading the textures defined in the atlas data.
"},{"location":"loader/#unity-texture-atlas","title":"Unity texture atlas","text":"
scene.load.unityAtlas(key, textureURL, atlasURL);\n// scene.load.unityAtlas(key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings);\n
"},{"location":"loader/#animation","title":"Animation","text":"
scene.load.animation(key, url);\n// scene.load.animation(key, url, dataKey, xhrSettings);\n

Get data from json cache

var cache = scene.json;\nvar data = cache.get(key);\n
"},{"location":"loader/#audio","title":"Audio","text":"
scene.load.audio(key, urls);\n// scene.load.audio(key, urls, {instances: 1}, xhrSettings);\n
  • urls : The absolute or relative URL to load the audio files from, or a blob, or a base64 string of Uri.
  • config.instances : Number of audio instances for HTML5Audio. Defaults to 1.

Get data from cache

var cache = scene.cache.audio;\nvar data = cache.get(key);\n
"},{"location":"loader/#audio-sprite","title":"Audio sprite","text":"
scene.load.audioSprite(key, jsonURL, audioURL, audioConfig);\n// scene.load.audioSprite(key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings);\n
  • jsonURL : The absolute or relative URL to load the json file from.
  • audioURL : The absolute or relative URL to load the audio file from.
  • audioConfig : An object containing an instances property for HTML5Audio. Defaults to 1.
"},{"location":"loader/#video","title":"Video","text":"
scene.load.video(key, url, noAudio);\n// scene.load.video(key, url, noAudio, xhrSettings);\n
  • url : The absolute or relative URL to load the video files from, or a blob.
  • loadEvent : The load event to listen for when not loading as a blob.
    • 'loadeddata' : Data for the current frame is available. Default value.
    • 'canplay' : The video is ready to start playing.
    • 'canplaythrough' : The video can be played all the way through, without stopping.
  • asBlob : Load the video as a data blob, or via the Video element? Default value is false.
  • noAudio : Does the video have an audio track? If not you can enable auto-playing on it.
  • false : Has audio track, default behavior.

Get data from video cache

var cache = scene.video;\nvar data = cache.get(key);\n
"},{"location":"loader/#bitmap-font","title":"Bitmap font","text":"
scene.load.bitmapFont(key, textureURL, fontDataURL);\n// scene.load.bitmapFont(key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings);\n
  • textureURL : The absolute or relative URL to load the font image file from.
  • fontDataURL : The absolute or relative URL to load the font xml data file from, which created by software such as
    • Angelcode Bitmap Font Generator
    • Littera
    • Glyph Designer

Get data from cache

var cache = scene.cache.bitmapFont;\nvar data = cache.get(key);\n
"},{"location":"loader/#tile-map","title":"Tile map","text":"
  • JSON : Created using the Tiled Map Editor and selecting JSON as the export format
    scene.load.tilemapTiledJSON(key, url);\n// scene.load.tilemapTiledJSON(key, url, xhrSettings);\n
  • CSV : Created in a text editor, or a 3rd party app that exports as CSV.
    scene.load.tilemapCSV(key, url);\n// scene.load.tilemapCSV(key, url, xhrSettings);\n

Get data from cache

var cache = scene.cache.tilemap;\nvar data = cache.get(key);\n
"},{"location":"loader/#text","title":"Text","text":"
scene.load.text(key, url);\n// scene.load.text(key, url, xhrSettings);\n

Get data from cache

var cache = scene.cache.text;\nvar data = cache.get(key);\n
"},{"location":"loader/#json","title":"JSON","text":"
scene.load.json(key, url);\n// scene.load.json(key, url, dataKey, xhrSettings);\n
  • dataKey : When the JSON file loads only this property will be stored in the Cache.

Get data from cache

var cache = scene.cache.json;\nvar data = cache.get(key);\n
"},{"location":"loader/#xml","title":"XML","text":"
scene.load.xml(key, url);\n// scene.load.xml(key, url, xhrSettings);\n

Get data from cache

var cache = scene.cache.xml;\nvar data = cache.get(key);\n
"},{"location":"loader/#html","title":"HTML","text":"
scene.load.html(key, url);\n// scene.load.html(key, url, xhrSettings);\n

Get data from cache

var cache = scene.cache.html;\nvar data = cache.get(key);\n
"},{"location":"loader/#css","title":"CSS","text":"
scene.load.css(key, url);\n// scene.load.css(key, url, xhrSettings);\n

Get data from cache

var cache = scene.cache.css;\nvar data = cache.get(key);\n
"},{"location":"loader/#scene","title":"Scene","text":"
scene.load.sceneFile(key, url);\n// scene.load.sceneFile(key, url, xhrSettings);\n

The key matches the class name in the JavaScript file.

"},{"location":"loader/#script","title":"Script","text":"
scene.load.script(key, url);\n// scene.load.script(key, url, type, xhrSettings);\n
  • type :\u3000'script', or 'module'.
"},{"location":"loader/#scripts","title":"Scripts","text":"
scene.load.scripts(key, urlArray);\n// scene.load.scripts(key, urlArray, xhrSettings);\n

Add scripts in the exact order of urlArray.

"},{"location":"loader/#glsl","title":"GLSL","text":"
scene.load.glsl(key, url);\n// scene.load.glsl(key, url, shaderType, xhrSettings);\n
  • shaderType : The type of shader.
    • 'fragment' : Fragment shader. Default value.
    • 'vertex' : Vertex shader.

Get data from cache

var cache = scene.cache.shader;\nvar data = cache.get(key);\n

A glsl file can contain multiple shaders, all separated by a frontmatter block.

---\nname: type: ---\n\nvoid main(void)\n{\n}\n
"},{"location":"loader/#binary","title":"Binary","text":"
scene.load.binary(key, url, dataType);  // dataType: Uint8Array\n// scene.load.binary(key, url, dataType, xhrSettings);\n
  • dataType : Optional type to cast the binary file to once loaded.
    • Uint8Array, Uint8ClampedArray, Uint16Array Uint32Array
    • Int8Array, Int16Array, Int32Array
    • Float32Array, Float64Array
    • BigInt64Array, BigUint64Array

Get data from cache

var cache = scene.cache.binary;\nvar data = cache.get(key);\n
"},{"location":"loader/#plugin","title":"Plugin","text":"
scene.load.plugin(key, url, true); // start plugin when loaded\n// scene.load.plugin(key, url, true, undefined, xhrSettings);\n
  • url : File url or class instance.
"},{"location":"loader/#scene-plugin","title":"Scene plugin","text":"
scene.load.scenePlugin(key, url, systemKey, sceneKey);\n// scene.load.scenePlugin(key, url, systemKey, sceneKey, xhrSettings);\n
  • url : File url or class instance.
"},{"location":"loader/#file-pack","title":"File pack","text":"

Load files in JSON format.

scene.load.pack(key, url);\n// scene.load.pack(key, url, dataKey, xhrSettings);\n

or

scene.load.pack(key, json);\n// scene.load.pack(key, json, dataKey);\n
  • dataKey : When the JSON file loads only this property will be stored in the Cache.

JSON pack file:

{\n'dataKey': {\n// \"prefix\": \"...\",          // optional, extend key by prefix\n// \"path\": \"...\",            // optional, extend url by path\n// \"defaultType\": \"image\",   // optional, default file type\n'files': [\n{\n'type': 'image',\n'key': '...',\n'url': '...'\n},\n{\n'type': 'image',\n'key': '...',\n'url': '...'\n}\n// ...\n]\n},\n\n'node0': {\n'node1': {\n'node2': {\n'files': [\n// ....\n]\n}\n}\n}\n// dataKey: 'node0.node1.node2'\n}\n

File type:

  • audio
  • binary
  • glsl
  • html
  • htmlTexture
  • image
  • json
  • script
  • spritesheet
  • svg
  • text
  • tilemapCSV
  • tilemapJSON
  • xml

Get pack json data from cache

var cache = scene.cache.json;  // pack json is stored in json cache\nvar data = cache.get(key);\n

Event name in 'filecomplete' event : 'filecomplete-packfile-' + key

"},{"location":"loader/#remove-pack-assets","title":"Remove pack assets","text":"
scene.load.removePack(key);\n// scene.load.removePack(key, dataKey);\n
"},{"location":"loader/#replace","title":"Replace","text":"
  1. Remove key.
  2. Load file again.
"},{"location":"loader/#cache","title":"Cache","text":""},{"location":"loader/#get-data","title":"Get data","text":"
var cache = scene.cache.text;\nvar data = cache.get(key);\n
"},{"location":"loader/#add-data","title":"Add data","text":"
var cache = scene.cache.text;\nvar data = cache.add(key);\n
"},{"location":"loader/#release-data","title":"Release data","text":"
var cache = scene.cache.text;\ncache.remove(key);\n
"},{"location":"loader/#data-in-cache","title":"Data in cache","text":"
var cache = scene.cache.text;\nvar hasData = cache.exists(key);\n// var hasData = cache.has(key);\n
"},{"location":"loader/#cache-events","title":"Cache events","text":"
  • Add any item
    cache.events.on('add', function(cache, key, item){\n\n})\n
  • Remove any item
    cache.events.on('remove', function(cache, key, item){\n\n})\n
"},{"location":"loader/#xhr-settings-object","title":"XHR Settings Object","text":"

Parameter xhrSettings

{\nasync: true,\nuser: '',\npassword: '',\ntimeout: 0,\nheaders: undefined,\nheader: undefined,\nheaderValue: undefined,\nrequestedWith: undefined,\noverrideMimeType: undefined,\nwithCredentials: false\n}\n
  • user : Optional username for the XHR request.
  • password : Optional password for the XHR request.
  • timeout : Optional XHR timeout value.
  • headers, header, headerValue, requestedWith : This value is used to populate the XHR setRequestHeader
  • overrideMimeType : Provide a custom mime-type to use instead of the default.
  • withCredentials : Whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests.
"},{"location":"loading-animation-scene/","title":"Loading animation scene","text":""},{"location":"loading-animation-scene/#introduction","title":"Introduction","text":"

Start loading animation scene, stop this scene when loading complete.

  • Author: Rex
  • Methods
"},{"location":"loading-animation-scene/#live-demos","title":"Live demos","text":"

Loading animation scene

"},{"location":"loading-animation-scene/#usage","title":"Usage","text":"

Sample code

"},{"location":"loading-animation-scene/#install-plugin","title":"Install plugin","text":""},{"location":"loading-animation-scene/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexloadinganimationsceneplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexloadinganimationsceneplugin.min.js', true);\n
  • In mainScene, start loading animation scene, or in animation scene, monitor loading status of mainScene.
    scene.plugins.get('rexloadinganimationsceneplugin').startScene(scene, animationSceneKey);\n
  • This plugin will also install AwaitLoader.
"},{"location":"loading-animation-scene/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LoadingAnimationScenePlugin from 'phaser3-rex-plugins/plugins/loadinganimationscene-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLoadingAnimationScene',\nplugin: LoadingAnimationScenePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • In mainScene, start loading animation scene, or in animation scene, monitor loading status of mainScene.
    scene.plugins.get('rexLoadingAnimationScene').startScene(config);\n
  • This plugin will also install AwaitLoader.
"},{"location":"loading-animation-scene/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import StartLoadingAnimationScene from 'phaser3-rex-plugins/plugins/loadinganimationscene.js';\n
  • In mainScene, start loading animation scene, or in animation scene, monitor loading status of mainScene.
    StartLoadingAnimationScene(config);\n
"},{"location":"loading-animation-scene/#start-loading-animation-scene","title":"Start loading animation scene","text":"

In mainScene, start loading animation scene, or in animation scene, monitor loading status of mainScene.

scene.plugins.get('rexLoadingAnimationScene').startScene({\nmainScene: animationScene:\n\nonLoadingComplete: undefined\nonLoadingProgress: undefined\n});\n
  • mainScene : Scene instaance of main scene.
  • animationScene : Scene instance or scene-key of animation scene.
    • This animation scene will be stopped wheen main scene's loading complete totally.
  • onLoadingComplete : Custom task invoked when loading complete.
    function(finishLoading, animationScene) {\n// finishLoading();\n}\n
    • Invoke finishLoading() method (later) to finish loading progress totally.
  • onLoadingProgress : Callback when loading progress is changing.
    function(progress, animationScene) {\n\n}\n
"},{"location":"loadingprogress/","title":"Loading progress","text":""},{"location":"loadingprogress/#introduction","title":"Introduction","text":"

Pop-up dialog for loading-progress, then scale-down this dialog.

  • Author: Rex
  • Behavior of game object
"},{"location":"loadingprogress/#live-demos","title":"Live demos","text":"
  • Loading progress
  • Custom transit
"},{"location":"loadingprogress/#usage","title":"Usage","text":"

Sample code

"},{"location":"loadingprogress/#install-plugin","title":"Install plugin","text":""},{"location":"loadingprogress/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexloadingprogressplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexloadingprogressplugin.min.js', true);\n
  • Add loading-progress behavior
    var loadingProgress = scene.plugins.get('rexloadingprogressplugin').add(gameObject, config);\n
"},{"location":"loadingprogress/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add loading-progress behavior
    var loadingProgress = scene.plugins.get('rexLoadingProgress').add(gameObject, config);\n
"},{"location":"loadingprogress/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LoadingProgress from 'phaser3-rex-plugins/plugins/loadingprogress.js';\n
  • Add loadingprogress behavior
    var loadingProgress = new LoadingProgressBehavoir(gameObject, config);\n
"},{"location":"loadingprogress/#create-instance","title":"Create instance","text":"
var loadingProgress = scene.plugins.get('rexLoadingProgress').add(gameObject, {\n// duration: {\n//     in: 200,\n//     out: 200\n// }\n\n// progress: function(gameObject, progress) {},\n// transitIn: function(gameObject, duration) {},\n// transitOut: function(gameObject, duration) {},\n});\n
  • gameObject : Game object for presenting loading-progress.
  • duration : Duration of transition-in, trantion-out.
    • duration.in : Duration of transition-in (open dialog).
      • 0 : No transition, open dialog immediately.-
    • duration.out : Duration of transition-out (close dialog). Game object will be destroyed after transiting out.
      • 0 : No transition, close dialog immediately.
  • progress : Callback of loading-progress
    function(gameObject, progress) {\n\n}\n
    • progress : Number between 0 to 1.
  • transitIn : Tween behavior of opening dialog.
    • Custom callback
      function(gameObject, duration) {\n\n}\n
  • transitOut : Tween behavior of closing dialog.
    • Custom callback
      function(gameObject, duration) {\n\n}\n
"},{"location":"loadingprogress/#events","title":"Events","text":"
  • On progress
    loadingProgress.on('progress', function(progress) {\n})\n
  • On opened dialog
    loadingProgress.on('open', function(gameObject, loadingProgress) {\n})\n
  • On closed dialog
    loadingProgress.on('close', function() {\n})\n
"},{"location":"localforage-files/","title":"Files","text":""},{"location":"localforage-files/#introduction","title":"Introduction","text":"

Save JSON data, using localforage.

Each file contains header and content indexed by fileID.

  • Author: Rex
  • Member of scene
"},{"location":"localforage-files/#usage","title":"Usage","text":"

Sample code

"},{"location":"localforage-files/#install-plugin","title":"Install plugin","text":""},{"location":"localforage-files/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlocalforagefilesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlocalforagefilesplugin.min.js', true);\n
  • Add localforage-files object
    var fileManager = scene.plugins.get('rexlocalforagefilesplugin').add(config);\n
"},{"location":"localforage-files/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FilesPlugin from 'phaser3-rex-plugins/plugins/localforagefiles-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFiles',\nplugin: FilesPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add localforage-files object
    var fileManager = scene.plugins.get('rexFiles').add(config);\n
"},{"location":"localforage-files/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Files from 'phaser3-rex-plugins/plugins/localforagefiles.js';\n
  • Add localforage-files object
    var fileManager = new Files(config);\n
"},{"location":"localforage-files/#create-instance","title":"Create instance","text":"
var fileManager = scene.plugins.get('rexFiles').add.files({\n// name: 'files',\n// zip: true\n});\n
  • name : Storage name.
  • zip :
    • true : Save compressed stringify json data.
    • false : Save json data directly
"},{"location":"localforage-files/#save-file","title":"Save file","text":"
  • Overwrite
    fileManager.save(fileID, header, content);\n
    • fileID : Unique ID of this file.
    • header : Header data for indexing, a JSON object.
      • Reserve keys : fileID.
    • content : Content/body, a JSON object.
      • Reserve keys : fileID.
  • Update
    fileManager.save(fileID, header, content, true);\n
"},{"location":"localforage-files/#load-headers","title":"Load headers","text":"
fileManager.loadHeaders()\n.then(function(result) { // var headers = result.headers;\n})\n.catch(function(result) {\n// var error = result.error;\n})\n
  • headers : Get header by headers[fileID], each header contains
    • header.fileID : Unique ID of this file.
"},{"location":"localforage-files/#load-file","title":"Load file","text":"
fileManager.load(fileID)\n.then(function(result) { // var header = result.header;\n// var content = result.content;\n// var fileID = result.fileID;\n})\n.catch(function(result) {\n// var error = result.error;\n// var fileID = result.fileID;\n})\n
  • header, content : Header/content of this file.
  • fileID : Unique ID of this file.
  • userID : User ID of file owner.
"},{"location":"localforage/","title":"LocalForage","text":""},{"location":"localforage/#introduction","title":"Introduction","text":"

Offline storage, improved.

  • Author: Mozilla
"},{"location":"localforage/#usage","title":"Usage","text":"

Official document

Sample code

By default, LocalForage selects backend drivers for the datastore in this order:

  1. IndexedDB
  2. WebSQL
  3. localStorage
"},{"location":"localforage/#save-data","title":"Save data","text":"
  • Callback
    localforage.setItem(key, value, function(){ /* ... */ });\n
  • Promise
    localforage.setItem(key, value)\n.then(function(value){ /* ... */ })\n.catch(function(err){ /* ... */ });\n
"},{"location":"localforage/#read-data","title":"Read data","text":"
  • Callback
    localforage.getItem(key, function(err, value){ /* ... */ });\n
  • Promise
    localforage.getItem(key)\n.then(function(value){ /* ... */ })\n.catch(function(err){ /* ... */ });\n
"},{"location":"localforage/#remove-data","title":"Remove data","text":"
  • Callback
    localforage.removeItem(key, function(){ /* ... */ });\n
  • Promise
    localforage.removeItem(key)\n.then(function(value){ /* ... */ })\n.catch(function(err){ /* ... */ });\n
"},{"location":"localstorage-data/","title":"Data manager","text":""},{"location":"localstorage-data/#introduction","title":"Introduction","text":"

Sync data from data manager to local-storage.

  • Author: Rex
  • Member of scene

Max Size

5MB per app per browser.

"},{"location":"localstorage-data/#live-demos","title":"Live demos","text":"
  • Extend game registry
  • New local storage data manager
"},{"location":"localstorage-data/#usage","title":"Usage","text":"

Sample code

"},{"location":"localstorage-data/#install-plugin","title":"Install plugin","text":""},{"location":"localstorage-data/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlocalstoragedataplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlocalstoragedataplugin.min.js', true);\n
  • Extend existed data object (game.registry, or scene.data)
    var data = scene.plugins.get('rexlocalstoragedataplugin').extend(game.registry, config);\n// var data = scene.plugins.get('rexlocalstoragedataplugin').extend(scene.data, config);\n
  • New local storage data manager
    var data = scene.plugins.get('rexlocalstoragedataplugin').add(parent, config);\n
"},{"location":"localstorage-data/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LocalStorageDataPlugin from 'phaser3-rex-plugins/plugins/localstoragedata-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLocalStorageData',\nplugin: LocalStorageDataPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Extend existed data object (game.registry, or scene.data)
    var data = scene.plugins.get('rexLocalStorageData').extend(game.registry, config);\n// var data = scene.plugins.get('rexLocalStorageData').extend(scene.data, config);\n
  • New local storage data manager
    var data = scene.plugins.get('rexLocalStorageData').add(parent, config);\n
"},{"location":"localstorage-data/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LocalStorageData from 'phaser3-rex-plugins/plugins/localstoragedata.js';\n
  • New local storage data manager
    var data = new LocalStorageData(parent, config);\n
"},{"location":"localstorage-data/#create-instance","title":"Create instance","text":"
var data = scene.plugins.get('rexLocalStorageData').add({\n// name: '',\n// load: true,\n// default: undefined,\n// reset: false\n});\n// var data = scene.plugins.get('rexLocalStorageData').add(parent, config);\n// var data = scene.plugins.get('rexRData').add(parent, eventEmitter, config);\n
  • name : Prefix of key in local storage.
  • load :
    • true : Load data from local storage. Default behavior.
    • false : Don't load data now.
  • default : Define valid keys and default values of loaded data.
    • undefined : Load all keys from local storage.
  • reset :
    • true : Reset all data to default values (default), clear keys which are not in defaultData.
  • parent : The object (a scene, or a game object) that this DataManager belongs to.
  • eventEmitter : The DataManager's event emitter.
"},{"location":"localstorage-data/#load","title":"Load","text":"
data.load(defaultData);\n// data.load(defaultData, reset);\n
  • defaultData : Define valid keys and default values of loaded data.
    • undefined : Load all keys from local storage. reset will be false in this case.
  • reset :
    • true : Reset all data to default values (defaultData), clear keys which are not in defaultData.

Note

Data loaded from local storage already, if load is true.

"},{"location":"localstorage-data/#getsetremove-value","title":"Get/set/remove value","text":"

See built-in data manager.

"},{"location":"localstorage-data/#reserved-keys","title":"Reserved keys","text":"

'__keys__' is used internally by this plugin.

"},{"location":"localstorage-data/#get-default-value","title":"Get default value","text":"
var value = data.getDefaultValue(key);\n
"},{"location":"localstorage/","title":"LocalStorage","text":""},{"location":"localstorage/#introduction","title":"Introduction","text":"

Store small data in key-value pairs locally within the user's browser.

  • Author: Built-in javascript function

Max Size

5MB per app per browser.

"},{"location":"localstorage/#usage","title":"Usage","text":"

Reference

Sample code

"},{"location":"localstorage/#save-data","title":"Save data","text":"
localStorage.setItem(key, value);\n
"},{"location":"localstorage/#read-data","title":"Read data","text":"
var value = localStorage.getItem(key);\n

Note

The keys and the values are always strings. Objects, integer keys will be automatically converted to strings.

"},{"location":"localstorage/#remove-data","title":"Remove data","text":"
localStorage.removeItem(key);\n
"},{"location":"lokijs/","title":"LokiJs","text":""},{"location":"lokijs/#introduction","title":"Introduction","text":"

In-memory JavaScript Datastore with Persistence.

  • Reference
  • Document
"},{"location":"lokijs/#usage","title":"Usage","text":"

Sample code

"},{"location":"lokijs/#create-database","title":"Create database","text":"
var db = new loki();\n// var db = new loki('loki.json', config);  // load database from file\n
"},{"location":"lokijs/#create-collection","title":"Create collection","text":"
var collection = db.addCollection(name);\n// var collection = db.addCollection(name, config);\n
"},{"location":"lokijs/#get-collection","title":"Get collection","text":"
var collection = db.getCollection(name);\n
"},{"location":"lokijs/#insert-document","title":"Insert document","text":"
var docInColl = collection.insert(doc);  // doc: an object\n

Get Id

var id = docInColl.$loki;\n
"},{"location":"lokijs/#insert-documents","title":"Insert documents","text":"
collection.insert(docArray);  // documents in array\n
"},{"location":"lokijs/#query","title":"Query","text":""},{"location":"lokijs/#get-document-by-id","title":"Get document by id","text":"
var doc = collection.get(id);  // id: `$loki`\n
"},{"location":"lokijs/#get-doc-by-unique-index","title":"Get doc by unique index","text":"
var doc = collection.by(key, value);\n
"},{"location":"lokijs/#filter-documents","title":"Filter documents","text":"
  • $eq : filter for document(s) with property of (strict) equality
    var docArray = collection.find({key: value});\n// var docArray = collection.find({key: {'$eq': value});\n
  • $aeq : filter for document(s) with property of abstract (loose) equality
    var docArray = collection.find({key: {'$aeq': value}});\n
    For example
    var results = coll.find({age: {'$aeq': 20}});  // age == '20' or age == 20\n
  • $ne : filter for document(s) with property not equal to provided value
    var docArray = collection.find({key: {'$ne': value}});\n
  • $gt : filter for document(s) with property greater than provided value
    var docArray = collection.find({key: {'$gt': value}});\n
  • $gte : filter for document(s) with property greater or equal to provided value
    var docArray = collection.find({key: {'$gte': value}});\n
  • $lt : filter for document(s) with property less than provided value
    var docArray = collection.find({key: {'$lt': value}});\n
  • $lte : filter for document(s) with property less than or equal to provided value
    var docArray = collection.find({key: {'$lte': value}});\n
  • $between : filter for documents(s) with property between provided values
    var docArray = collection.find({key: {'$between': [value0, value1]}});\n
  • $in : filter for document(s) with property matching any of the provided array values
    var docArray = collection.find({key: {'$in': [value0, value1, ...]}});\n
    Your property should not be an array but your compare values should be.
  • $nin : filter for document(s) with property not matching any of the provided array values
    var docArray = collection.find({key: {'$nin': [value0, value1, ...]}});\n
  • $contains : filter for document(s) with property containing the provided value
    var docArray = collection.find({key: {'$contains': value}});\n
    Use this when your property contains an array but your compare value is not an array
  • $containsAny : filter for document(s) with property containing any of the provided values
    var docArray = collection.find({key: {'$containsAny': [value0, value1, ...]}});\n
  • $containsNone : filter for documents(s) with property containing none of the provided values
    var docArray = collection.find({key: {'$containsNone': [value0, value1, ...]}});\n
  • $regex : filter for document(s) with property matching provided regular expression
    var docArray = collection.find({key: {'$regex': pattern}});\n// var docArray = collection.find({key: {'$regex': [pattern, options]});\n
    For example
    var docArray = collection.find({key: { '$regex': 'din' }});\nvar docArray = collection.find({key: { '$regex': ['din', 'i'] }});\n
  • $dteq: filter for document(s) with date property equal to provided date value
    var docArray = collection.find({key: {'$dteq': new Date('1/1/2017')}});\n
  • $type : filter for documents which have a property of a specified type
    var docArray = collection.find({key: {'$type': value}}); // 'string', or 'number', ...\n
  • $size : filter for documents which have array property of specified size
    var docArray = collection.find({key: {'$size': value}});\n
    (does not work for strings)
  • $len : filter for documents which have string property of specified length
    var docArray = collection.find({key: {'$len': value}});\n
  • $or : filter for documents which meet any of the nested subexpressions
    var docArray = collection.find({'$or': [\n{key0: {'$lt': value0}},\n{key1: {'$gte': value1}},\n// ...\n]});\n
"},{"location":"lokijs/#find-one-document","title":"Find one document","text":"
var doc = collection.findOne({});\n
"},{"location":"lokijs/#filter-by-function","title":"Filter by function","text":"
var docArray = collection.where(function(doc){\n// ...\nreturn isPicked;  // true to pick this document\n})\n
"},{"location":"lokijs/#sort","title":"Sort","text":"
  • Sort with a key
    var docArray = collection.chain().find({}).simplesort(key).data();  // ascending\n// var docArray = collection.chain().find({}).simplesort(key, {desc: true}).data();  // descending\n
  • Sort with mutiple keys
    var docArray = collection.chain().find({}).compoundsort([key0, key1]).data();  // key0, key1: ascending\n// var docArray = collection.chain().find({}).compoundsort([key0, [key1, true]]).data(); // key0: ascending, key1: descending\n
  • Sort with function
    var docArray = collection.chain().find({}).sort(\nfunction(doc1, doc2) {\nreturn result; // 0, 1, -1\n})\n.data();\n
    result:
    • 0: equal
    • 1: greater
    • -1: less
"},{"location":"lokijs/#pagination","title":"Pagination","text":"

Get documents from start to start+count-1.

var docArray = collection.chain().find({}).offset(start).limit(count).data();\n
"},{"location":"lokijs/#update","title":"Update","text":"

Update each filtered documents.

var docArray = collection.chain().find({}).update(\nfunction(doc) { //\nreturn doc;\n});\n
"},{"location":"lokijs/#remove","title":"Remove","text":"

Remove filtered documents.

collection.chain().find({}).remove();\n
"},{"location":"lokijs/#map","title":"Map","text":"

Map document into a new anonymous collection, won't affect original collection.

var docArray = collection.chain().find({}).map(\nfunction(doc) {\n// ...\nreturn doc\n})\n.data();\n
"},{"location":"lokijs/#map-reduce","title":"Map-reduce","text":"
  1. Map document into a new anonymous collection
  2. Run reduceFn to get final result value from result set of step 1.
var mapFn = function(doc) {\n// ...\nreturn doc\n};\nvar reduceFn = function(docArray) {\n// ...\nreturn result;\n}\nvar result = collection.chain().find({}).mapReduce(mapFn, reduceFn);\n
"},{"location":"lokijs/#clone-result-set","title":"Clone result set","text":"
var resultSet = collection.chain().find({});\nvar resultSetClone = resultSet.branch();\n\n// resultSetClone.find({}).data();\n
"},{"location":"lokijs/#dynamic-view","title":"Dynamic view","text":"
  1. Create dynamic view
    var view = children.addDynamicView(name);\n
  2. Add filters
    • find
      view.applyFind({});\n
    • where
      view.applyWhere(function(doc) { return true; });\n
    • simple sort
      view.applySimpleSort(key);\n
    • sort by multiple keys
      view.applySortCriteria([key0, key1]);\n// view.applySortCriteria([key0, [key1, true]]);\n
    • sort function
      view.applySort(function(doc1, doc2) {\nreturn result; // 0, 1, -1\n});\n
      result:
      • 0: equal
      • 1: greater
      • -1: less
  3. Get result data
    var docArray = view.data();\n

Add new filters

var docArray = view.branchResultset().find({}).data();\n

"},{"location":"lokijs/#speed-up-quering","title":"Speed-up quering","text":""},{"location":"lokijs/#custom-unique-index","title":"Custom unique index","text":"
  1. Define custom unique index
    var collection = db.addCollection(name, {\nunique: [key0]\n});\n
  2. Get document by custom unique index
    var doc = collection.by(key0, value);\n
"},{"location":"lokijs/#binary-indices","title":"Binary indices","text":"
  1. Define binary index
    var collection = db.addCollection(name, {\nindices: [key0]\n});\n
    Or
    collection.ensureIndex(key);\n
  2. Get documents by normal filters
    var docArray = collection.find({key0: {'$gt': value}});\n
"},{"location":"lokijs/#methods-of-collection","title":"Methods of collection","text":"
  • Average value of a property
    var avgValue = collection.avg(key);\n
  • Maximum value of a property
    var maxValue = collection.max(key);\n
  • Minimum value of a property
    var minValue = collection.min(key);\n
  • Median value of a property
    var medianValue = collection.median(key);\n
  • Amount of documents
    var amount = collection.count(query);  // {key: {'$gt': value}}\n
"},{"location":"lokijs/#serialize-deserialize","title":"Serialize & Deserialize","text":"
  • Database as string
    var s = db.serialize();\n
  • Load database from string
    db.loadJSON(s);\n
"},{"location":"luxon/","title":"Luxon","text":""},{"location":"luxon/#introduction","title":"Introduction","text":"

Parse, validate, manipulate, and display dates and times. Reference

"},{"location":"luxon/#usage","title":"Usage","text":"
  • Install
  • Getting started
    • Demo
    • A quick tour
    • API
"},{"location":"luxon/#creating-a-datetime","title":"Creating a DateTime","text":"
const dt = DateTime.local(2017, 5, 15, 8, 30);\n

or

var dt = DateTime.fromISO('2017-05-15');\n// var dt = DateTime.fromISO('2017-05-15T17:36');\n// var dt = DateTime.fromISO('2017-W33-4');\n// var dt = DateTime.fromISO('2017-W33-4T04:45:32.343');\n
"},{"location":"luxon/#current-date-and-time","title":"Current date and time","text":"
const now = DateTime.now();\n// const now = DateTime.local();\n
"},{"location":"luxon/#json","title":"JSON","text":"
  • To JSON
    var json = dt.toObject();\n
  • From JSON
    var dt = DateTime.fromObject(json);\n// var dt = DateTime.fromObject({year: 2017, month: 5, day: 15, hour: 17, minute: 36});\n
"},{"location":"luxon/#math","title":"Math","text":"
var dt1 = dt0.plus({ hours: 3, minutes: 2 });\nvar dt1 = dt0.minus({ days: 7 });\nvar dt1 = dt0.startOf('day');\nvar dt1 = dt0.endOf('hour');\n
"},{"location":"luxon/#difference","title":"Difference","text":"
var i1 = DateTime.fromISO('1982-05-25T09:45'),\ni2 = DateTime.fromISO('1983-10-14T10:30');\ni2.diff(i1).toObject() //=> { milliseconds: 43807500000 }\ni2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }\ni2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }\ni2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }\n
"},{"location":"luxon/#durations","title":"Durations","text":"
var dur = Duration.fromObject({ hours: 2, minutes: 7 });\n// dt.plus(dur);\n\ndur.as('seconds') //=> 7620\ndur.toObject()    //=> { hours: 2, minutes: 7 }\ndur.toISO()       //=> 'PT2H7M'\n
"},{"location":"luxon/#parseformat","title":"Parse/Format","text":"
  • Parse
    var dt = DateTime.fromFormat('12-16-2017', 'MM-dd-yyyy');\n// var dt = DateTime.fromFormat('May 25, 1982', 'MMMM dd, yyyy');\n// var dt = DateTime.fromFormat('mai 25, 1982', 'MMMM dd, yyyy', { locale: 'fr' });\n
  • Format
    var s = dt.toFormat('MM-dd-yyyy');\n// var s = dt.toFormat('MMMM dd, yyyy')\n// var s = dt.setLocale('fr').toFormat('MMMM dd, yyyy')\n
"},{"location":"luxon/#relative-time","title":"Relative time","text":"

Returns a string representation of this date relative to today.

var s = dt.toRelativeCalendar();\n
var s = dt.toRelativeCalendar({\nbase: dt0,\nlocale: string,\nunit: string\n});\n
  • base : The DateTime to use as the basis to which this time is compared. Defaults to now.
  • locale : Override the locale of this DateTime.
  • unit : Use a specific unit; if omitted, the method will pick the unit. Use one of 'years', 'quarters', 'months', 'weeks', or 'days'
"},{"location":"lzstring/","title":"LZ string","text":""},{"location":"lzstring/#introduction","title":"Introduction","text":"

Compress string using LZ-based compression algorithm. Reference

  • Author: Rex
  • Member of scene
"},{"location":"lzstring/#usage","title":"Usage","text":"

Sample code

"},{"location":"lzstring/#install-plugin","title":"Install plugin","text":""},{"location":"lzstring/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlzstringplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlzstringplugin.min.js', true);\n
  • Add lz-string object
    var lzstring = scene.plugins.get('rexlzstringplugin').add(config);\n
"},{"location":"lzstring/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LZStringPlugin from 'phaser3-rex-plugins/plugins/lzstring-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLZString',\nplugin: LZStringPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add lz-string object
    var lzstring = scene.plugins.get('rexLZString').add(config);\n
"},{"location":"lzstring/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LZString from 'phaser3-rex-plugins/plugins/lzstring.js';\n
  • Add lz-string object
    var lzstring = new LZString(config);\n
"},{"location":"lzstring/#create-instance","title":"Create instance","text":"
var lzstring = scene.plugins.get('rexLZString').add({\n// encoding: 'none'     // 'none'|0, 'base64'|1, 'utf16'|2, 'uri'|3\n});\n
  • encoding :
    • 'none', or 0 : no encoding.
    • 'base64', or 1 : base64 encoding.
    • 'utf16', or 2 : UTF16 encoding.
    • 'uri', or 3 : URI encoding.
"},{"location":"lzstring/#compression","title":"Compression","text":"
var compressionResult = lzstring.compress(src);\n
"},{"location":"lzstring/#decompression","title":"Decompression","text":"
var decompressionResult = lzstring.decompress(compressionResult);\n
"},{"location":"lzstring/#set-encoding","title":"Set encoding","text":"
lzstring.setEncoding(m);  // 0|'none'|1|'base64'|2|'utf16'|3|'uri'\n
"},{"location":"mainloop/","title":"Main loop","text":"
  1. game.events prestep event. Global Managers like Input and Sound update.
    1. trigger game.sound.update()
  2. game.events step event. User-land code and plugins
    • Register event
      scene.game.events.on('step', function(time, delta){\n//\n}, scope);\n
  3. Update the Scene Manager and all active Scenes
    1. scene.events preupdate event
      • Register event
        scene.events.on('preupdate', function(time, delta){\n//\n}, scope);\n
      • InputPlugin.preUpdate()
      • TweenManager.preUpdate() to arrange active targets
      • UpdateList.preUpdate(), to arrange game objects in UpdateList
    2. scene.events update event
      • Register event
        scene.events.on('update', function(time, delta){\n//\n}, scope);\n
      • TweenManager.update(), to run active tweens
      • UpdateList.update
        • gameObject.preUpdate
      • Update arcade world
    3. scene.update()
    4. scene.events postupdate event
      • Register event
        scene.events.on('postupdate', function(time, delta){\n//\n}, scope);\n
  4. game.events poststep event. Final event before rendering starts.
    • Register event
      scene.game.events.on('poststep', function(time, delta){\n//\n}, scope);\n
  5. game.renderer.preRender()
  6. game.events prerenderclear event
    • Register event
      scene.game.events.on('prerenderclear', function(){\n//\n}, scope);\n
  7. game.events prerender event
    • Register event
      scene.game.events.on('prerender', function(){\n//\n}, scope);\n
  8. SceneManager.render()
    1. Sort display list
    2. scene.events prerender event
      • Register event
        scene.events.on('prerender', function(renderer){\n//\n}, scope);\n
    3. Render cameras
    4. scene.events render event
      • Register event
        scene.events.on('render', function(renderer){\n//\n}, scope);\n
  9. game.renderer.postRender()
  10. game.events postrender event. Final event before the step repeats.
    • Register event
      scene.game.events.on('postrender', function(renderer, time, delta){\n//\n}, scope);\n

Note

Each scene is a standalone system.

"},{"location":"mainloop/#flow-chart","title":"Flow chart","text":""},{"location":"mainloop/#game-loop","title":"Game loop","text":"
graph TB\n\nsubgraph Render\nGameRenderPreRender[\"game.renderer.preRender()\"]\nGameEventPreRenderClear>\"game.events: prerenderclear\"]\nGameEventPreRender>\"game.events: prerender\"]\nSceneManagerRender[\"SceneManager.render()<br>...See 'Scene steps'...\"]\nGameRenderPostRender[\"game.renderer.postRender()\"]\nGameEventPostRender>\"game.events: postrender\"]\nend\n\nsubgraph Step\nGameEventPreStep>\"game.events: prestep<br><br>sound.update()\"]\nGameEventStep>\"game.events: step\"]\nSceneManagerUpdate[\"SceneManager.update()<br>...See 'Scene steps'...\"]\nGameEventPostStep>\"game.events: poststep\"]\nend\n\n\nGameEventPreStep --> GameEventStep\nGameEventStep --> SceneManagerUpdate\nSceneManagerUpdate --> GameEventPostStep\nGameEventPostStep --> GameRenderPreRender\nGameRenderPreRender --> GameEventPreRenderClear\nGameEventPreRenderClear --> GameEventPreRender\nGameEventPreRender --> SceneManagerRender\nSceneManagerRender --> GameRenderPostRender\nGameRenderPostRender --> GameEventPostRender\nGameEventPostRender --> GameEventPreStep
"},{"location":"mainloop/#scene-steps","title":"Scene steps","text":"
graph TB\n\nsubgraph Render\nSceneEventPreRender>\"scene.events: prerender\"]\nSceneCameraRender[\"scene.cameras.render()\"]\nSceneEventRender>\"scene.events: render\"]\nend\n\nsubgraph Update\nSceneEventPreUpdate>\"scene.events: preupdate<br><br>InputPlugin.preUpdate()<br>TweenManager.preUpdate()<br>UpdateList.preUpdate()\"]\nSceneEventUpdate>\"scene.events: update<br><br>TweenManager.update()<br>UpdateList.update()<br>gameObject.preUpdate()\"]\nSceneUpdate[\"scene.update()\"]\nSceneEventPostUpdate>\"scene.events: postupdate\"]\nend\n\n\nSceneEventPreUpdate --> SceneEventUpdate\nSceneEventUpdate --> SceneUpdate\nSceneUpdate --> SceneEventPostUpdate\n\nSceneEventPostUpdate -.-> SceneEventPreRender\nSceneEventPreRender --> SceneCameraRender\nSceneCameraRender --> SceneEventRender
"},{"location":"mainloop/#rendering-order","title":"Rendering order","text":"
  • For each scene from bottom to top, in game
    • For each camera from bottom to top, in scene
      • For each game object from bottom to top in scene's displayList
        • Render this game object
          • Render children game objects, if game object is a container or a layer

Note

A game object can be seen by all cameras of this scene, therefore game object could be rendering more than one times.

See also Ignore game object

"},{"location":"markedeventsheet/","title":"Markdown event sheets","text":""},{"location":"markedeventsheet/#introduction","title":"Introduction","text":"

Event sheets contains main condition(s) and actions, in simple markdown format (headings, code block).

  • Author: Rex
  • Member of scene
"},{"location":"markedeventsheet/#live-demos","title":"Live demos","text":"
  • Command executor
"},{"location":"markedeventsheet/#usage","title":"Usage","text":"
  • Sample code
  • Event sheets
"},{"location":"markedeventsheet/#install-plugin","title":"Install plugin","text":""},{"location":"markedeventsheet/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexmarkedeventsheetsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexmarkedeventsheetsplugin.min.js', true);\n
  • Add event-sheet-manager object
    var eventSheetManager = scene.plugins.get('rexmarkedeventsheetsplugin').add(config);\n
"},{"location":"markedeventsheet/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import MarkedEventSheetsPlugin from 'phaser3-rex-plugins/plugins/markedeventsheets-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexMarkedEventSheets',\nplugin: MarkedEventSheetsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add event-sheet-manager object
    var eventSheetManager = scene.plugins.get('rexMarkedEventSheets').add(config);\n
"},{"location":"markedeventsheet/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import MarkedEventSheets from 'phaser3-rex-plugins/plugins/markedeventsheets.js';\n
  • Add event-sheet-manager object
    var eventSheetManager = new MarkedEventSheets(config);\n
"},{"location":"markedeventsheet/#create-instance","title":"Create instance","text":"
var eventSheetManager = scene.plugins.get('rexMarkedEventSheets').add({\ncommandExecutor: Object,\nparallel: false\n});\n
  • commandExecutor : Command executor of actions.
    • This plugin provides a built-in command executor.
  • parallel :
    • false : Test condition then execute event sheet one by one. Default behavior.
    • true : Test all condition of event sheets then execute event sheets one by one.
"},{"location":"markedeventsheet/#add-event-sheet","title":"Add event sheet","text":"

Each event sheet belong a group.

eventSheetManager.addEventSheet(content, {\ncommentLineStart: '\\/\\/',\nlineBreak: '\\\\',\nparallel: undefined,\nactive: true,\nonce: false\n})\n

or

eventSheetManager.addEventSheet(content, groupName, {\ncommentLineStart: '\\/\\/',\nlineBreak: '\\\\',\nparallel: undefined,\nactive: true,\nonce: false\n})\n

or

eventSheetManager.addEventSheet(content, {\ngroupName: '_'\ncommentLineStart: '\\/\\/',\nlineBreak: '\\\\',\nparallel: undefined,\nactive: true,\nonce: false\n})\n
  • content : See structure of event sheet
  • commentLineStart : Content line start by this symobl (default value is //) will be ignored as a comment line.
  • lineBreak : Markdown will use \\ as line break. So the last character \\ will be discarded.
  • parallel :
    • undefined : Use default parallel property.
  • active :
    • true : Eval condition of this event sheet every round. Default behavior.
    • false : Skip this event sheet.
  • once :
    • true : Set active of this event sheet to false when exection of this event sheet is complete.
    • false : Do nothing when exection of this event sheet is complete. Default behavior.
  • groupName : Each event sheet belong a group. Ignore this parameter to use default group.
    • '_' : Default group name.
"},{"location":"markedeventsheet/#remove-event-sheet","title":"Remove event sheet","text":"
  • Remove an event sheet in default group
    eventSheetManager.removeEventSheet(title);\n
  • Remove an event sheet in a specific group
    eventSheetManager.removeEventSheet(title, groupName);\n
  • Remove all event sheets in default group
    eventSheetManager.removeAllEventSheets();\n
  • Remove all event sheets in a specific group
    eventSheetManager.removeAllEventSheets(groupName);\n
"},{"location":"markedeventsheet/#start-running","title":"Start running","text":"

Starting command will be ignored if group is running.

"},{"location":"markedeventsheet/#start-running-a-group-of-event-sheets","title":"Start running a group of event sheets","text":"
  • Start running default group
    eventSheetManager.startGroup();\n
  • Start running a specific group of event sheets
    eventSheetManager.startGroup(groupName);\n
"},{"location":"markedeventsheet/#flow-chart","title":"Flow chart","text":"
graph TD\n\n    startGroup{{\"startGroup()\"}}  ------>  eventstart>Fire event\\nstart]\n    eventstart --> foreacheventsheet((For each\\nevent sheet))\n    foreacheventsheet --> |Next| activate{activate}\n\n    subgraph Event sheet\n    activate --> |True| condition{\"Test\\n[condition]\"}\n    condition --> |True| enterevent>Fire event\\neventsheet.enter]\n    condition --> |False| eventcatch>Fire event\\neventsheet.catch] \n\n    subgraph Run\n    enterevent --> actions[Run\\nactions\\n...\\n...]\n    actions --> exitevent>Fire event\\neventsheet.exit]    \n    end\n\n    subgraph Catch\n    eventcatch --> catch[\"Run\\n[catch]\"]\n    end\n\n    end\n\n    exitevent --> foreacheventsheet\n    catch --> foreacheventsheet\n\n    activate --> |False| foreacheventsheet\n\n    foreacheventsheet --> eventcomplete>Fire event\\ncomplete]\n    eventcomplete --> endnode{{End}}
"},{"location":"markedeventsheet/#start-running-a-event-sheet-in-a-group","title":"Start running a event sheet in a group","text":"
  • Start running default group
    eventSheetManager.start();\n
  • Start running an event sheet (indexed by title) without condition testing, in default group.
    eventSheetManager.start(title);\n
  • Start running an event sheet (indexed by title) without condition testing, in a specific group.
    eventSheetManager.start(title, groupName);\n
  • Start running an event sheet (indexed by title) with condition testing, in default group.
    eventSheetManager.start(title, false);\n
  • Start running an event sheet (indexed by title) with condition testing, in a specific group.
    eventSheetManager.start(title, groupName, false);\n
"},{"location":"markedeventsheet/#start-running-a-group-by-event","title":"Start running a group by event","text":"
eventSheetManager.startGroup(eventName, groupName);\n// eventSheetManager.startGroup(eventName, groupName, once);\n

or

eventSheetManager.startGroup({\neventName:\ngroupName:\nonce: false\n});\n
"},{"location":"markedeventsheet/#round-counter","title":"Round counter","text":"

Round counter is started from 0.

  • Increase round counter
    eventSheetManager.updateRoundCounter();\n// eventSheetManager.$roundCounter += 1;\n
  • Set round counter
    eventSheetManager.updateRoundCounter(value);\n// eventSheetManager.$roundCounter = value;\n
  • Get round counter
    var roundCounter = eventSheetManager.getRoundCounter();\n// var roundCounter = eventSheetManager.$roundCounter;\n
"},{"location":"markedeventsheet/#active","title":"Active","text":"
  • Activate state of event sheet (indexed by title)
    eventSheetManager.setEventSheetActiveState(title);\n// eventSheetManager.setEventSheetActiveState(title, true);\n
  • Inactivate state of event sheet (indexed by title)
    eventSheetManager.setEventSheetActiveState(title, false);\n
  • Get active state of event sheet (indexed by title)
    var active = eventSheetManager.getEventSheetActiveState(title);\n

Note

Event sheet which has once property will set active property to false when exection of this event sheet is complete.

"},{"location":"markedeventsheet/#stop-running","title":"Stop running","text":"

Stop running a group of event sheet, also fires 'eventsheet.exit' event. And game objects with 'autoClear' will be destroyed.

  • Stop running default group
    eventSheetManager.stopGroup();\n
    or
    eventSheetManager.stop();\n
  • Stop running a specific group of event sheets
    eventSheetManager.stopGroup(groupName);\n
    or
    eventSheetManager.stop(groupName);\n
"},{"location":"markedeventsheet/#local-memory","title":"Local memory","text":"

Local memory is shared for all event sheets.

  • Set value
    eventSheetManager.setData(key, value);\n
    or
    eventSheetManager.setData(data);  // data : a plain json object\n
  • Toggle value
    eventSheetManager.toggleData(key, value);\n
  • Increase value
    eventSheetManager.incData(key, inc);\n
  • Get value
    var value = eventSheetManager.getData(key);\n
  • Has key
    var hasData = eventSheetManager.hasData(key);\n
  • Local memory as a dictionary
    var data = eventSheetManager.memory;\n
"},{"location":"markedeventsheet/#custom-expression","title":"Custom expression","text":"
eventSheetManager.addExpression(name, callback);\n
  • name : A string value
  • callback : A function object retuen a number
    function(a, b, c, ...) { return x; }\n

For example :

eventSheetManager.addExpression('randomInt', function (a, b) {\nreturn Math.floor(a + Math.random() * (b - a + 1));\n});\n

Expression will store at local memory

"},{"location":"markedeventsheet/#states","title":"States","text":"
  • Dump state of event sheets of all groups
    var states = eventSheetManager.dumpState();\n
  • Load state of event sheet of all groups
    eventSheetManager.loadState(states);\n
"},{"location":"markedeventsheet/#events","title":"Events","text":"
  • Start A group of event sheets
    eventSheetManager.on('start', function(groupName, eventSheetManager){ });\n
  • A group of event sheets has been executed completed
    eventSheetManager.on('complete', function(groupName, eventSheetManager){ });\n
  • Enter an event sheet
    eventSheetManager.on('eventsheet.enter', function(title, groupName, eventSheetManager){ });\n
  • Exit an event sheet
    eventSheetManager.on('eventsheet.exit', function(title, groupName, eventSheetManager){ });\n
  • Enter a label (any heading) an event sheet
    eventSheetManager.on('label.enter', function(headingTitle, eventSheetTitle, groupName, eventSheetManager){ });\n
  • Exit a label (any heading) of an event sheet
    eventSheetManager.on('label.exit', function(headingTitle, eventSheetTitle, groupName, eventSheetManager){ });\n
  • Test condition of an event sheet failed
    eventSheetManager.on('eventsheet.catch', function(title, groupName, eventSheetManager){ });\n
"},{"location":"markedeventsheet/#structure-of-event-sheet","title":"Structure of event sheet","text":"

Sample

"},{"location":"markedeventsheet/#main-headings","title":"Main headings","text":"
# Title\n\ngroupName\nparallel\nactive=false\nonce\n\n## [Condition]\n\ncoin > 5\n\n## Script\n\n## [Catch]\n
  • H1 heading : Title of this event sheet
  • Content under Title (H1 heading) : Setting of this event sheet, optional.
    • groupName : Assign groupName in event sheet, put this event sheet in to that group.
    • parallel : Set parallel property of this event sheet to true.
    • active=false : Set active property of this event sheet to false.
    • once : Set once property of this event sheet to true.
  • H2 heading with [Condition] : Main condition.
    • Each line under [Condition] is a boolean equation, composed of AND logic.
    • Can have many [Condition] heading, each [Condition] heading will be composed of OR logic.
    • Read data from local memory
  • H2/H3/... headings between [Condition] and [Catch] : Actions when main condition is true.
    • Flow control instructions of headings
    • Actions : Custom command
  • H2 heading with [Catch] : Actions when main condition is false.
"},{"location":"markedeventsheet/#flow-control-instructions","title":"Flow control instructions","text":""},{"location":"markedeventsheet/#if-else-if-else","title":"If, Else if, Else","text":"
### [If coin > 10]\n\nactions...\n\n### [Else If (coin > 5) && (coin <10)]\n\nactions...\n\n### [Else]\n\nactions...\n
  • H2/H3/... heading with [If expression], or [Else if expression] : If/Else If condition with expression
    • Read data from local memory
    • Boolean expression AND/OR : &&.
    • Boolean expression OR : ||.
    • Actions when expression is true.
  • H2/H3/... heading with [Else] :
    • Actions when previous expressions are all false.
## [If]\n\ncoin > 10\n\n### Label\n\nactions...\n\n## [Else If]\n\ncoin > 5\ncoin < 10\n\n### Label\n\nactions...\n\n## [Else]\n\n### Label\n\nactions...\n
  • H2/H3/... heading with [If], or [Else if] : If, Else If condition
    • Each line under [If], [Else If] is a boolean equation, composed of AND logic.
    • Read data from local memory
  • H3/H4/... heading under [If], [Else if] : - Actions when previous expressions are all false.
"},{"location":"markedeventsheet/#repeat-loop","title":"Repeat loop","text":"
## [Repeat 3]\n\nactions...\n

or

## [Repeat loopCount]\n\nactions...\n

or

## [Repeat 3]\n\n### Label\n\nactions...\n
  • H2/H3/... heading with [Repeat N], or [Repeat var] : Repeat loop N times
"},{"location":"markedeventsheet/#while-loop","title":"While loop","text":"
## [While loopCount > 0]\n\nactions...\n
  • H2/H3/... heading with [While expression] : While loop with expression
    • Read data from local memory
    • Actions when expression is true.
## [While]\n\nloopCount > 0\n\n### Label\n\nactions...\n
  • H2/H3/... heading with [While] : While loop
    • Each line under [While] is a boolean equation, composed of AND logic.
    • Read data from local memory
  • H3/H4/... heading under [While] : Actions running when condition is true
"},{"location":"markedeventsheet/#break","title":"Break","text":"
[break]\n
  • Action line with [break] : Ignore remainder actions in current label (heading).
"},{"location":"markedeventsheet/#exit","title":"Exit","text":"
[exit]\n
  • Action line with [exit] : Skip remainder label (heading) and actions.
"},{"location":"markedeventsheet/#deactivate","title":"Deactivate","text":"
[deactivate]\n

or

[deactivate title]\n
  • Action line with [deactivate], or [deactivate title] : Deactivate this event sheet, or deactivate event sheet by title in the same tree group. i.e. Set active property of this event shhet to false.
"},{"location":"markedeventsheet/#activate","title":"Activate","text":"
[activate]\n

or

[activate title]\n
  • Action line with [activate], or [activate title] : Activate this event sheet, or activate event sheet by title in the same tree group. i.e. Set active property of this event shhet to true.
"},{"location":"markedeventsheet/#custom-command","title":"Custom command","text":"
commandName\n  param0=value\n  param1=value\n
  • Each command is divided by space line. i.e. add space lines above and below command.
  • First line is the command name.
    1. Invoke commandExecutor.commandName method if this commandName method is existed.
      commandName(config, eventSheetManager) {\n// var resumeCallback = eventSheetManager.pauseEventSheet();\n// ... \n// resumeCallback()\n}\n
      • config : Parameter and value in a dictionary.
      • eventSheetManager : This event mangager.
        • Pause running of current event sheet
          var resumeCallback = eventSheetManager.pauseEventSheet();  //  resumeCallback();  // Resume running of current event sheet      \n
        • Pause running of current event sheet until another eventName firing from eventEmitter
          eventSheetManager.pauseEventSheetUnitlEvent(eventEmitter, eventName);\n
    2. Otherwise, invoke commandExecutor.defaultHandler.
      defaultHandler(commandName, config, eventSheetManager) {\n// var resumeCallback = eventSheetManager.pauseEventSheet();\n// ... \n// resumeCallback()\n}\n
      • commandName : Command name.
      • config : Parameter and value in a dictionary.
      • eventSheetManager : This event mangager.
        • Pause running of current event sheet
          var resumeCallback = eventSheetManager.pauseEventSheet(); //  resumeCallback();  // Resume running of current event sheet\n
        • Pause running of current event sheet until another eventName firing from eventEmitter
          eventSheetManager.pauseEventSheetUnitlEvent(eventEmitter, eventName);\n
  • Remainder lines are parameter composed of parameter name and value, with =
    • Space characters at line start will be discarded.
    • Value will be parsed to number, boolean, or string.
      • String value contains {{, and }} will be interpolation by mustache template syntax, return a string value.
      • String value wrapped by #( ) will be treated as expression, return a number value.
  • Any line start with // will be ignored as comment line.

For multiple lines parameter :

```commandName,param0=value,param1=value\nline0\nline1\nline2\n```\n
  • Lines in code block will be assigned to text parameter.

So it will be equal to

commandName\n  text=...\n  param0=value\n  param1=value\n
  • '\\n'
"},{"location":"markedeventsheet/#command-executor","title":"Command executor","text":"

A command executor for phaser3 engine.

"},{"location":"markedeventsheet/#create-command-executor-instance","title":"Create command executor instance","text":"
var commandExecutor = scene.plugins.get('rexMarkedEventSheets').addCommandExecutor(scene, {\n// layers: ['layer0', 'layer1', ...]\n// layers: [{name, cameraName}, ...]\n\n// layerDepth: undefined,\n// rootLayer: undefined,\n\nlog: {\ndelimiters: '[]'\nenable: true\n}\n});\n\n// Add to event sheet manager\n// var eventSheetManager = scene.plugins.get('rexMarkedEventSheets').add({\n//     commandExecutor: commandExecutor\n// });\n

or

// import MarkedEventSheets from 'phaser3-rex-plugins/plugins/markedeventsheets.js';\n// import CommandExecutor from 'phaser3-rex-plugins/plugins/commandexecutor.js';\n\nvar commandExecutor = new CommandExecutor(scene, config);\n\n// var eventSheetManager = new MarkedEventSheets({\n//     commandExecutor: commandExecutor\n// });\n
  • layers : Add some initial layers
    • A string array : Add layers by string name
    • A array of plain object { name, cameraName }
      1. Add layer by string name
      2. Bind this layer to dedicate camera (indexed by cameraName), ignore other cameras Add a new camera if this target camera is not existing
  • layerDepth : Set depth to each layer game object.
    • undefined : Keep default depth value (0)
  • rootLayer : Add all layer game objects created by layer-manager into this root layer.
  • log : Configuration of BBCodeLog
    • log.delimiters : String of left-delimiter and right-delimiter.
      • A single string with 2 characters. Default value is '[]'.
      • A array with 2 strings
    • log.enable :
      • true : Can print message on console. Default behavior.
      • false : Don't print any message on console.
"},{"location":"markedeventsheet/#local-memory-of-event-sheet-manager","title":"Local memory of event sheet manager","text":"
  • Set value by key
    setData\n  key=value\n
  • Increase value of key
    incData\n  key=value\n
    or
    setData\n  key=#(key+value)\n
  • Toggle value of key
    toggleData\n  key\n

See Local memory

"},{"location":"markedeventsheet/#bbcode-log","title":"BBCode Log","text":""},{"location":"markedeventsheet/#print-message-on-console","title":"Print message on console","text":"
log\n  text=...\n

or

log\n  text=...\n  // logType='log'\n  // showTitle=true\n  // title\n  // titleColor='green'\n
  • text : Message with bbcode format.
    • [color=gold]...[/color]
    • [bgcolor=green]...[/bgcolor]
    • [b]...[/b]
    • [i]...[/i]
    • [u]...[/u]
  • logType :
    • 'log' : console.log. Default value.
    • 'warn': console.warn
  • showTitle
    • true : Show title before text message. Default behavior.
    • false : Don't show title.
  • title
    • undefined : Using title of current event sheet. Default behavior.
    • A string, custom string before text message.
  • titleColor : Background color of title block, default value is 'green'
"},{"location":"markedeventsheet/#disable-console-message","title":"Disable console message","text":"
log.disable\n
  • Disable console message of current event sheet.

or

log.disable\n  title=...\n
  • title : Disable console message of event sheet by title.
"},{"location":"markedeventsheet/#enable-console-message","title":"Enable console message","text":"
log.enable\n
  • Enable console message of current event sheet.

or

log.enable\n  title=...\n
  • title : Enable console message of event sheet by title.
"},{"location":"markedeventsheet/#dump-memory","title":"Dump memory","text":"
log.memory\n
  • Dump all key in memory

or

log.memory\n  text=...\n  keys=a,b,c\n
  • keys : Dump part of memory by keys.
  • text : Message with bbcode format.
"},{"location":"markedeventsheet/#game-object","title":"Game object","text":""},{"location":"markedeventsheet/#register-custom-game-object","title":"Register custom game object","text":"
commandExecutor.addGameObjectManager({\nname: GOTYPE,\n\nviewportCoordinate: false,\n// viewportCoordinate: { viewport: new Phaser.Geom.Rectangle() },\n\nfade: 500,\n// fade: {mode: 'tint', time: 500},\n\ndefaultLayer: layerName,\n\nautoClear: true,\n\ncommands: {\ncommandName(gameObject, config, commandExecutor, eventSheetManager, eventSheet) {\n// commandExecutor.waitEvent(eventEmitter, eventName);\n}\n}\n})\n
  • name : A string name of game object's type. Will register command GOTYPE to this command executor.
  • createGameObject : A callback for creating game object
    function(scene, config) {\nreturn gameObject;\n}\n
    • config : Parameters passed from event sheet.
      • id, layer, autoClear, eventSheetManager, eventsheet : These parameters are reserved.
      • eventSheetManager : This event sheet manager.
  • viewportCoordinate : Apply viewportCoordinate behavior to game object.
    • true : Attach vpx, vpy, vp to sprite game object.
      • vpx, vpy : Number between 0~1. Proportion of viewport.
      • vp : Viewport in rectangle
    • false : Do nothing, default behavior.
  • fade :
    • 0 : No fade-in or fade-out when adding or removing a sprite.
    • A number : Duration of fading. Default value is 500.
    • A plain object contains mode, time
      • fade.mode : Fade mode
        • 'tint', or 0 : Fade-in or fade-out via tint property.
        • 'alpha', or 1 : Fade-in or fade-out via alpha property.
        • 'revealUp', or 2 : Reveal up for fade-in.
        • 'revealDown', or 3 : Reveal down for fade-in.
        • 'revealLeft', or 4 : Reveal left for fade-in.
        • 'revealRight', or 5 : Reveal right for fade-in.
      • fade.time : Duration of fading. Default value is 500.
  • defaultLayer : A layer name defined in layers parameter of addCommandExecutor method
  • autoClear :
    • true : Clear game objects when exiting current event sheet. Default behavior.
    • false : Ignore this behavior.
  • commands : Custom commands, each command is a callback indexed by command name
    commandName: function(gameObject, config, commandExecutor, eventSheetManager) {\n// commandExecutor.waitEvent(eventEmitter, eventName);\n}\n
    • commandName : Command name. These command names are reserved : to, yoyo, destroy
    • gameObject : Game object instance.
    • config : Parameters passed from event sheet.
    • commandExecutor : This command executor instance. See also
    • eventSheetManager : This event sheet manager instance.
      • Store variable into blackboard of eventSheetManager : eventSheetManager.setData(key, value)
"},{"location":"markedeventsheet/#create-custom-game-object","title":"Create custom game object","text":"
GOTYPE\n  id=NAME\n  layer=\n  autoClear=\n  param0=value\n  param1=value\n
  • Create custom game object GOTYPE with config {param0, param1}, indexed by id
  • layer : Put this game object at layer.
    • undefined : Put this game object at default layer
  • autoClear : Clear game objects when exiting current event sheet.
    • undefined : Use default value of autoClear

Reserved id : time, click, key, bgm, bgm2, se, se2, camera.

Will store reference of this game object into memory at key @NAME, can see it by log.memory, or get property of game object via #(@NAME.x + 3).

"},{"location":"markedeventsheet/#set-properties-of-custom-game-object","title":"Set properties of custom game object","text":"
  • Set properties of a game object indexing by NAME
    NAME.set\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n
    • vpx, vpy : viewportCoordinate properties injected if viewportCoordinate is true.
    • Add empty line above and below this command block.
  • Set properties of all game objects belong GOTYPE
    GOTYPE.set\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n
  • Set properties of all game objects belong GOTYPE excluding NAME
    !NAME.set\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n
"},{"location":"markedeventsheet/#ease-properties-of-custom-game-object","title":"Ease properties of custom game object","text":"
  • Ease properties of a game object indexing by NAME
    NAME.to\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    NAME.from\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    NAME.yoyo\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    • These properties are reserved : id, duration, delay, ease, repeat, yoyo, wait
    • wait :
      • false : Run next command immediately. Default behavior.
      • true : Run next command after playing sound complete.
    • Add empty line above and below this command block.
  • Ease properties of all game objects belong GOTYPE
    GOTYPE.to\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    GOTYPE.from\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    GOTYPE.yoyo\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
  • Ease properties of all game objects belong GOTYPE excluding NAME
    !NAME.to\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    !NAME.from\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
    !NAME.yoyo\n  x=\n  vpx=\n  y=\n  vpy=\n  alpha=\n  duration=1000\n  delay=0\n  ease=Linear\n  repeat=0\n  wait=\n
"},{"location":"markedeventsheet/#invoke-custom-command","title":"Invoke custom command","text":"
  • Invoke custom command of a game object indexing by NAME
    NAME.commandName\n  param0=value\n  param1=value\n
    • Invoke custom command commandName method with these parameters
      • gameObject : Indexed by NAME
      • config : {param0, param1}
    • Add empty line above and below this command block.
    • value :
      • For string value, characters \\n (2 characters) will be replaced by \\n new line character (1 character)
  • Invoke custom command of all game objects belong GOTYPE
    GOTYPE.commandName\n  param0=value\n  param1=value\n
  • Invoke custom command of all game objects belong GOTYPE excluding NAME
    !NAME.commandName\n  param0=value\n  param1=value\n

Do nothing if gameObject or commandName is not found.

"},{"location":"markedeventsheet/#destroy-custom-game-object","title":"Destroy custom game object","text":"
  • Destroy game object indexing by NAME
    NAME.destroy\n
  • Destroy all game objects belong GOTYPE
    GOTYPE.destroy\n
  • Destroy all game objects belong GOTYPE excluding NAME
    !NAME.destroy\n
"},{"location":"markedeventsheet/#methods-used-in-command","title":"Methods used in command","text":"
  • Hold command execution until eventEmitter emits eventName event.
    commandExecutor.waitEvent(eventEmitter, eventName);\n
  • Apply value to property of
    commandExecutor.setGOProperty({\ngoType, id, property, ... });\n
    • goType : GameObject type assigned by commandExecutor.addGameObjectManager({name...}).
    • id : NAME of game object, which will store in gameObject.name.
      • gameObject.name : Apply value to property of this game object.
      • '!' + gameObject.name : Apply value to property of all game objects exclude this game object.
      • undefined : All game objects.
    • propertyName: value : Assign value to property. Can assign one or many properties.
  • Ease value of game object(s)' property
    if (wait) {\ncommandExecutor.setWaitEventFlag();\n}\ncommandExecutor.easeGOProperty({\ngoType, id, duration, ease, repeat, yoyo, wait, property, ... });\n
    • goType : GameObject type assigned by commandExecutor.addGameObjectManager({name...}).
    • id : NAME of game object, which will store in gameObject.name.
      • gameObject.name : Apply value to property of this game object.
      • '!' + gameObject.name : Apply value to property of all game objects exclude this game object.
      • undefined : All game objects.
    • duration : Duration of easing task.
    • ease : Ease function
    • repeat : Repeat times.
    • yoyo : Yoyo flag.
    • wait : Wait until easing task complete.
      • Invoke commandExecutor.setWaitEventFlag().
    • propertyName: value : Ease value of property. Can assign one or many properties.
"},{"location":"markedeventsheet/#wait","title":"Wait","text":""},{"location":"markedeventsheet/#wait-click","title":"Wait click","text":"
click\n
  • Run next command after clicking.
"},{"location":"markedeventsheet/#wait-any","title":"Wait any","text":"

Run next command after...

wait\n  click\n  key=keyName\n  time=\n  GONAME.destroy\n  GONAME.PROPNAME\n  GONAME.DATAKEY\n  GONAME.EVTNAME\n  event=EVENTNAME\n
  • click : Run next command after clicking.
  • key : Run next command after key down
  • time : Run next command after time-out.
  • GONAME.destroy : Run next command after game object has destroyed.
  • GONAME.PROPNAME (ex. GONAME.x) : Run next command after game object's property tween complete
  • GONAME.DATAKEY, GONAME.!DATAKEY (ex. GONAME.!hp) : Run next command after game object's data is true (or > 0) or false (or <= 0). Will check PROPNAME first.
  • GONAME.EVTNAME : Run next command after game object's EVTNAME firing. Will check PROPNAME and DATAKEY first.
  • event : Run next command after eventSheetManager firing EVENTNAME event.

Emit these events from eventSheetManager

  • Wait click or key down
    eventSheetManager.on('pause.input', function(){ });\n
    • Resume (run next command)
      eventSheetManager.on('resume.input', function(){ });\n
  • Wait click only
    eventSheetManager.on('pause.click', function(){ });\n
  • Wait key down only
    eventSheetManager.on('pause.key', function(keyName){ });\n
"},{"location":"markedeventsheet/#sound","title":"Sound","text":"

This command executor provides

  • 2 background music tracks : bgm, bgm2
  • 2 sound effects : se, se2.
"},{"location":"markedeventsheet/#sound-properties","title":"Sound properties","text":"
bgm.set\n  volume\n  mute\n  unmute\n
  • Command name : bgm, bgm2, se, se2
"},{"location":"markedeventsheet/#play-sound","title":"Play sound","text":"
bgm.play\n  key=\n  // volume\n  // detune\n  // rate\n  fadeIn=0\n  // loop\n  wait=false\n
  • Command name : bgm.play, bgm2.play, se.play, se2.play
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after playing sound complete.
"},{"location":"markedeventsheet/#cross-fade-in-sound","title":"Cross fade in sound","text":"
bgm.cross\n  key=\n  duration=500\n  wait=false\n
  • Command name : bgm.cross, bgm2.cross
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after playing sound complete.
"},{"location":"markedeventsheet/#stop-sound","title":"Stop sound","text":"
bgm.stop\n
  • Command name : bgm.stop, bgm2.stop, se.stop, se2.stop
"},{"location":"markedeventsheet/#fade-out-sound","title":"Fade out sound","text":"
bgm.fadeOut\n  duration=500\n  stop=true\n  wait=false\n
  • Command name : bgm.fadeOut, bgm2.fadeOut, se.fadeOut, se2.fadeOut
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after playing sound complete.
"},{"location":"markedeventsheet/#fade-in-sound","title":"Fade in sound","text":"
bgm.fadeIn\n  duration=500\n
  • Command name : bgm.fadeIn, bgm2.fadeIn
"},{"location":"markedeventsheet/#pause-sound","title":"Pause sound","text":"
bgm.pause\n
  • Command name : bgm.pause, bgm2.pause
"},{"location":"markedeventsheet/#resume-sound","title":"Resume sound","text":"
bgm.resume\n
  • Command name : bgm.resume, bgm2.resume
"},{"location":"markedeventsheet/#mute-sound","title":"Mute sound","text":"
bgm.mute\n
  • Command name : bgm.mute, bgm2.mute, se.mute, se2.mute
"},{"location":"markedeventsheet/#unmute-sound","title":"Unmute sound","text":"
bgm.unmute\n
  • Command name : bgm.unmute, bgm2.unmute, se.unmute, se2.unmute
"},{"location":"markedeventsheet/#camera","title":"Camera","text":""},{"location":"markedeventsheet/#camera-properties","title":"Camera properties","text":"
camera.set\n  x=\n  y=\n  rotate=\n  zoom=\n  name\n
  • x, y : Scroll
  • rotate : Rotate in degree
  • zoom : Zoom
  • name : Target camera indexed by name. Default is main camera.

Run next command immediately.

"},{"location":"markedeventsheet/#fade-in","title":"Fade in","text":"
camera.fadeIn\n  duration=1000\n  red\n  green\n  blue\n  name\n  wait=false\n
  • duration, red, green, blue : See fade effect
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#fade-out","title":"Fade out","text":"
camera.fadeOut\n  duration=1000\n  red\n  green\n  blue\n  name\n  wait=false\n
  • duration, red, green, blue : See fade effect
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#flash","title":"Flash","text":"
camera.flash\n  duration=1000\n  red\n  green\n  blue\n  name\n  wait=false\n
  • duration, red, green, blue : See flash effect
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#shake","title":"Shake","text":"
camera.shake\n  duration=1000\n  intensity\n  name\n  wait=false\n
  • duration, intensity : See shake effect
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#zoom","title":"Zoom","text":"
camera.zoomTo\n  duration=1000\n  zoom\n  name\n  wait=false\n
  • duration, zoom : See zoom effect
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#rotate-to","title":"Rotate to","text":"
camera.rotateTo\n  duration=1000\n  rotate\n  ease\n  name\n  wait=false\n
  • duration, rotate, ease : See rotateTo effect
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#scroll-to","title":"Scroll to","text":"
camera.scrollTo\n  duration=1000\n  x\n  y\n  ease\n  name\n  wait=false\n
  • duration, x, y, ease : Scroll to position.
  • name : Target camera indexed by name. Default is main camera.
  • wait :
    • false : Run next command immediately. Default behavior.
    • true : Run next command after effect complete.
"},{"location":"markedeventsheet/#add-custom-command","title":"Add custom command","text":"
commandExecutor.addCommand(commandName, function(config, eventSheetManager){\n// var resumeCallback = eventSheetManager.pauseEventSheet();\n// ... \n// resumeCallback()\n}, scope);\n
  • config : Parameters passed from event sheet.
  • eventSheetManager : This event mangager.
    • Pause running of current event sheet
      var resumeCallback = eventSheetManager.pauseEventSheet();\n//  resumeCallback();  // Resume running of current event sheet\n
    • Pause running of current event sheet until another eventName firing from eventEmitter
      eventSheetManager.pauseEventSheetUnitlEvent(eventEmitter, eventName);\n
"},{"location":"mask/","title":"Mask","text":""},{"location":"mask/#introduction","title":"Introduction","text":"

Apply mask on game object. Built-in render of phaser.

  • Author: Richard Davey
"},{"location":"mask/#usage","title":"Usage","text":""},{"location":"mask/#add-mask","title":"Add mask","text":""},{"location":"mask/#create-mask-object","title":"Create mask object","text":""},{"location":"mask/#bitmap-mask","title":"Bitmap mask","text":"
  1. Create image (image, sprite, bitmap text, particles, text),or shader
    var shape = scene.add.image(x, y, key).setVisible(false);\n
  2. Create mask
    var mask = shape.createBitmapMask();\n
    or
    var mask = scene.add.bitmapMask(shape);\n

or

var mask =  scene.add.bitmapMask(undefined, x, y, key, frame);\n
"},{"location":"mask/#geometry-mask","title":"Geometry mask","text":"

The mask is essentially a clipping path which can only make a masked pixel fully visible or fully invisible without changing its alpha (opacity).

  1. Create graphics
    var shape = scene.make.graphics();\n
  2. Create mask
    var mask = shape.createGeometryMask();\n
"},{"location":"mask/#apply-mask-object","title":"Apply mask object","text":"
gameObject.setMask(mask); // image.mask = mask;\n

A mask object could be added to many game objects.

Error

Don't put game object and its mask into a container together. See this testing, enable line 22-24.

Note

Bitmap Mask is WebGL only.

Note

Can combine Geometry Masks and Blend Modes on the same Game Object, but Bitmap Masks can't.

"},{"location":"mask/#clear-mask","title":"Clear mask","text":"
  • Clear mask
    image.clearMask();\n
  • Clear mask and destroy mask object
    image.clearMask(true);\n
"},{"location":"mask/#invert-alpha","title":"Invert alpha","text":"

Only GeometryMask has inverse alpha feature.

  • Inverse alpha
    mask.setInvertAlpha();\n// mask.invertAlpha = true;\n
  • Disable
    mask.setInvertAlpha(false);\n// mask.invertAlpha = false;\n
"},{"location":"mask/#get-shape-game-object","title":"Get shape game object","text":"
  • Bitmap mask
    var shape = mask.bitmapMask;\n
  • Geometry mask
    var shape = mask.geometryMask;\n
"},{"location":"matterjs-attractor/","title":"Attractor","text":""},{"location":"matterjs-attractor/#introduction","title":"Introduction","text":"

Apply continual forces on bodies.

  • Reference
"},{"location":"matterjs-attractor/#usage","title":"Usage","text":""},{"location":"matterjs-attractor/#system-configuration","title":"System configuration","text":"
  • Game config
    var config = {\n// ...\nphysics: {\nmatter: {\n// ...\nplugins: {\nattractors: true,\n// ...\n}\n// ...\n}\n}\n// ...\n}\nvar game = new Phaser.Game(config);\n
  • Runtime
    scene.matter.system.enableAttractorPlugin();\n
"},{"location":"matterjs-attractor/#matter-object-configuration","title":"Matter object configuration","text":"
var options = {\n// ...\nplugin: {\nattractors: [\ncallback,\n// ...\n]\n},\n// ...\n}\n
  • callback :
    • Retuen a force ({x,y}), which will be applied to bodyB
      function(bodyA, bodyB) {\nreturn {x, y}; // Force\n}\n
      • bodyA : Attractor matter object.
      • bodyB : Other matter object.
    • Apply forece to bodies directly.
      function(bodyA, bodyB) {\nbodyA.gameObject.applyForce({x, y});\nbodyB.gameObject.applyForce({x, y});\n}\n
      • bodyA : Attractor matter object.
        • bodyA.gameObject : Game object.
      • bodyB : Other matter object.
        • bodyB.gameObject : Game object.
"},{"location":"matterjs-gameobject/","title":"Game object","text":""},{"location":"matterjs-gameobject/#introduction","title":"Introduction","text":"

Matterjs physics Image/Sprite/Group object.

  • Author: Richard Davey
"},{"location":"matterjs-gameobject/#usage","title":"Usage","text":""},{"location":"matterjs-gameobject/#add-physics-object","title":"Add physics object","text":"

Enable physics world

"},{"location":"matterjs-gameobject/#image-object","title":"Image object","text":"
var image = scene.matter.add.image(x, y, key, frame);\n// var image = scene.matter.add.image(x, y, key, frame, config);\n
  • config : Config object
"},{"location":"matterjs-gameobject/#sprite-object","title":"Sprite object","text":"
var image = scene.matter.add.sprite(x, y, key, frame);\n// var image = scene.matter.add.sprite(x, y, key, frame, config);\n
  • config : Config object
"},{"location":"matterjs-gameobject/#any-game-object","title":"Any game object","text":"
var gameObject = scene.matter.add.gameObject(gameObject);\n// var gameObject = scene.matter.add.gameObject(gameObject, config);\n
  • config : Config object
"},{"location":"matterjs-gameobject/#image-composite","title":"Image composite","text":"

Create a new composite containing Matter Image objects created in a grid arrangement.

var composite = scene.matter.add.imageStack(key, frame, x, y, columns, rows);\n// var composite = scene.matter.add.imageStack(key, frame, x, y, columns, rows, columnGap, rowGap, options);\n
  • key, frame : Texture key and frame name.
  • x, y : Top-left position of these game objects.
  • columns, rows : The number of columns/rows in the grid.
  • columnGap, rowGap : The distance between each column/row.
  • config : Config object
  • composite : Composite matter object.
    • composite.bodies : An array of bodies.
"},{"location":"matterjs-gameobject/#config","title":"Config","text":"
{\nlabel: 'Body',\nshape: 'rectangle',\nchamfer: null,\n\nisStatic: false,\nisSensor: false,\nisSleeping: false,\nignoreGravity: false,\nignorePointer: false,\n\nsleepThreshold: 60,\ndensity: 0.001,\nrestitution: 0,\nfriction: 0.1,\nfrictionStatic: 0.5,\nfrictionAir: 0.01,\n\nforce: { x: 0, y: 0 },\nangle: 0,\ntorque: 0,\n\ncollisionFilter: {\ngroup: 0,\ncategory: 0x0001,\nmask: 0xFFFFFFFF,\n},\n\n// parts: [],\n\n// plugin: {\n//     attractors: [\n//         (function(bodyA, bodyB) { return {x, y}}),\n//     ]\n// },\n\nslop: 0.05,\n\ntimeScale: 1,\n}\n
  • label : An arbitrary String name to help the user identify and manage bodies.
  • shape :
    • A string : 'rectangle', 'circle', 'trapezoid', 'polygon', 'fromVertices', 'fromPhysicsEditor'
    • An object :
      • Rectangle shape
        {\ntype: 'rectangle',\n// width: gameObject.width\n// height: gameObject.height\n}\n
      • Circle shape
        {\ntype: 'circle',\n// radius: (Math.max(gameObject.width, gameObject.height) / 2),\n// maxSides: 25\n}\n
      • Trapezoid shape
        {\ntype: 'trapezoid',\n// slope: 0.5,\n}\n
      • Polygon shape
        {\ntype: 'polygon',\n// radius: (Math.max(gameObject.width, gameObject.height) / 2),\n// sides: 5,\n}\n
      • Vertices
        {\ntype: 'fromVertices',\nverts: points,\n// flagInternal: false,\n// removeCollinear: 0.01,\n// minimumArea: 10,\n}\n
        • points :
          • A string : 'x0 y0 x1 y1 ...'
          • An array of points : [{x:x0, y:y0}, {x:x1, y:y1}, ...]
  • chamfer :
    • null
    • A number
    • {radius: value}
    • {radius: [topLeft, topRight, bottomRight, bottomLeft]}
  • isStatic : A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed.
  • isSensor : A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically.
  • isSleeping : A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken.
  • sleepThreshold : The number of updates in which this body must have near-zero velocity before it is set as sleeping.
  • density : Density of the body, that is its mass per unit area.
  • restitution : The restitution/bounce/elasticity of the body. The value is always positive and is in the range (0, 1).
    • 0 : Collisions may be perfectly inelastic and no bouncing may occur.
    • 0.8 : The body may bounce back with approximately 80% of its kinetic energy.
  • friction : Friction of the body. The value is always positive and is in the range (0, 1).
    • 0 : The body may slide indefinitely.
    • 1 : The body may come to a stop almost instantly after a force is applied.
  • frictionStatic : The static friction of the body (in the Coulomb friction model).
    • 0 : The body will never 'stick' when it is nearly stationary and only dynamic friction is used.
    • 10 : The higher the value, the more force it will take to initially get the body moving when nearly stationary.
  • frictionAir : The air friction of the body (air resistance).
    • 0 : The body will never slow as it moves through space.
    • The higher the value, the faster a body slows when moving through space.
  • force : The force to apply in the current step.
  • angle : Angle of the body, in radians.
  • torque : the torque (turning force) to apply in the current step.
  • collisionFilter : An Object that specifies the collision filtering properties of this body.
    • collisionFilter.group
    • collisionFilter.category : A bit field that specifies the collision category this body belongs to.
    • collisionFilter.mask : A bit mask that specifies the collision categories this body may collide with.
  • slop : A tolerance on how far a body is allowed to 'sink' or rotate into other bodies.
    • The default should generally suffice, although very large bodies may require larger values for stable stacking.
"},{"location":"matterjs-gameobject/#collision","title":"Collision","text":"

Collisions between two bodies will obey the following rules:

  • (grpupA > 0) && (groupB > 0) :
    • Collision = (groupA == groupB)
  • (grpupA == 0) || (groupB == 0) :
    • Collision = ((categoryA & maskB) !== 0) && ((categoryB & maskA) !== 0)
"},{"location":"matterjs-gameobject/#movement","title":"Movement","text":""},{"location":"matterjs-gameobject/#velocity","title":"Velocity","text":"
gameObject.setVelocity(x, y);\n
gameObject.setVelocityX(x);\n
gameObject.setVelocityY(x);\n
"},{"location":"matterjs-gameobject/#acceleration","title":"Acceleration","text":""},{"location":"matterjs-gameobject/#force","title":"Force","text":"
  • Applies a force to a body.
    gameObject.applyForce(force);\n
    • force : {x, y}
  • Applies a force to a body from a given position.
    gameObject.applyForceFrom(position, force); // position, force: {x, y}\n
    • position : {x, y}
    • force : {x, y}
  • Apply thrust to the forward position of the body.
    gameObject.thrust(speed);\n
    • speed : A number.
  • Apply thrust to the left position of the body.
    gameObject.thrustLeft(speed);\n
    • speed : A number.
  • Apply thrust to the right position of the body.
    gameObject.thrustRight(speed);\n
    • speed : A number.
  • Apply thrust to the back position of the body.
    gameObject.thrustBack(speed);\n
    • speed : A number.
  • Apply thrust to the back position of the body.
    gameObject.thrustBack(speed);\n
    • speed : A number.
"},{"location":"matterjs-gameobject/#gravity","title":"Gravity","text":"
  • Ignore world gravity
    gameObject.setIgnoreGravity(ignore);\n
    • ignore : Set to true to ignore the effect of world gravity
"},{"location":"matterjs-gameobject/#friction","title":"Friction","text":"
gameObject.setFriction(value, air, fstatic);\n
gameObject.setFrictionAir(v);\n
gameObject.setFrictionStatic(v);\n
"},{"location":"matterjs-gameobject/#rotation","title":"Rotation","text":""},{"location":"matterjs-gameobject/#fixed-rotation","title":"Fixed rotation","text":"
gameObject.setFixedRotation();\n
"},{"location":"matterjs-gameobject/#angular-velocity","title":"Angular velocity","text":"
gameObject.setAngularVelocity(v);\n
"},{"location":"matterjs-gameobject/#collision_1","title":"Collision","text":""},{"location":"matterjs-gameobject/#enable","title":"Enable","text":"
  • Get
    var isSensor = gameObject.isSensor();\n
  • Set
    gameObject.setSensor(value);\n
    • value : Set true to enable sensor.
"},{"location":"matterjs-gameobject/#collision-group","title":"Collision group","text":"
  • Collision grpup
    gameObject.setCollisionGroup(value);\n
  • Collision category
    1. Get new collision category
      var category = scene.matter.world.nextCategory();\n
      • category : An one-shot number (1, 2, 4, 8, ...., 2147483648 (1<<31))
    2. Set collision category of game object
      gameObject.setCollisionCategory(category);\n
    3. Set category mask
      gameObject.setCollidesWith([categoryA, categoryB, ...]);\n// gameObject.setCollidesWith(categoryA);\n
"},{"location":"matterjs-gameobject/#collision-event","title":"Collision event","text":"
scene.matter.world.on('collisionstart', function (event, bodyA, bodyB) {\n// var pairs = event.pairs;\n});\n
  • event :
    • event.pairs : An array of collision pairs
      • event.pairs[i].bodyA, event.pairs[i].bodyB : Matter body object.
        • body.gameObject : Game object of matter body.
  • bodyA, bodyB : Equal to event.pairs[0].bodyA, event.pairs[0].bodyB.
"},{"location":"matterjs-gameobject/#collision-bound","title":"Collision bound","text":"
  • Rectangle
    gameObject.setRectangle(width, height, options);\n
  • Circle
    gameObject.setCircle(radius, options);\n
  • Polygon
    gameObject.setPolygon(radius, sides, options);\n
  • Trapezoid
    gameObject.setTrapezoid(width, height, slope, options);\n
  • Any
    gameObject.setBody(config, options);\n
    • config :
      • Rectangle shape
        {\ntype: 'rectangle',\n// width: gameObject.width\n// height: gameObject.height\n}\n
      • Circle shape
        {\ntype: 'circle',\n// radius: (Math.max(gameObject.width, gameObject.height) / 2),\n// maxSides: 25\n}\n
      • Trapezoid shape
        {\ntype: 'trapezoid',\n// slope: 0.5,\n}\n
      • Polygon shape
        {\ntype: 'polygon',\n// radius: (Math.max(gameObject.width, gameObject.height) / 2),\n// sides: 5,\n}\n
"},{"location":"matterjs-gameobject/#bounce","title":"Bounce","text":"
gameObject.setBounce(v);\n
  • restitution
"},{"location":"matterjs-gameobject/#mass","title":"Mass","text":"
gameObject.setMass(v);\n
gameObject.setDensity(v);\n
"},{"location":"matterjs-gameobject/#sleep","title":"Sleep","text":""},{"location":"matterjs-gameobject/#enable_1","title":"Enable","text":"
var config = {\n// ...\nphysics: {\nmatter: {\n// ...\nenableSleeping: true\n// ...\n}\n}\n\n}\n
"},{"location":"matterjs-gameobject/#sleep-threshold","title":"Sleep threshold","text":"
gameObject.setSleepThreshold(value);\n
"},{"location":"matterjs-gameobject/#sleep-events","title":"Sleep events","text":"
  • Sleeping start
    scene.matter.world.on('sleepstart', function (event, body) {\n});\n
  • Sleeping end
    scene.matter.world.on('sleepend', function (event, body) {\n});\n
"},{"location":"matterjs-world/","title":"World","text":""},{"location":"matterjs-world/#introduction","title":"Introduction","text":"

Matter physics engine in phaser.

  • Author: Richard Davey
"},{"location":"matterjs-world/#usage","title":"Usage","text":""},{"location":"matterjs-world/#configuration","title":"Configuration","text":"
var config = {\n// ...\nphysics: {\ndefault: 'matter',\nmatter: {\n//    enabled: true,\n//    positionIterations: 6,\n//    velocityIterations: 4,\n//    constraintIterations: 2,\n//    enableSleeping: false,\n//    plugins: {\n//        attractors: false,\n//        wrap: false,\n//    },\n//    gravity: {\n//        x: 0,\n//        y: 0,\n//    }\n//    setBounds: {\n//        x: 0,\n//        y: 0,\n//        width: scene.sys.scale.width,\n//        height: scene.sys.scale.height,\n//        thickness: 64,\n//        left: true,\n//        right: true,\n//        top: true,\n//        bottom: true,\n//    },\n//    timing: {\n//        timestamp: 0,\n//        timeScale: 1,\n//    },\n//    correction: 1,\n//    getDelta: (function() { return 1000 / 60; }),\n//    autoUpdate: true,\n//    debug: false,\n//    debug: {\n//        showAxes: false,\n//        showAngleIndicator: false,\n//        angleColor: 0xe81153,\n//        showBroadphase: false,\n//        broadphaseColor: 0xffb400,\n//        showBounds: false,\n//        boundsColor: 0xffffff,\n//        showVelocity: false,\n//        velocityColor: 0x00aeef,\n//        showCollisions: false,\n//        collisionColor: 0xf5950c,\n//        showSeparations: false,\n//        separationColor: 0xffa500,\n//        showBody: true,\n//        showStaticBody: true,\n//        showInternalEdges: false,\n//        renderFill: false,\n//        renderLine: true,\n//        fillColor: 0x106909,\n//        fillOpacity: 1,\n//        lineColor: 0x28de19,\n//        lineOpacity: 1,\n//        lineThickness: 1,\n//        staticFillColor: 0x0d177b,\n//        staticLineColor: 0x1327e4,\n//        showSleeping: false,\n//        staticBodySleepOpacity: 0.7,\n//        sleepFillColor: 0x464646,\n//        sleepLineColor: 0x999a99,\n//        showSensors: true,\n//        sensorFillColor: 0x0d177b,\n//        sensorLineColor: 0x1327e4,\n//        showPositions: true,\n//        positionSize: 4,\n//        positionColor: 0xe042da,\n//        showJoint: true,\n//        jointColor: 0xe0e042,\n//        jointLineOpacity: 1,\n//        jointLineThickness: 2,\n//        pinSize: 4,\n//        pinColor: 0x42e0e0,\n//        springColor: 0xe042e0,\n//        anchorColor: 0xefefef,\n//        anchorSize: 4,\n//        showConvexHulls: false,\n//        hullColor: 0xd703d0\n//    }\n}\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"matterjs-world/#control","title":"Control","text":""},{"location":"matterjs-world/#pause","title":"Pause","text":"
scene.matter.world.pause();\n
"},{"location":"matterjs-world/#resume","title":"Resume","text":"
scene.matter.world.resume();\n
"},{"location":"matterjs-world/#drag-object","title":"Drag object","text":"
scene.matter.add.mouseSpring();\n// scene.matter.add.mouseSpring(options);\n
  • options
    {\nlength: 0.01,\nstiffness: 0.1,\ndamping: 0,\nangularStiffness: 1,\ncollisionFilter: {\ncategory: 0x0001,\nmask: 0xFFFFFFFF,\ngroup: 0\n}\n}\n
    • collisionFilter : Drag filter, see collision.
"},{"location":"matterjs-world/#world-bounds","title":"World bounds","text":""},{"location":"matterjs-world/#enable","title":"Enable","text":"
  • World :
    • Set bounds
      scene.matter.world.setBounds(x, y, width, height);\n// scene.matter.world.setBounds(x, y, width, height, thickness, left, right, top, bottom);\n
      • thickness : The thickness of each wall, in pixels.
      • left, right, top, bottom : If true will create the left/right/top/bottom bounds wall.
"},{"location":"matterjs-world/#gravity","title":"Gravity","text":"
  • Set
    scene.matter.world.setGravity(x, y);\n// scene.matter.world.setGravity(x, y, scale);\n
  • Disable
    scene.matter.world.disableGravity();\n
"},{"location":"matterjs-world/#constraint","title":"Constraint","text":""},{"location":"matterjs-world/#constraint-of-2-game-objects","title":"Constraint of 2 game objects","text":"
var constraint = scene.matter.add.constraint(gameObjectA, gameObjectB);\n// var constraint = scene.matter.add.constraint(gameObjectA, gameObjectB, length, stiffness, options);\n
  • gameObjectA, gameObjectB : Matter game object, or matter body object.
  • length : The target resting length of the constraint.
    • undefined : Current distance between gameObjectA and gameObjectB. (Default value)
  • stiffness : The stiffness of the constraint.
    • 1 : Very stiff. (Default value)
    • 0.2 : Acts as a soft spring.
  • options :
    {\npointA: {\nx: 0,\ny: 0,\n},\npointB: {\nx: 0,\ny: 0,\n},\ndamping: 0,\nangularStiffness: 0,\n// render: {\n//     visible: true\n// }\n}\n
    • pointA, pointB : Offset position of gameObjectA, gameObjectB.

Alias:

var constraint = scene.matter.add.spring(gameObjectA, gameObjectB, length, stiffness, options);\nvar constraint = scene.matter.add.joint(gameObjectA, gameObjectB, length, stiffness, options);\n
"},{"location":"matterjs-world/#constraint-to-world-position","title":"Constraint to world position","text":"
var constraint = scene.matter.add.worldConstraint(gameObjectB, length, stiffness, options);\n
  • gameObjectB : Matter game object, or matter body object.
  • length : The target resting length of the constraint.
    • undefined : Current distance between gameObjectA and gameObjectB. (Default value)
  • stiffness : The stiffness of the constraint.
    • 1 : Very stiff. (Default value)
    • 0.2 : Acts as a soft spring.
  • options :
    {\npointA: {\nx: 0,\ny: 0,\n},\npointB: {\nx: 0,\ny: 0,\n},\ndamping: 0,\nangularStiffness: 0,\n// render: {\n//     visible: true\n// }\n}\n
    • pointA : World position.
    • pointB : Offset position of gameObjectB.
"},{"location":"matterjs-world/#chain-game-objects","title":"Chain game objects","text":"
var composite = scene.matter.add.chain(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options);\n
  • composite : Image composite
  • xOffsetA, yOffsetA : Offset position of gameObjectA, in scale.
    • xOffset = (Offset distance / width)
    • yOffset = (Offset distance / height)
  • xOffsetB, yOffsetB : Offset position of gameObjectB, in scale.
  • options :
    {\nlength: undefined,\nstiffness: 1,\ndamping: 0,\nangularStiffness: 0,\n// render: {\n//     visible: true\n// }\n}\n
    • length : The target resting length of the constraint.
      • undefined : Current distance between gameObjectA and gameObjectB. (Default value)
    • stiffness : The stiffness of the constraint.
      • 1 : Very stiff. (Default value)
      • 0.2 : Acts as a soft spring.
  • composite
    • composite.bodies : An array of bodies.
    • composite.constraints : An array of constraints
"},{"location":"matterjs-world/#remove-constraint","title":"Remove constraint","text":"
scene.matter.world.removeConstraint(constraint);\n
"},{"location":"matterjs-wrap/","title":"Wrap","text":""},{"location":"matterjs-wrap/#introduction","title":"Introduction","text":"

Automatically wrap the position of bodies and composites such that they always stay within the given bounds.

  • Reference
"},{"location":"matterjs-wrap/#usage","title":"Usage","text":""},{"location":"matterjs-wrap/#system-configuration","title":"System configuration","text":"
  • Game config
    var config = {\n// ...\nphysics: {\nmatter: {\n// ...\nplugins: {\nwrap: true,\n// ...\n}\n// ...\n}\n}\n// ...\n}\nvar game = new Phaser.Game(config);\n
  • Runtime
    scene.matter.system.enableWrapPlugin();\n
"},{"location":"matterjs-wrap/#matter-object-configuration","title":"Matter object configuration","text":"
var options = {\n// ...\nplugin: {\nwrap: {\nmin: {\nx: 0,\ny: 0\n},\nmax: {\nx: 1024,\ny: 1024\n}\n}\n},\n// ...\n}\n
"},{"location":"mesh/","title":"Mesh","text":""},{"location":"mesh/#introduction","title":"Introduction","text":"

Render a group of textured vertices and manipulate the view of those vertices, such as rotation, translation or scaling.

  • Author: Richard Davey

WebGL only

It only works in WebGL render mode.

"},{"location":"mesh/#usage","title":"Usage","text":""},{"location":"mesh/#quad","title":"Quad","text":"

Note

See also Plane

  1. Load texture
    scene.load.image(key, url);\n
  2. Add mesh object
    var mesh = scene.add.mesh(x, y, texture, frame);\n
    or
    var mesh = scene.make.mesh({\nx: 0,\ny: 0,\nadd: true,\n\nkey: null,\nframe: null\n});\n
  3. Set perspective or orthographic projection
    • Perspective projection
      mesh.setPerspective(width, height, fov);\n// mesh.setPerspective(width, height, fov, near, far);\n
      • width, height : The width/height of the projection matrix. Typically the same as the Mesh and/or Renderer.
      • fov : The field of view, in degrees.
      • near, far : The near/far value of the view. Default value are 0.01/1000.
    • Orthographic projection
      mesh.setOrtho(mesh.width/mesh.height, 1);\n// mesh.setOrtho(scaleX, scaleY, near, far);\n
      • scaleX, scaleY : The default horizontal/vertical scale in relation to the Mesh / Renderer dimensions.
      • near, far : The near/far value of the view. Default value are 0.01/1000.
  4. Creates a grid of vertices
    Phaser.Geom.Mesh.GenerateGridVerts({\nmesh: mesh,\ntexture: textureKey,\nframe: frameName,\nwidth: 1,\nheight: 1,\nwidthSegments: 1,\nheightSegments: 1,\n\n// x: 0,\n// y: 0,\n// colors: 0xffffff,\n// alphas: 1,\n// tile: false,\n// isOrtho: false\n})\n
    • mesh : The vertices of the generated grid will be added to this Mesh Game Object.
    • texture : The texture to be used for this Grid.
    • frame : The name or index of the frame within the Texture.
    • width , height : The width/height of the grid in 3D units.
      {\n// ...\nwidth: (frameWidth/frameHeight),\nheight: (frameHeight/frameHeight)\n// ...\n}\n
    • widthSegments, heightSegments : The number of segments to split the grid horizontally/vertically in to.
    • colors : An array of colors, one per vertex, or a single color value applied to all vertices.
    • alphas An array of alpha values, one per vertex, or a single alpha value applied to all vertices.
    • tile :
      • false : Display as a single texture. Default value.
      • true : Texture tile (repeat) across the grid segments.
"},{"location":"mesh/#model","title":"Model","text":"
  1. Load model
    scene.load.obj(key, url, objURL, matURL);\n
    • objURL : URL to load the obj file.
    • matURL : URL to load the material file.
  2. Add mesh object
    var mesh = scene.add.mesh(x, y);\n
    or
    var mesh = scene.make.mesh({\nx: 0,\ny: 0,\nadd: true\n});\n
  3. Add model
    mesh.addVerticesFromObj(key, scale, x, y, z, rotateX, rotateY, rotateZ, zIsUp);\n
    • key : The key of the model data in the OBJ Cache to add to this Mesh.
    • scale : An amount to scale the model data by. Default is 1.
    • x, y, z : Translate the model x/y/z position by this amount.
    • rotateX, rotateY, rotateZ : Rotate the model on the x/y/z axis by this amount, in radians.
    • zIsUp :
      • true : Z axis is up.
      • false : Y axis is up.
"},{"location":"mesh/#custom-mesh-class","title":"Custom mesh class","text":"
  • Define class
    class MyMesh extends Phaser.GameObjects.mesh {\nconstructor(scene, x, y, texture, frame, vertices, uvs, indicies, containsZ, normals, colors, alphas) {\nsuper(scene, x, y, texture, frame, vertices, uvs, indicies, containsZ, normals, colors, alphas);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var mesh = new MyMesh(scene, x, y, texture, frame);\n
"},{"location":"mesh/#control","title":"Control","text":""},{"location":"mesh/#view","title":"View","text":"
  • Translates the view position of this Mesh on the x/y/z axis by the given amount.
    mesh.panX(x);\nmesh.panY(y);\nmesh.panZ(z);\n
"},{"location":"mesh/#model_1","title":"Model","text":"
  • Position
    mesh.modelPosition.x = x;\nmesh.modelPosition.y = y;\nmesh.modelPosition.z = z;\n
    • x, y, z : Offset position.
      • z+ : Near
      • z- : Far
      • x- : Left
      • x+ : Right
      • y+ : Up
      • y- : Down
  • Rotation
    mesh.modelRotation.x = radiansX;\nmesh.modelRotation.y = radiansY;\nmesh.modelRotation.z = radiansZ;\n
    or
    mesh.rotateX = degreesX;\nmesh.rotateY = degreesY;\nmesh.rotateZ = degreesZ;\n
    • radiansX, radiansY, radiansZ : Rotation angle in radians.
    • degreesX, degreesY, degreesZ : Rotation angle in degrees.
  • Scale
    mesh.modelScale.x = scaleX;\nmesh.modelScale.y = scaleY;\nmesh.modelScale.z = scaleZ;\n
    • scaleX, scaleY, scaleZ : Scale value, 1 is origin size.
"},{"location":"mesh/#backward-facing-faces","title":"Backward facing Faces","text":"
  • Hide backward facing Faces. Default behavior.
    mesh.hideCCW = true;\n
  • Show backward facing Faces
    mesh.hideCCW = false;\n
"},{"location":"mesh/#faces","title":"Faces","text":"

Mesh is composed of triangle faces.

var faces = mesh.faces;\n
"},{"location":"mesh/#contains","title":"Contains","text":"
  • Has any face which contains point
    var isHit = mesh.hasFaceAt(worldX, worldY);\n// var isHit = mesh.hasFaceAt(worldX, worldY, camera);\n
  • Get face contains point
    var face = mesh.getFaceAt(worldX, worldY);\n// var face = mesh.getFaceAt(worldX, worldY, camera);\n
"},{"location":"mesh/#properties","title":"Properties","text":"
  • Alpha
    • Get
      var alpha = face.alpha;\n
    • Set
      face.alpha = alpha;\n
  • Angle
    • Rotate
      Phaser.Geom.Mesh.RotateFace(face, radians);\n
  • Center position
    • Get
      var x = face.x;\nvar y = face.y;\n
      • x : 0(left) ~ 1(right)
      • y : 1(top) ~ 0(bottom)
    • Set
      face.x = x;\nface.y = y;\n
      or
      face.translate(x, y);\n
      • x : 0(left) ~ 1(right)
      • y : 1(top) ~ 0(bottom)
"},{"location":"mesh/#vertices","title":"Vertices","text":"

Each face has 3 vertices.

var vertices = mesh.vertices;\n
  • vertices : Array of vertex.
"},{"location":"mesh/#properties_1","title":"Properties","text":"
  • Alpha
    • Get
      var alpha = vertex.alpha;\n
    • Set
      vertex.alpha = alpha;\n
  • Tint
    • Get
      var color = vertex.color;\n
    • Set
      vertex.color = color;\n
"},{"location":"mesh/#update-properties","title":"Update properties","text":"
  • Start updating
    mesh.ignoreDirtyCache = true;\n
  • Stop updating
    mesh.ignoreDirtyCache = false;\n
"},{"location":"mesh/#interactive","title":"Interactive","text":"

To test if pointer is at any face of this mesh game object.

mesh.setInteractive();\n
"},{"location":"mesh/#debug","title":"Debug","text":"
  1. Set debug Graphics
    var debugGraphics = scene.add.graphics();\nmesh.setDebug(debugGraphics);\n
  2. Update Graphics in scene.update() method.
    debugGraphics.clear();\ndebugGraphics.lineStyle(1, 0x00ff00);\n
"},{"location":"mesh/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"mesh/#create-mask","title":"Create mask","text":"
var mask = mesh.createBitmapMask();\n

See mask

"},{"location":"mesh/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"modal-promise/","title":"Modal promise","text":""},{"location":"modal-promise/#introduction","title":"Introduction","text":"

Modal behavior wrapped into promise.

  • Author: Rex
  • Promise
"},{"location":"modal-promise/#live-demos","title":"Live demos","text":"
  • Manual
  • Timeout
  • Modal dialog
"},{"location":"modal-promise/#usage","title":"Usage","text":"

Sample code

"},{"location":"modal-promise/#install-plugin","title":"Install plugin","text":""},{"location":"modal-promise/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexmodalplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexmodalplugin.min.js', true);\n
  • Add modal behavior
    scene.plugins.get('rexmodalplugin').promise(gameObject, config)\n.then(function(closeEventData) {\n})\n
"},{"location":"modal-promise/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add modal behavior
    scene.plugins.get('rexModal').promise(gameObject, config)\n.then(function(closeEventData) {\n})\n
"},{"location":"modal-promise/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ModalPromise } from 'phaser3-rex-plugins/plugins/modal.js';\n
  • Add modal behavior
    ModalPromise(gameObject, config)\n.then(function(closeEventData) {\n})\n
"},{"location":"modal-promise/#promise","title":"Promise","text":"
scene.plugins.get('rexModal').promise(gameObject, config)\n.then(function(closeEventData) {\n})\n
  • config : See Modal behavior
"},{"location":"modal-promise/#close","title":"Close","text":"

scene.plugins.get('rexModal').close(gameObject);\n// scene.plugins.get('rexModal').close(gameObject, closeEventData);\n
or
gameObject.emit('modal.requestClose');\n// gameObject.emit('modal.requestClose', closeEventData);\n

  • Fire 'modal.requestClose' event on game object, which will invoke modal.requestClose() method. After closing dialog, resolve part of promise will be triggered.
graph TB\n\nPromise[\"promose('gameObject, config)\"]\nOnOpen[\"gameObject.on('modal.open')\"]\nRequestCloseEvent[\"gameObject.emit('modal.requestClose', closeEventData)\"]\nTimeOut[\"Timeout<br>Any touch\"]\nOnClose[\"gameObject.on('modal.close')\"]\nResolve[\"then(function(closeEventData) { })\"]\n\nPromise --> |Transition-in| OnOpen\nOnOpen --> |manualClose| RequestCloseEvent\nOnOpen --> |Not manualClose| TimeOut\nRequestCloseEvent --> |Transition-out| OnClose\nTimeOut --> |Transition-out| OnClose\nOnClose --> Resolve
"},{"location":"modal-promise/#events","title":"Events","text":"
  • To invoke modal.requestClose() method
    gameObject.emit('modal.requestClose', closeEventData);\n
  • On opened dialog
    gameObject.on('modal.open', function(modalBehavior) {\n})\n
  • On closed dialog
    gameObject.on('modal.close', function(closeEventData, modalBehavior) {\n})\n
"},{"location":"modal/","title":"Modal behavior","text":""},{"location":"modal/#introduction","title":"Introduction","text":"

Pop-up modal dialog, then scale-down this dialog.

  • Author: Rex
  • Behavior of game object
"},{"location":"modal/#live-demos","title":"Live demos","text":"
  • Manual
  • Timeout
  • Touch outside
  • Custom transit
"},{"location":"modal/#usage","title":"Usage","text":"

Sample code

"},{"location":"modal/#install-plugin","title":"Install plugin","text":""},{"location":"modal/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexmodalplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexmodalplugin.min.js', true);\n
  • Add modal behavior
    var modal = scene.plugins.get('rexmodalplugin').add(gameObject, config);\n
"},{"location":"modal/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add modal behavior
    var modal = scene.plugins.get('rexModal').add(gameObject, config);\n
"},{"location":"modal/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ModalBehavoir } from 'phaser3-rex-plugins/plugins/modal.js';\n
  • Add modal behavior
    var modal = new ModalBehavoir(gameObject, config);\n
"},{"location":"modal/#create-instance","title":"Create instance","text":"
var modal = scene.plugins.get('rexModal').add(gameObject, {\n// cover: {\n//     color: 0x0,\n//     alpha: 0.8,\n//     transitIn: function(gameObject, duration) { },\n//     transitOut: function(gameObject, duration) { },\n// },\n// cover: false, \n\n// When to close modal dialog?\n// touchOutsideClose: false,\n// anyTouchClose: false,\n// timeOutClose: false,\n// manualClose: false,\n\n// duration: {\n//     in: 200,\n//     hold: 2000,\n//     out: 200\n// }\n\n// transitIn: 0,\n// transitOut: 0,\n\n// destroy: true,\n// openOnStart: true\n});\n
  • cover : Configuration of Cover -- A rectangle shape covered full window, and block all touch events.
    • false : Don't create cover game object.
    • cover.transitIn : Custom callback. Default behavior is fade-in.
      function(gameObject, duration) {\n\n}\n
    • cover.transitOut : Custom callback. Default behavior is fade-out.
      function(gameObject, duration) {\n\n}\n
  • touchOutsideClose : Set to true to close modal dialog when clicking out side of gameObject.
    • Default value is false. Will be set to false if anyTouchClose is set to true.
  • anyTouchClose : Set to true to close modal dialog when any clicking.
    • Default value is false.
  • timeOutClose : Set to true to close modal dialog when holding time out (duration.hold).
    • If duration.hold is given, default value is true. Otherwise default value is false.
  • manualClose : Set to true to close modal dialog via modal.requestClose() method.
    • Default value is false. When this parameter is true, other closing methods will be disabled.
    • If touchOutsideClose, anyTouchClose, and timeOutClose are false, it is equal to manualClose.
  • duration : Duration of transition-in, hold, trantion-out.
    • duration.in : Duration of transition-in (open dialog).
      • 0 : No transition, open dialog immediately.
    • duration.out : Duration of transition-out (close dialog).
      • 0 : No transition, close dialog immediately.
    • duration.hold : Duration of hold.
      • -1 : Disable timeOutClose.
  • transitIn : Transition behavior of opening dialog.
    • 0, 'popUp' : Pop up dialog from 0 to current scale.
    • 1, 'fadeIn' : Fade in dialog
    • Custom callback
      function(gameObject, duration) {\n\n}\n
  • transitOut : Tween behavior of closing dialog.
    • 0, 'scaleDown' : Scale down dialog
    • 1, 'fadeOut' : Fade out dialog
    • Custom callback
      function(gameObject, duration) {\n\n}\n
  • destroy
    • true : Destroy dialog game object and this behavior when closing completed. Default behavior.
    • fasle : Keep dialog game object and this behavior when closing completed. Could reuse it later.
  • openOnStart:
    • true : Open dialog game object (modal.requestOpen()) at beginning. Default behavior.
    • false : Open dialog game object manually.
"},{"location":"modal/#open","title":"Open","text":"
  • Will open modal dialog game object (run transition-in callback) when creating this behavior, if openOnStart is set to true.
  • Invoke modal.requestOpen() to open modal dialog game object again, after closing modal dialog.
    • Set destroy to false to reuse dialog game object and this behavior.
"},{"location":"modal/#close","title":"Close","text":"
modal.requestClose();\n// modal.requestClose(closeEventData);\n
  • closeEventData : Emit 'close' event when closed dialog complete, pass closeEventData to callback of this event.
    modal.on('close', function(closeEventData) {\n})\n
"},{"location":"modal/#events","title":"Events","text":"
  • On opened dialog
    modal.on('open', function(gameObject, modal) {\n})\n
  • On closed dialog
    modal.on('close', function(closeEventData) {\n})\n
"},{"location":"mousewheel/","title":"Mouse wheel","text":""},{"location":"mousewheel/#introduction","title":"Introduction","text":"

Mouse wheel events of phaser.

  • Author: Richard Davey
"},{"location":"mousewheel/#usage","title":"Usage","text":""},{"location":"mousewheel/#mouse-wheel-events","title":"Mouse wheel events","text":"
  1. Events on touched Game object
    gameObject.on('wheel', function(pointer, dx, dy, dz, event){ /* ... */ });\n
  2. Event on input plugin for each touched Game object
    scene.input.on('gameobjectwheel', function(pointer, gameObject, dx, dy, dz, event){ /* ... */ });\n
  3. Events to get all touched Game Objects
    scene.input.on('wheel', function(pointer, currentlyOver, dx, dy, dz, event){ /* ... */ });\n
"},{"location":"mousewheel/#mouse-wheel-properties","title":"Mouse wheel properties","text":"
  • pointer.deltaX : The horizontal scroll amount that occurred due to the user moving a mouse wheel or similar input device.
  • pointer.deltaY : The vertical scroll amount that occurred due to the user moving a mouse wheel or similar input device.
  • pointer.deltaZ : The z-axis scroll amount that occurred due to the user moving a mouse wheel or similar input device.
"},{"location":"mousewheelscroller/","title":"Mouse wheel scroller","text":""},{"location":"mousewheelscroller/#introduction","title":"Introduction","text":"

Emit scroll event when mouse-wheeling.

  • Author: Rex
  • Member of scene
"},{"location":"mousewheelscroller/#live-demos","title":"Live demos","text":"
  • Scroller
"},{"location":"mousewheelscroller/#usage","title":"Usage","text":"

Sample code

"},{"location":"mousewheelscroller/#install-plugin","title":"Install plugin","text":""},{"location":"mousewheelscroller/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexmousewheelscrollerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexmousewheelscrollerplugin.min.js', true);\n
  • Add mouse-wheeling-to-cursor-key object
    var scroller = scene.plugins.get('rexmousewheelscrollerplugin').add(gameObject, config);\n
"},{"location":"mousewheelscroller/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import MouseWheelScrollerPlugin from 'phaser3-rex-plugins/plugins/mousewheelscroller-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexMouseWheelScroller',\nplugin: MouseWheelScrollerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add mouse-wheeling-to-cursor-key object
    var scroller = scene.plugins.get('rexMouseWheelScroller').add(gameObject, config);\n
"},{"location":"mousewheelscroller/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import MouseWheelScroller from 'phaser3-rex-plugins/plugins/mousewheelscroller.js';\n
  • Add mouse-wheeling-to-cursor-key object
    var scroller = new MouseWheelScroller(gameObject, config);\n
"},{"location":"mousewheelscroller/#create-instance","title":"Create instance","text":"
var scroller = scene.plugins.get('rexMouseWheelScroller').add(gameObject, {\n// focus: true,\n// speed: 0.1,\n// enable: true,\n});\n
  • focus : Fire 'scroll' event when mouse-wheeling --
    • false, or 0 : Without checking if cursor is over game object or not.
    • true, or 1 : Cursor is over game object. Default behavior.
    • 2 : Cursor is inside the rectangle bounds of game object.
  • speed : Scrolling speed. Default value is 0.1.
  • enable : Set true to enable 'scroll' event.
"},{"location":"mousewheelscroller/#event","title":"Event","text":"
  • Scroll
    scroller.on('scroll', function(inc, gameObject, scroller) {\n\n}, scope)\n
    • inc : Scroll value,
      • Positive value : Mouse-wheeling down
      • Negative value : Mouse-wheeling up
"},{"location":"mousewheelscroller/#speed","title":"Speed","text":"
  • Set
    scroller.setSpeed(speed);\n// scroller.speed = speed;\n
  • Get
    var speed = scroller.speed;\n
"},{"location":"mousewheelscroller/#enable","title":"Enable","text":"
  • Set
    scroller.setEnable(enable);\n// scroller.enable = enable;\n
  • Get
    var enable = scroller.enable;\n
"},{"location":"mousewheeltoupdown/","title":"Mouse-wheel to up/down","text":""},{"location":"mousewheeltoupdown/#introduction","title":"Introduction","text":"

Map mouse-wheeling to (up/down) cursor key state.

  • Author: Rex
  • Member of scene
"},{"location":"mousewheeltoupdown/#usage","title":"Usage","text":"

Sample code

"},{"location":"mousewheeltoupdown/#install-plugin","title":"Install plugin","text":""},{"location":"mousewheeltoupdown/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexmousewheeltoupdownplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexmousewheeltoupdownplugin.min.js', true);\n
  • Add mouse-wheeling-to-cursor-key object
    var mouseWheelToUpDown = scene.plugins.get('rexmousewheeltoupdownplugin').add(scene);\n
"},{"location":"mousewheeltoupdown/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import MouseWheelToUpDownPlugin from 'phaser3-rex-plugins/plugins/mousewheeltoupdown-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexMouseWheelToUpDown',\nplugin: MouseWheelToUpDownPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add mouse-wheeling-to-cursor-key object
    var mouseWheelToUpDown = scene.plugins.get('rexMouseWheelToUpDown').add(scene);\n
"},{"location":"mousewheeltoupdown/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import MouseWheelToUpDown from 'phaser3-rex-plugins/plugins/mousewheeltoupdown.js';\n
  • Add mouse-wheeling-to-cursor-key object
    var mouseWheelToUpDown = new MouseWheelToUpDown(scene);\n
"},{"location":"mousewheeltoupdown/#create-instance","title":"Create instance","text":"
var mouseWheelToUpDown = scene.plugins.get('rexMouseWheelToUpDown').add(scene);\n
"},{"location":"mousewheeltoupdown/#state-of-cursor-keys","title":"State of cursor keys","text":"
var cursorKeys = mouseWheelToUpDown.createCursorKeys();\n\nvar upKeyDown = cursorKeys.up.isDown;\nvar downKeyDown = cursorKeys.down.isDown;\n

Or

var upKeyDown = mouseWheelToUpDown.up;\nvar downKeyDown = mouseWheelToUpDown.down;\nvar noKeyDown = mouseWheelToUpDown.noKey;\n
"},{"location":"mousewheeltoupdown/#destroy","title":"Destroy","text":"
mouseWheelToUpDown.destroy();\n
"},{"location":"moveto/","title":"Move to","text":""},{"location":"moveto/#introduction","title":"Introduction","text":"

Move game object towards target position with a steady speed.

  • Author: Rex
  • Behavior of game object
"},{"location":"moveto/#live-demos","title":"Live demos","text":"
  • Move-to
"},{"location":"moveto/#usage","title":"Usage","text":"

Sample code

"},{"location":"moveto/#install-plugin","title":"Install plugin","text":""},{"location":"moveto/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexmovetoplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexmovetoplugin.min.js', true);\n
  • Add move-to behavior
    var moveTo = scene.plugins.get('rexmovetoplugin').add(gameObject, config);\n
"},{"location":"moveto/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import MoveToPlugin from 'phaser3-rex-plugins/plugins/moveto-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexMoveTo',\nplugin: MoveToPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add move-to behavior
    var moveTo = scene.plugins.get('rexMoveTo').add(gameObject, config);\n
"},{"location":"moveto/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import MoveTo from 'phaser3-rex-plugins/plugins/moveto.js';\n
  • Add move-to behavior
    var moveTo = new MoveTo(gameObject, config);\n
"},{"location":"moveto/#create-instance","title":"Create instance","text":"
var moveTo = scene.plugins.get('rexMoveTo').add(gameObject, {\n// speed: 400,\n// rotateToTarget: false\n});\n
  • speed : Moving speed, pixels in second.
  • rotateToTarget : Set true to change angle towards path.
"},{"location":"moveto/#start-moving","title":"Start moving","text":"
  • Move to target position
    moveTo.moveTo(x, y);\n
    or
    moveTo.moveTo({\nx: 0,\ny: 0,\n// speed: 0\n});\n
    • x , y : Target position
  • Move from start position to current position
    moveTo.moveFrom(x, y);\n
    or
    moveTo.moveFrom({\nx: 0,\ny: 0,\n// speed: 0\n});\n
    • x , y : Start position
  • Move toward angle
    moveTo.moveToward(angle, distance);\n
    • angle : Angle in radian.
"},{"location":"moveto/#target-position","title":"Target position","text":"
var targetX = moveTo.targetX;\nvar targetY = moveTo.targetY;\n
"},{"location":"moveto/#enable","title":"Enable","text":"
  • Enable (default)
    moveTo.setEnable();\n
    or
    moveTo.enable = true;\n
  • Disable
    moveTo.setEnable(false);\n
    or
    moveTo.enable = false;\n
"},{"location":"moveto/#pause-resume-stop-moving","title":"Pause, Resume, stop moving","text":"
moveTo.pause();\nmoveTo.resume();\nmoveTo.stop();\n
"},{"location":"moveto/#set-speed","title":"Set speed","text":"
moveTo.setSpeed(speed);\n// moveTo.speed = speed;\n
"},{"location":"moveto/#set-rotate-to-target","title":"Set rotate-to-target","text":"
moveTo.setRotateToTarget(rotateToTarget);\n
  • rotateToTarget : Set true to change angle towards target
"},{"location":"moveto/#events","title":"Events","text":"
  • On start moving
    moveTo.on('start', function(gameObject, moveTo){});\n
  • On reached target
    moveTo.on('complete', function(gameObject, moveTo){});\n// moveTo.once('complete', function(gameObject, moveTo){});\n
"},{"location":"moveto/#status","title":"Status","text":"
  • Is moving
    var isRunning = moveTo.isRunning;\n
"},{"location":"mustache/","title":"Mustache","text":""},{"location":"mustache/#introduction","title":"Introduction","text":"

Format string with variables. Reference

"},{"location":"mustache/#usage","title":"Usage","text":"
var template = 'hello, {{name}}';\nvar view = {\nname: 'rex'\n};\nvar result = Mustache.render(template, view);\n
"},{"location":"ninepatch/","title":"Nine patch","text":""},{"location":"ninepatch/#introduction","title":"Introduction","text":"

Stretchable image, extended from RenderTexture game object.

  • Author: Rex
  • Game object
"},{"location":"ninepatch/#live-demos","title":"Live demos","text":"
  • 3x3, 3x3
  • 5x5
  • Custom frame name
  • Custom base frame name
  • Preserve ratio
  • Max-fixed-part-scale
"},{"location":"ninepatch/#usage","title":"Usage","text":"

Sample code

"},{"location":"ninepatch/#install-plugin","title":"Install plugin","text":""},{"location":"ninepatch/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexninepatchplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexninepatchplugin.min.js', true);\n
  • Add nine-patch object
    var ninePatch = scene.add.rexNinePatch(x, y, width, height, key, baseFrame, columns, rows, config);\n
"},{"location":"ninepatch/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import NinePatchPlugin from 'phaser3-rex-plugins/plugins/ninepatch-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexNinePatchPlugin',\nplugin: NinePatchPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add nine-patch object
    var ninePatch = scene.add.rexNinePatch(x, y, width, height, key, baseFrame, columns, rows, config);\n
"},{"location":"ninepatch/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import NinePatch from 'phaser3-rex-plugins/plugins/ninepatch.js';\n
  • Add nine-patch object
    var ninePatch = new NinePatch(scene, x, y, width, height, key, baseFrame, columns, rows, config);\nscene.add.existing(ninePatch);\n
"},{"location":"ninepatch/#create-instance","title":"Create instance","text":"
var ninePatch = scene.add.rexNinePatch(x, y, width, height, key, baseFrame, columns, rows, {\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch(x, y, width, height, key, columns, rows, {\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch(x, y, width, height, key, {\ncolumns: undefined, // leftWidth: undefined, right: undefined,\nrows: undefined,    // topHeight: undefined, bottomHeight: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch(x, y, width, height, {\nkey: undefined,\ncolumns: undefined, // leftWidth: undefined, right: undefined,\nrows: undefined,    // topHeight: undefined, bottomHeight: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch(x, y, {\nwidth: 1, height: 1,\nkey: undefined,\ncolumns: undefined, // leftWidth: undefined, right: undefined,\nrows: undefined,    // topHeight: undefined, bottomHeight: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch({\nx: 0, y: 0,\nwidth: 1, height: 1,\nkey: undefined,\ncolumns: undefined, // leftWidth: undefined, rightWidth: undefined,\nrows: undefined,    // topHeight: undefined, bottomHeight: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,  // frame: undefined,\ngetFrameNameCallback: undefined\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • key : Texture key of source image.
  • baseFrame, or frame : Frame name of base texture.
    • undefined : Use default base frame '__BASE'.
  • columns : Configuration of columns.
    • A number array, like [20, 20, 20], or [20, undefined, 20] : Width of each column. undefined value will be replaced by remainder value from texture width.
      • Width of odd columns (column 0, column 2, ...) will be origin width.
      • Width of even columns (column 1, column 3, ...) will be stretched.
  • leftWidth, rightWidth : Set columns to [leftWidth, undefined, rightWidth], if columns is undefined.
  • rows : Configuration of rows.
    • A number array, like [20, 20, 20], or [20, undefined, 20] : Height of each row. undefined value will be replaced by remainder value from texture width.
      • Height of odd rows (row 0, row 2, ...) will be origin height.
      • Height of odd rows (row 1, row 3, ...) will be stretched.
  • topHeight, bottomHeight : Set rows to [topHeight, undefined, bottomHeight], if rows is undefined.
  • preserveRatio : Preserve ratio of fixed parts (i.e. displaying in origin size). Default is true.
  • maxFixedPartScale : Max scale value of fixed-part.
  • stretchMode : Stretch mode of edges and internal cells.
    • A number (0, or 1), or a string ('scale', or 'repeat'):
      • 0, or 'scale' : Stretch each edge and internal cell by scaled image. Default value.
      • 1, or 'repeat' : Stretch each edge and internal cell by repeated image (tile-sprite).
    • An object :
      {\nedge: 0, // 'scale', or 1, 'repeat'\ninternal: 0, // 'scale', or 1, 'repeat'\n}\n
  • getFrameNameCallback : Callback to get frame name of each cell.
    • undefined : Use default callback.
      • If baseFrame is '__BASE' : return ${colIndex},${rowIndex}
      • Else : return ${baseFrame}_${colIndex},${rowIndex}
    • Function object : Return a string, or undefined.
      function(colIndex, rowIndex, baseFrame) {\nreturn `${colIndex},${rowIndex}`;\n}\n
"},{"location":"ninepatch/#custom-class","title":"Custom class","text":"
  • Define class
    class MyNinePatch extends NinePatch {\nconstructor(scene, x, y, width, height, key, baseFrame, columns, rows, config) {\nsuper(scene, x, y, width, height, key, baseFrame, columns, rows, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var ninePatch = new MyNinePatch(scene, x, y, width, height, key, baseFrame, columns, rows, config);\n
"},{"location":"ninepatch/#resize","title":"Resize","text":"
ninePatch.resize(width, height);\n

Will update texture

"},{"location":"ninepatch/#set-base-texture-of-source-image","title":"Set base texture of source image","text":"
ninePatch.setBaseTexture(key, baseFrame, columns, rows);\n

or

ninePatch.setBaseTexture(key, baseFrame, leftWidth, rightWidth, topHeight, bottomHeight);\n

or

ninePatch.setBaseTexture(key, baseFrame);\n
  • key : Texture key of source image.
  • baseFrame : Frame name of base texture.
    • undefined, or null : Use default base frame '__BASE'. Default value.
  • columns : Configuration of columns.
    • A number array, like [20, 20, 20] : Width of each column.
      • Width of odd columns (column 0, column 2, ...) will be origin width.
      • Width of even columns (column 1, column 3, ...) will be stretched.
    • undefined : If columns and rows are undefined, it will use current configuration of columns and rows.
  • rows : Configuration of rows.
    • A number array, like [20, 20, 20] : Height of each row.
      • Height of odd rows (row 0, row 2, ...) will be origin height.
      • Height of odd rows (row 1, row 3, ...) will be stretched.
    • undefined : If columns and rows are undefined, it will use current configuration of columns and rows.
  • leftWidth, rightWidth : Set columns to [leftWidth, undefined, rightWidth].
  • topHeight, bottomHeight : Set rows to [topHeight, undefined, bottomHeight].

Will update texture

"},{"location":"ninepatch/#set-stretch-mode","title":"Set stretch mode","text":"
ninePatch.setStretchMode(mode);\n
  • mode :
    • A number (0, or 1), or a string ('scale', or 'repeat'):
      • 0, or 'scale' : Stretch each edge and internal cell by scaled image. Default value.
      • 1, or 'repeat' : Stretch each edge and internal cell by repeated image (tile-sprite).
    • An object :
      {\nedge: 0, // 'scale', or 1, 'repeat'\ninternal: 0, // 'scale', or 1, 'repeat'\n}\n
"},{"location":"ninepatch/#set-get-frame-name-callback","title":"Set get-frame-name callback","text":"
ninePatch.setGetFrameNameCallback(callback);\n
  • callback : Return a string, or undefined.
    function(colIndex, rowIndex, baseFrame) {\nreturn `${colIndex},${rowIndex}`\n}\n
"},{"location":"ninepatch/#fixed-part-scale","title":"Fixed-part scale","text":"
  • Fixed-part scale
    • Get
      var scaleX = ninePatch.fixedPartScaleX;\nvar scaleY = ninePatch.fixedPartScaleY;\n
  • Max fixed-part scale
    • Get
      var scaleX = ninePatch.maxFixedPartScaleX;\nvar scaleY = ninePatch.maxFixedPartScaleY;\n
    • Set
      ninePatch.setMaxFixedPartScale(scale);\n// ninePatch.setMaxFixedPartScale(scaleX, scaleY);\n
      or
      ninePatch.maxFixedPartScaleX = scaleX;\nninePatch.maxFixedPartScaleY = scaleY;\n
"},{"location":"ninepatch/#update-texture","title":"Update texture","text":"
ninePatch.updateTexture();\n
"},{"location":"ninepatch/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"ninepatch/#create-mask","title":"Create mask","text":"
var mask = ninePatch.createBitmapMask();\n

See mask

"},{"location":"ninepatch/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"ninepatch/#compare-with-nine-slice","title":"Compare with nine-slice","text":"
  • Nine-slice is a built-in game object.
  • Nine-slice has better render performance.
    • Nine-patch extends from render-texture, which will create a new texture, then draw frames on it.
  • Nine-slice is webgl mode only.
  • Nine-slice does not have flip, crop methods.
"},{"location":"ninepatch2/","title":"Nine patch2","text":""},{"location":"ninepatch2/#introduction","title":"Introduction","text":"

Stretchable image. Has better performance than nine-patch.

  • Author: Rex
  • Game object
"},{"location":"ninepatch2/#live-demos","title":"Live demos","text":"
  • 3x3
  • Performance test
"},{"location":"ninepatch2/#usage","title":"Usage","text":"

Sample code

"},{"location":"ninepatch2/#install-plugin","title":"Install plugin","text":""},{"location":"ninepatch2/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexninepatch2plugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexninepatch2plugin.min.js', true);\n
  • Add nine-patch object
    var ninePatch = scene.add.rexNinePatch2(x, y, width, height, key, baseFrame, columns, rows, config);\n
"},{"location":"ninepatch2/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import NinePatch2Plugin from 'phaser3-rex-plugins/plugins/ninepatch2-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexNinePatch2Plugin',\nplugin: NinePatch2Plugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add nine-patch object
    var ninePatch = scene.add.rexNinePatch2(x, y, width, height, key, baseFrame, columns, rows, config);\n
"},{"location":"ninepatch2/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import NinePatch2 from 'phaser3-rex-plugins/plugins/ninepatch2.js';\n
  • Add nine-patch object
    var ninePatch = new NinePatch2(scene, x, y, width, height, key, baseFrame, columns, rows, config);\nscene.add.existing(ninePatch);\n
"},{"location":"ninepatch2/#create-instance","title":"Create instance","text":"
var ninePatch = scene.add.rexNinePatch2(x, y, width, height, key, baseFrame, columns, rows, {\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch2(x, y, width, height, key, columns, rows, {\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch2(x, y, width, height, key, {\ncolumns: undefined,\nrows: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch2(x, y, width, height, {\nkey: undefined,\ncolumns: undefined,\nrows: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch2(x, y, {\nwidth: 1, height: 1,\nkey: undefined,\ncolumns: undefined,\nrows: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n

or

var ninePatch = scene.add.rexNinePatch2({\nx: 0, y: 0,\nwidth: 1, height: 1,\nkey: undefined,\ncolumns: undefined,\nrows: undefined,\n\n// preserveRatio: true,\n// maxFixedPartScale: 1,\n// stretchMode: 0,\nbaseFrame: undefined,\ngetFrameNameCallback: undefined\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • key : Texture key of source image.
  • baseFrame : Frame name of base texture.
    • undefined : Use default base frame '__BASE'.
  • columns : Configuration of columns.
    • A number array, like [20, 20, 20], or [20, undefined, 20] : Width of each column. undefined value will be replaced by remainder value from texture width.
      • Width of odd columns (column 0, column 2, ...) will be origin width.
      • Width of even columns (column 1, column 3, ...) will be stretched.
  • rows : Configuration of rows.
    • A number array, like [20, 20, 20], or [20, undefined, 20] : Height of each row. undefined value will be replaced by remainder value from texture width.
      • Height of odd rows (row 0, row 2, ...) will be origin height.
      • Height of odd rows (row 1, row 3, ...) will be stretched.
  • preserveRatio : Preserve ratio of fixed parts (i.e. displaying in origin size). Default is true.
  • maxFixedPartScale : Max scale value of fixed-part.
  • stretchMode : Stretch mode of edges and internal cells.
    • A number (0, or 1), or a string ('scale', or 'repeat'):
      • 0, or 'scale' : Stretch each edge and internal cell by scaled image. Default value.
      • 1, or 'repeat' : Stretch each edge and internal cell by repeated image (tile-sprite).
    • An object :
      {\nedge: 0, // 'scale', or 1, 'repeat'\ninternal: 0, // 'scale', or 1, 'repeat'\n}\n
  • getFrameNameCallback : Callback to get frame name of each cell.
    • undefined : Use default callback.
      • If baseFrame is '__BASE' : return ${colIndex},${rowIndex}
      • Else : return ${baseFrame}:${colIndex},${rowIndex}
    • Function object : Return a string, or undefined.
      function(colIndex, rowIndex, baseFrame) {\nreturn `${colIndex},${rowIndex}`;\n}\n
"},{"location":"ninepatch2/#custom-class","title":"Custom class","text":"
  • Define class
    class MyNinePatch extends NinePatch2 {\nconstructor(scene, x, y, width, height, key, baseFrame, columns, rows, config) {\nsuper(scene, x, y, width, height, key, baseFrame, columns, rows, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var ninePatch = new MyNinePatch(scene, x, y, width, height, key, baseFrame, columns, rows, config);\n
"},{"location":"ninepatch2/#resize","title":"Resize","text":"
ninePatch.resize(width, height);\n

Will update texture

"},{"location":"ninepatch2/#tint","title":"Tint","text":"
  • Set tint
    ninePatch.setTint(tint);\n
  • Clear tint
    ninePatch.clearTint();\n
  • Set tint fill
    ninePatch.setTintFill(tint);\n
  • Get tint
    var tint = ninePatch.tint;\nvar tintFill = ninePatch.tintFill;\n
    • tintFill :
      • false : Solid tint + texture alpha
      • true : Solid tint, no texture
"},{"location":"ninepatch2/#set-texture-of-source-image","title":"Set texture of source image","text":"
ninePatch.setBaseTexture(key, baseFrame, columns, rows);\n// ninePatch.setBaseTexture(key, columns, rows);\n
  • key : Texture key of source image.
  • baseFrame : Frame name of base texture.
    • undefined : Use default base frame '__BASE'. Default value.
  • columns : Configuration of columns.
    • A number array, like [20, 20, 20] : Width of each column.
      • Width of odd columns (column 0, column 2, ...) will be origin width.
      • Width of even columns (column 1, column 3, ...) will be stretched.
  • rows : Configuration of rows.
    • A number array, like [20, 20, 20] : Height of each row.
      • Height of odd rows (row 0, row 2, ...) will be origin height.
      • Height of odd rows (row 1, row 3, ...) will be stretched.

Will update texture

"},{"location":"ninepatch2/#set-stretch-mode","title":"Set stretch mode","text":"
ninePatch.setStretchMode(mode);\n
  • mode :
    • A number (0, or 1), or a string ('scale', or 'repeat'):
      • 0, or 'scale' : Stretch each edge and internal cell by scaled image. Default value.
      • 1, or 'repeat' : Stretch each edge and internal cell by repeated image (tile-sprite).
    • An object :
      {\nedge: 0, // 'scale', or 1, 'repeat'\ninternal: 0, // 'scale', or 1, 'repeat'\n}\n
"},{"location":"ninepatch2/#set-get-frame-name-callback","title":"Set get-frame-name callback","text":"
ninePatch.setGetFrameNameCallback(callback);\n
  • callback : Return a string, or undefined.
    function(colIndex, rowIndex, baseFrame) {\nreturn `${colIndex},${rowIndex}`\n}\n
"},{"location":"ninepatch2/#fixed-part-scale","title":"Fixed-part scale","text":"
  • Fixed-part scale
    • Get
      var scaleX = ninePatch.fixedPartScaleX;\nvar scaleY = ninePatch.fixedPartScaleY;\n
  • Max fixed-part scale
    • Get
      var scaleX = ninePatch.maxFixedPartScaleX;\nvar scaleY = ninePatch.maxFixedPartScaleY;\n
    • Set
      ninePatch.setMaxFixedPartScale(scale);\n// ninePatch.setMaxFixedPartScale(scaleX, scaleY);\n
      or
      ninePatch.maxFixedPartScaleX = scaleX;\nninePatch.maxFixedPartScaleY = scaleY;\n
"},{"location":"ninepatch2/#update-texture","title":"Update texture","text":"
ninePatch.updateTexture();\n
"},{"location":"ninepatch2/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"ninepatch2/#create-mask","title":"Create mask","text":"
var mask = ninePatch.createBitmapMask();\n

See mask

"},{"location":"ninepatch2/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"ninepatch2/#compare-with-nine-patch","title":"Compare with nine-patch","text":"
  • Nine-patch2 has better performance.
    • Nine-patch extends from render-texture, which will create a new texture, then draw frames on it.
    • Nine-patch2 draws frames directly.
  • Nine-patch2 does not have flip, crop methods.
  • Nine-patch2 can't apply custom spriteFx pipeline.
"},{"location":"nineslice/","title":"Nine slice","text":""},{"location":"nineslice/#introduction","title":"Introduction","text":"

Display a texture-based object that can be stretched both horizontally and vertically, but that retains fixed-sized corners, built-in game object of phaser.

  • Author: Richard Davey

WebGL only

Only work in WebGL render mode.

"},{"location":"nineslice/#usage","title":"Usage","text":""},{"location":"nineslice/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"nineslice/#add-nine-slice-object","title":"Add nine slice object","text":"
var nineSlice = scene.add.nineslice(x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight);\n

or

var nineSlice = scene.add.nineslice(x, y, texture, frame, width, height);\n// var nineSlice = scene.add.nineslice(x, y, texture, frame);\n
  • If that frame (indexed by texture, frame) is generated by Texture Packer.

Add nine slice from JSON

var nineSlice = scene.make.nineslice({\nx: 0,\ny: 0,\nkey: '',\n// frame: '',\n\n// width: 256,\n// height: 256,\n// leftWidth: 10,\n// rightWidth: 10,\n// topHeight: 0,\n// bottomHeight: 0,\n\n// angle: 0,\n// alpha: 1,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
"},{"location":"nineslice/#custom-class","title":"Custom class","text":"
  • Define class
    class MyNineSlice extends Phaser.GameObjects.NineSlice {\nconstructor(scene, x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight) {\nsuper(scene, x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var nineSlice = new MyNineSlice(scene, x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight);\n
"},{"location":"nineslice/#resize","title":"Resize","text":"
nineSlice.setSize(width, height);\n
"},{"location":"nineslice/#set-texture-of-source-image","title":"Set texture of source image","text":"
nineSlice.setTexture(texture, frame);\nnineSlice.setSlices(width, height, leftWidth, rightWidth, topHeight, bottomHeight);\n
"},{"location":"nineslice/#texture","title":"Texture","text":"

See game object - texture

"},{"location":"nineslice/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"nineslice/#create-mask","title":"Create mask","text":"
var mask = nineSlice.createBitmapMask();\n

See mask

"},{"location":"nineslice/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"nineslice/#compare-with-nine-patch","title":"Compare with nine-patch","text":"
  • Nine-slice is a built-in game object.
  • Nine-slice has better render performance.
    • Nine-patch extends from render-texture, which will create a new texture, then draw frames on it.
  • Nine-slice is webgl mode only.
  • Nine-slice does not have flip, crop methods.
"},{"location":"orientation/","title":"Orientation","text":""},{"location":"orientation/#introduction","title":"Introduction","text":"

Get oriention, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"orientation/#usage","title":"Usage","text":""},{"location":"orientation/#orientation","title":"Orientation","text":"
var orientation = scene.scale.orientation;\n
"},{"location":"orientation/#events","title":"Events","text":"
  • On orientation change
    scene.scale.on('orientationchange', function(orientation) {\nswitch (orientation) {\ncase Phaser.Scale.PORTRAIT:\ncase Phaser.Scale.PORTRAIT_SECONDARY:\n// ...\nbreak;\n\ndefault:  // Phaser.Scale.LANDSCAPE or Phaser.Scale.LANDSCAPE_SECONDARY\n// ...\nbreak;\n}\n});\n
"},{"location":"orientation/#lock-orientation","title":"Lock orientation","text":"
scene.scale.lockOrientation(orientation)\n
  • orientation :
    • 'portrait'
    • 'landscape'
    • 'portrait-primary'
    • 'portrait-secondary'
    • 'landscape-primary'
    • 'landscape-secondary'
    • 'default'
"},{"location":"pad/","title":"Pad","text":""},{"location":"pad/#introduction","title":"Introduction","text":"

Takes the given string and pads it out, to the length required, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"pad/#usage","title":"Usage","text":"
var result = Phaser.Utils.String.Pad(str, len, pad, dir);\n
  • str : String, or number.
  • len : Length or result string.
  • pad : The string to pad it out.
  • dir :
    • 1 : Left
    • 2 : Right
    • 3 : Both
"},{"location":"particles-along-bounds/","title":"Particles along bounds","text":""},{"location":"particles-along-bounds/#introduction","title":"Introduction","text":"

Emit particles along bounds of game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"particles-along-bounds/#live-demos","title":"Live demos","text":"
  • Particles-along-bounds
"},{"location":"particles-along-bounds/#usage","title":"Usage","text":"

Sample code

"},{"location":"particles-along-bounds/#install-plugin","title":"Install plugin","text":""},{"location":"particles-along-bounds/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexparticlesalongboundsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexparticlesalongboundsplugin.min.js', true);\n
  • Start emit particles along bounds of game object
    var particles = scene.plugins.get('rexparticlesalongboundsplugin').startEffect(gameObject, config);\n
"},{"location":"particles-along-bounds/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import DragPlugin from 'phaser3-rex-plugins/plugins/particlesalongbounds-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexParticlesAlongBounds',\nplugin: ParticlesAlongBoundsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Start emit particles along bounds of game object
    var particles = scene.plugins.get('rexParticlesAlongBounds').startEffect(gameObject, config);\n
"},{"location":"particles-along-bounds/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ParticlesAlongBounds from 'phaser3-rex-plugins/plugins/particlesalongbounds.js';\n
  • Start emit particles along bounds of game object
    var particles = ParticlesAlongBounds(gameObject, config);\n
"},{"location":"particles-along-bounds/#create-instance","title":"Create instance","text":"
var particles = scene.plugins.get('rexParticlesAlongBounds').startEffect(gameObject, {\ntextureKey: key,\n// textureFrames: undefined,\n// padding: 0,\n// blendMode: 'ADD',\n// lifespan: 1000,\n// stepRate: 10,\n// spread: 10,\n\n// scale: undefined,\n// alpha: undefined,\n// tint: undefined,\n\n// repeat: 0,\n// gravityX: 0,\n// gravityY: 0,\n// duration: undefined\n});\n
  • padding : Extra padded space around bounds of game object. Default is 0.
    • A number for left/right/top/bottom bounds,
    • Or a plain object.
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • textureKey : Texture key of particles.
  • textureFrames : : One or more texture frames, or a configuration object.
    • String or number value.
    • Array of string or number value.
    • Configuration object :
      {\nframes: [],\ncycle: false,\nquantity: 1\n}\n
  • blendMode : Blend mode of particles. Default value is ADD.
  • lifespan : Lifespan of particle.
  • stepRate : Step length between each particle's initial position along bounds of game object.
  • spread : Moving speed of particle.
  • scale : Scale changing of particle.
  • alpha : Alpha changing of particle.
  • tint : Tint changing of particle.
  • repeat : Fire particles around bounds repeatly.
    • 0 : Fire particles around bounds one time, default value.
  • gravityX, gravityY : Gravity vector of world axis. This vector will rotate back if game object is rotated.
  • duration : Total duration from firing of 1st particle to destroy last particle.
    • undefined : Use default behavior of particles
    • Less or equal to lifespan : Fires all particles at begining.

Format of spread, scale, alpha, tint parameters :

  • {min, max} : Pick a random value between min and max
  • {start, end} : Pick values incremented continuously across a range. (ease='Linear')
    • {start, end, ease}
  • {start, end, steps} : Pick values incremented by steps across a range.
  • {start, end, random}
    • random: true or false
  • {min, max, steps} : Pick values between min to max, with steps.
  • {onEmit: function(particle, key, t, value) {return value}} : Get return value from a function invoking.
"},{"location":"particles-along-bounds/#is-running","title":"Is running","text":"
var isRunning = particles.isRunning;\n
"},{"location":"particles-along-bounds/#events","title":"Events","text":"
  • On fire completed, i.e. last particle is dead
    particles.on('complete', function(gameObject, particles){\n\n}, scope);\n
"},{"location":"particles/","title":"Particles","text":""},{"location":"particles/#introduction","title":"Introduction","text":"

Particles uses its own lightweight physics system, and can interact only with its Emitter's bounds and zones. Built-in game object of phaser.

  • Author: Richard Davey

Note

API is not compatible with 3.55.x

"},{"location":"particles/#usage","title":"Usage","text":""},{"location":"particles/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"particles/#add-particle","title":"Add particle","text":"
var particles = scene.add.particles(x, y, texture, {\n\n// EmitterOp\naccelerationX: 0,\naccelerationY: 0,\nalpha: 1,\nangle: { min: 0, max: 360 },\nbounce: 0,\ncolor: undefined,\ndelay: 0,\nhold: 0,\nlifespan: 1000,\nmaxVelocityX: 10000,\nmaxVelocityY: 10000,\nmoveToX: 0,\nmoveToY: 0,\nquantity: 1,\nrotate: 0,\nscaleX: 1,\nscaleY: 1,\n// scale:\nspeedX: 0,\nspeedY: 0,\nspeed: tint: 0xffffff,\nx: 0,\ny: 0,\n\n// Emitter properties\nactive:\nadvance:\nblendMode:\ncolorEase:\ndeathCallback:\ndeathCallbackScope:\nduration:\nemitCallback:\nemitCallbackScope:\n// callbackScope    \nfrequency:\ngravityX:\ngravityY:\nmaxAliveParticles:\nmaxParticles:\nname:\nemitting:\nparticleBringToTop:\nparticleClass:\nradial:\nsortCallback:\nsortOrderAsc:\nsortProperty:\nstopAfter:\ntintFill:\ntimeScale:\ntrackVisible:\nvisible:\n\n// Position\n// emitZone : random-zone, edge-zone\n// random-zone\nemitZone: {\ntype: 'random',\nsource: geom,\n},\n\n// edge-zone\nemitZone:{\ntype: 'edge',\nsource: geom,\nquantity: 1,\nstepRate: 0,\ntotal: -1,\nyoyo: false,\nseamless: true\n},\n\ndeathZone: {\ntype: 'onEnter', // 'onEnter', or 'onLeave'\nsource: geom,\n},\n\nbounds:               // {x, y, w, h}, or {x, y, width, height}, or Phaser.Geom.Rectangle\ncollideLeft: true,\ncollideRight: true,\ncollideTop: true,\ncollideBottom: true,\n\nfollow:\nfollowOffset:{\nx: 0,\ny: 0\n},\n\n// Texture\ntexture:\nframe:\nanim: [],  // string, or array of string\n\nreserve: 0,\nadvance: 0\n});\n
  • Parameters of EmitterOp : Number, Random Array, Custom Callback, Stepped start/end, Eased start/end, min/max, Random object, Custom onEmit onUpdate, Interpolation
    • A number
    • {min, max} : Pick a random value between min and max
    • {min, max, int}
    • {start, end} : Pick values incremented continuously across a range. (ease='Linear')
      • {start, end, ease}
      • {start, end, ease, easeParams}
    • {start, end, steps} : Pick values incremented by steps across a range.
    • {start, end, steps, yoyo: true}
    • {start, end, random}
      • random: true or false
    • {random: [start, end]} : Pick a random number between start and and.
    • [a, b, c, d] : Pick a random number from an array.
    • {min, max, steps} : Pick values between min to max, with steps.
    • { values: [ a, b, c, d ], interpolation: 'catmull', ease: 'linear' } : Interpolation (linear, bezier, catmull) in values array.
    • function(particle, key, t, value) { return value; }
    • {onEmit, onUpdate} : Get return value from a function invoking.
      function(particle, key, t, value) {\nreturn value;\n}\n
  • active : Whether this emitter updates itself and its particles.
    • false : Equal to pause.
  • advance : If you wish to fast forward the emitter in time, set this value to a number representing the amount of ms the emitter should advance.
  • blendMode : See blend mode
  • colorEase : The string-based name of the Easing function to use if you have enabled Particle color interpolation via the color property, otherwise has no effect.
  • deathCallback, deathCallbackScope
    function(particle) {\n\n}\n
  • emitCallback, emitCallbackScope
    function(particle, emitter) {\n\n}\n
  • duration : Limit the emitter to emit particles for a maximum of duration ms.
    • 0 : Forever, default behavior.
  • follow : A Game Object whose position is used as the particle origin.
  • followOffset : The offset of the particle origin from thefollow target.
  • frequency
    • 0 : One particle flow cycle for each logic update (the maximum flow frequency).
    • > 0 : The time interval between particle flow cycles in ms.
    • -1 : Exploding emitter.
  • hold : Frozen or 'held in place' after it has finished its lifespan for a set number of ms
  • gravityX, gravityY
  • maxAliveParticles
  • maxParticles
    • 0 : Unlimited.
    • > 0 : Hard limit the amount of particle objects.
  • frames : One or more texture frames, or a configuration object.
    • String or number value
    • Array of string or number value
    • Configuration object :
      {\nframes: [],\ncycle: false,\nquantity: 1\n}\n
  • anim :
    • String
    • Array of string
    • Configuration object :
      {\nanim: [],  // Array of string\ncycle: false,\nquantity: 1\n}\n
  • particleBringToTop :
    • true : Newly emitted particles are added to the top of the particle list, i.e. rendered above those already alive. Default behavior.
  • sortCallback : The callback used to sort the particles.
  • sortProperty : Optionally sort the particles before they render based on this property. The property must exist on the Particle class, such as y, lifeT, scaleX, etc.
  • sortOrderAsc : When sortProperty is defined this controls the sorting order, either ascending or descending.
  • stopAfter : The Particle Emitter will stop emitting particles once this total has been reached. It will then enter a 'stopped' state, firing the STOP event.
  • radial : A radial emitter will emit particles in all directions between angle min and max,
  • emitting : Controls if the emitter is currently emitting a particle flow (when frequency >= 0). Already alive particles will continue to update until they expire.
    • false : Equal to stop
  • tintFill :
  • timeScale : The time rate applied to active particles, affecting lifespan, movement, and tweens. Values larger than 1 are faster than normal.
  • trackVisible : Whether the emitter's visible state will track the follow target's visibility state.
  • emitZone :
    • Emit zone
      {\ntype: 'random',\nsource: geom,\n}            
    • Emit edge
      {\ntype: 'edge',\nsource: curve,\n\nquantity: 1,\nstepRate: 0,\nyoyo: false,\nseamless: true\n}            
  • deathZone
    {\ntype: 'onEnter', // 'onEnter', or 'onLeave'\nsource: geom\n}\n
  • bounds : {x, y, w, h}, or {x, y, width, height}, or Rectangle.
  • collideLeft, collideRight, collideTop, collideBottom : Whether particles interact with the left/right/top/bottom edge of the bounds.
  • name
  • particleClass
"},{"location":"particles/#control","title":"Control","text":"
  • Start
    emitter.start();\n// emitter.start(advance, duration);\n
    • advance : Advance this number of ms in time through the emitter.
    • duration : Limit this emitter to only emit particles for the given number of ms. Setting this parameter will override any duration already set in the Emitter configuration object.
  • Stop
    emitter.stop();\n// emitter.stop(kill);\n
    • kill :
      • true : Kill all particles immediately
      • false : Leave them to die after their lifespan expires. Default behavior.
  • Pause
    emitter.pause();  // set `active` to false\n
  • Resume
    emitter.resume();  // set `active` to true\n
  • Starts (or restarts) a particle flow.
    emitter.flow(frequency, count, stopAfter);\n
    • frequency :
      • >= 0 : The time interval of each flow cycle, in ms
      • -1 : Explosion mode.
    • count : The number of particles to emit at each flow cycle.
    • stopAfter : Stop this emitter from firing any more particles once this value is reached.
      • Setting this parameter will override any stopAfter value already set in the Emitter configuration object.
      • 0 : Unlimited
  • Explode : Puts the emitter in explode mode (frequency = -1), stopping any current particle flow, and emits several particles all at once.
    emitter.explode();\n// emitter.explode(count, x, y);\n
    • count : The number of Particles to emit.
    • x, y : The x, y coordinate to emit the Particles from.
  • Emit : Emits particles at the given position. If no position is given, it will emit from this Emitters current location.
    emitter.emitParticleAt();\n// emitter.emitParticleAt(x, y, count);    \n
    or
    emitter.emitParticle(count, x, y);\n
    • count : The number of Particles to emit.
    • x, y : The x, y coordinate to emit the Particles from.
  • Fast forward
    emitter.fastForward(time, delta);\n
    • time : The number of ms to advance the Particle Emitter by.
    • delta : The amount of delta to use for each step. Defaults to 1000 / 60.
  • Kill all alive particles
    emitter.killAll()\n
"},{"location":"particles/#follow-target","title":"Follow target","text":"
  • Start
    emitter.startFollow(target);\n// emitter.startFollow(target, offsetX, offsetY, trackVisible);\n
    • target : The Game Object to follow.
    • offsetX, offsetY : Horizontal/vertical offset of the particle origin from the Game Object.
    • trackVisible : Whether the emitter's visible state will track the target's visible state.
  • Stop
    emitter.stopFollow();\n
"},{"location":"particles/#frame","title":"Frame","text":"

emitter.setEmitterFrame(frames);\n// emitter.setEmitterFrame(frames, pickRandom, quantity);\n
- frames : One or more texture frames, or a configuration object. - String or number value - Array of string or number value - Configuration object :
{\nframes: [],\ncycle: false,\nquantity: 1\n}\n
- pickRandom : - true : Whether frames should be assigned at random from frames. Default behavior. - quantity : The number of consecutive particles that will receive each frame. Default value is 1.

"},{"location":"particles/#animation","title":"Animation","text":"

emitter.setAnim(anims);\n// emitter.setAnim(anims, pickRandom, quantity);\n
- anims : One or more animations, or a configuration object. - String - Array of string - Configuration object :
{\nanims: [],\ncycle: false,\nquantity: 1\n}\n
- anims : One or more animations names, or Play Animation Config objects. - String - Array of string - Animation config - Array of Animation config - pickRandom : - true : Whether frames should be assigned at random from frames. Default behavior. - quantity : The number of consecutive particles that will receive each frame. Default value is 1.

"},{"location":"particles/#particle","title":"Particle","text":"
  • Speed
    emitter.setParticleSpeed(x, y);\n
    or
    emitter.speedX = x;\nemitter.speedY = y;\n
    • Changes the emitter from radial to a point emitter
  • Bounce
    emitter.bounce = value;\n
    • 0 : No bounce
    • 1 : Full rebound
  • Max velocity
    emitter.maxVelocityX = x;\nemitter.maxVelocityY = y;\n
  • Gravity
    emitter.setParticleGravity(x, y);\n
    or
    emitter.gravityX = x;\nemitter.gravityY = y;\n
  • Acceleration
    emitter.accelerationX = x;\nemitter.accelerationY = y;\n
  • Lifespan : Sets the lifespan of newly emitted particles in milliseconds.
    emitter.setParticleLifespan(time);\n
    or
    emitter.lifespan = time\n
  • The number of milliseconds to wait after emission before the particles start updating.
    emitter.delay = time;\n
  • The number of milliseconds to wait after a particle has finished its life before it will be removed.
    emitter.hold = time;\n
  • Tint
    emitter.setParticleTint(tint);\n
    or
    emitter.particleTint = tint;\n
    • Webgl only
  • Color
    emitter.particleColor = color;   // WebGL only.\nemitter.colorEase = easeName;\n
    • Webgl only
  • Alpha
    emitter.setParticleAlpha(alpha);\n
    or
    emitter.setAlpha(alpha);\n
    or
    emitter.particleAlpha = alpha;\n
  • Scale : Sets the vertical and horizontal scale of the emitted particles.
    emitter.setParticleScale(x, y);\n
    or
    emitter.setScale(x, y);\n
    or
    emitter.particleScaleX = x;\nemitter.particleScaleY = y;\n
  • Position
    emitter.particleX = x;\nemitter.particleY = y;\n
  • Position to move toward
    emitter.moveToX = x;\nemitter.moveToY = y;\n
  • The angle at which the particles are emitted.
    emitter.particleAngle = angle;  // degrees    \n
  • The rotation (or angle) of each particle when it is emitted.
    emitter.particleRotate = rotation; // degrees\n
  • The number of particles that are emitted each time an emission occurs
    emitter.quantity = quantity;\n
  • Hard limit the amount of particle objects
    var count = emitter.maxParticles;\n
    • Whether this emitter is at its limit
      var atLimit = emitter.atLimit();\n
  • Alive (active) particles
    • Amount of alive particles
      var count = emitter.getAliveParticleCount();\n
      or
      var count = emitter.alive.length;\n
    • Add callback for newly emitted particle
      var callback = function(particle, emitter) { /* ... */ }\nemitter.onParticleEmit(callback, context);\n
      • Clear callback
        emitter.onParticleEmit();\n
    • For each alive particle
      var callback = function(particle, emitter) { /* ... */ }\nemitter.forEachAlive(callback, context);\n
  • Dead (inactive) particles
    • Amount of dead particles
      var count = emitter.getDeadParticleCount();\n
      or
      var count = emitter.dead.length;\n
    • Add callback for each particle death
      var callback = function(particle, emitter) { /* ... */ }\nemitter.onParticleDeath(callback, context);\n
      • Clear callback
        emitter.onParticleDeath();\n
    • For each dead particle
      var callback = function(particle, emitter) { /* ... */ }\nemitter.forEachDead(callback, context);\n
    • Add dead particles into pool
      emitter.reserve(count);\n
  • Total (alive + dead) number of particles.
    var count = emitter.getParticleCount();\n
  • Active particles overlaps with a Rectangle Geometry object or an Arcade Physics Body.
    var particles = emitter.overlap(target);\n
    • target :
      • A Rectangle.
      • Arcade Physics Body.
    • particles : An array of Particles that overlap with the given target
  • Gets a bounds Rectangle calculated from the bounds of all currently active Particles
    emitter.getBounds(padding, advance, delta, output);\n
    • padding : The amount of padding, in pixels, to add to the bounds Rectangle.
    • advance, delta : Fast forward in time to try and allow the bounds to be more accurate.
    • output : The Rectangle to store the results in.
  • Gets the bounds of this particle as a Geometry Rectangle
    particle.getBounds();\n
"},{"location":"particles/#render-order","title":"Render order","text":"
  • Sort by property
    emitter.setSortProperty(property, ascending);\n
    • property : The property on the Particle class to sort by.
    • ascending : Should the particles be sorted in ascending or descending order?
  • Sort by callback
    var callback = function(particleA, particleB) {\nreturn 1; // 0,1,-1\n}\nemitter.setSortCallback(callback);\n
"},{"location":"particles/#emitter","title":"Emitter","text":"
  • Frequency
    emitter.setFrequency(frequency);\n// emitter.setFrequency(frequency, quantity);\n
    • frequency :
      • >= 0 : The time interval of each flow cycle, in ms
      • -1 : Explosion mode.
    • quantity : The number of particles to release at each flow cycle or explosion.
  • Quantity
    emitter.setQuantity(quantity);\n
    • quantity : The number of particles to release at each flow cycle or explosion.
"},{"location":"particles/#zone","title":"Zone","text":""},{"location":"particles/#emit-zone","title":"Emit zone","text":""},{"location":"particles/#add-emit-zone","title":"Add emit zone","text":"
var zone = emitter.addEmitZone({\ntype: 'random',\nsource: geom,\n});\n
  • source : Geom like Circle, Ellipse, Rectangle,Triangle, Polygon, BitmapZone, or Path or Curve, which has getRandomPoint(point) method
    • Custom zone
      {\ngetRandomPoint: function(point) {\n// point.x = ...\n// point.y = ...\nreturn point;\n}\n}\n
"},{"location":"particles/#add-emit-edge","title":"Add emit edge","text":"
var zone = emitter.addEmitZone({\ntype: 'edge',\nsource: curve,\n\nquantity: 1,\nstepRate: 0,\nyoyo: false,\nseamless: true,\ntotal: -1\n});\n
  • source : Geom like Circle, Ellipse, Rectangle,Triangle, Polygon, or Path or Curve, which has getPoints(quantity, stepRate) method
    • Custom edge
      {\ngetPoints: function(quantity, stepRate) {\n// output = [point0, point1, ...];  // point: Phaser.Math.Vector2, or {x, y}\nreturn output;\n}\n}\n
  • quantity : The number of particles to place on the source edge. Set to 0 to use stepRate instead.
  • stepRate : The distance between each particle. When set, quantity is implied and should be set to 0.
  • yoyo : Whether particles are placed from start to end and then end to start. Default is false.
  • seamless : Whether one endpoint will be removed if it's identical to the other. Default is true.
  • total : The total number of particles this zone will emit before passing over to the next emission zone in the Emitter.

quantity or stepRate

  • Any geometry like circle, ellipse, kine, polygon, rectangle, triangle source has quantity, or stepRate
  • Curve source has quantity, or stepRate
  • Path source only has quantity
"},{"location":"particles/#set-emit-zone","title":"Set emit zone","text":"
emitter.setEmitZone(zone);\n
  • zone : The Emit Zone to set as the active zone.
    • A zone object
    • A number as index
"},{"location":"particles/#zone-source","title":"Zone source","text":"
  • Get
    // var zone = emitter.emitZones[i];\nvar source = zone.source;    
  • (Edge type only) Update points of curve source
    zone.updateSource();\n
  • (Edge type only) Set source to another curve, also update points
    zone.changeSource(curve);\n
"},{"location":"particles/#remove-emit-zone","title":"Remove emit zone","text":"
emitter.removeEmitZone(zone)\n
"},{"location":"particles/#clear-emit-zone","title":"Clear emit zone","text":"

emitter.clearEmitZones();\n
or
emitter.emitZones.length = 0;\nemitter.zoneIndex = 0;\n

"},{"location":"particles/#death-zone","title":"Death zone","text":"
var zone = emitter.addDeathZone({\ntype: 'onEnter',\nsource: geom\n});\n
  • type : 'onEnter' or 'onLeave'
  • source : Geom like Circle, Ellipse, Rectangle,Triangle, Polygon
    • Custom source :
      {\ncontains: function (x, y) {\n// ...\nreturn bool;\n}\n}\n
"},{"location":"particles/#remove-death-zone","title":"Remove death zone","text":"
emitter.removeDeathZone(zone)\n
"},{"location":"particles/#clear-death-zone","title":"Clear death zone","text":"

emitter.clearDeathZones();\n
or
emitter.deathZones.length = 0;\n

"},{"location":"particles/#update-configuration","title":"Update Configuration","text":"
emitter.updateConfig(config)\n
  • config : See config parameter in constructor.
"},{"location":"particles/#events","title":"Events","text":"
  • Starts emission of particles.
    emitter.on('start', function(emitter) {\n\n})\n
  • Explodes a set of particles.
    emitter.on('explode', function(emitter, particle) {\n\n})\n
  • Death Zone kills a Particle instance.
    emitter.on('deathzone', function(emitter, particle, zone) {\n\n})\n
  • Stops emission
    emitter.on('stop', function(emitter) {\n\n})\n
    • Directly call the ParticleEmitter.stop method.
    • Stop after a set time via the duration property.
    • Stop after a set number of particles via the stopAfter property.
  • Complete Event, no particles are still rendering at this point in time.
    emitter.on('complete', function(emitter) {\n\n})\n
"},{"location":"particles/#bounds","title":"Bounds","text":"
  • Add bounds
    var bounds = emitter.addParticleBounds(x, y, width, height);\n// var bounds = emitter.addParticleBounds(x, y, width, height, collideLeft, collideRight, collideTop, collideBottom);\n
    or
    var bounds = emitter.addParticleBounds(rect);\n
    • x, y, width, height, {x, y, width, height}, or {x, y, w, h}, or Rectangle : Bounds
    • collideLeft, collideRight, collideTop, collideBottom : Whether particles interact with the left/right/top/bottom edge of the bounds.
  • Collide edges
    bounds.collideLeft = enabled;\nbounds.collideRight = enabled;\nbounds.collideTop = enabled;\nbounds.collideBottom = enabled;\n
  • Bound rectangle
    var rect = bounds.bounds;\n
    • rect : Rectangle
"},{"location":"particles/#gravity-well","title":"Gravity well","text":"
  • Create a gravity well
    var well = particles.createGravityWell({\n// x: 0,\n// y: 0,\n// power: 0,\n// epsilon: 100,\n// gravity: 50\n});\n
  • Enable
    • Active
      well.active = true;\n
    • Inactive
      well.active = false;\n
  • Position
    well.x = x;\nwell.y = y;\n
  • Gravity
    well.gravity = value;\n
  • Power
    well.power = value;\n
"},{"location":"particles/#custom-particle-processor","title":"Custom Particle Processor","text":"
  • Declare Particle Processor class
    class MyParticleProcessor extends Phaser.GameObjects.Particles.ParticleProcessor {\nconstructor() {\nsuper(x, y, active);\n// ...\n}\n\nupdate(particle, delta, step, t) {\n// particle : The Particle to update.\n// delta : The delta time in ms.\n// step : The delta value divided by 1000.\n// t : The current normalized lifetime of the particle, between 0 (birth) and 1 (death).\n}\n\ndestroy() {\nsuper.destroy();\n}\n}\n
    • Override update method
  • Add to emitter
    var myParticleProcessor = emitter.addParticleProcessor(new MyParticleProcessor);\n
"},{"location":"particles/#custom-particle-class","title":"Custom particle class","text":"
class MyParticle extends Phaser.GameObjects.Particles.Particle {\nconstructor (emitter) {\nsuper(emitter);\n/* ... */\n}\n\nupdate (delta, step, processors) {\nsuper.update(delta, step, processors);\n/* ... */\n}\n}\n
"},{"location":"particles/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"particles/#create-mask","title":"Create mask","text":"
var mask = emitter.createBitmapMask();\n

See mask

"},{"location":"particles/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"path/","title":"Path","text":""},{"location":"path/#introduction","title":"Introduction","text":"

Path in curves, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"path/#usage","title":"Usage","text":""},{"location":"path/#add-path-object","title":"Add path object","text":"
var path = scene.add.path();\n// var path = scene.add.path(x, y);  // curve start from (x, y)\n

or

var path = new Phaser.Curves.Path();\n// var path = new Phaser.Curves.Path(x, y);  // curve start from (x, y)\n
"},{"location":"path/#add-path-object-with-curves","title":"Add path object with curves","text":"

Curves in JSON

var path = scene.add.path(json);\n
or
var path = new Phaser.Curves.Path(json);\n

"},{"location":"path/#add-curve","title":"Add curve","text":""},{"location":"path/#line","title":"Line","text":"
  • Add line object
    1. Create line object
      var curve = new Phaser.Curves.Line({x: x0, y: y0}, {x: x1, y: y1});\n
      or
      var curve = new Phaser.Curves.Line([x0, y0, x1, y1]);\n
    2. Add to path
      path.add(curve);\n
  • Add line started from previous end point to next point
    path.lineTo(endX, endY);\n
    or
    path.lineTo(new Phaser.Math.Vector2({x, y}));\n

Properties:

  • curve.p0 : The first endpoint.
    • curve.p0.x, curve.p0.y
  • curve.p1 : The second endpoint.
    • curve.p1.x, curve.p1.y
"},{"location":"path/#circleellipsearc","title":"Circle/ellipse/arc","text":"
  • Add circle/ellipse/arc object
    1. Create circle/ellipse/arc object
      • Circle
        var curve = new Phaser.Curves.Ellipse(x, y, radius);\n
      • Ellipse
        var curve = new Phaser.Curves.Ellipse(x, y, xRadius, yRadius);\n
      • Arc
        var curve = new Phaser.Curves.Ellipse(x, y, xRadius, yRadius, startAngle, endAngle, clockwise,     rotation);\n
    2. Add to path
      path.add(curve);\n
  • Add circle/ellipse/arc started from previous end point to next point
    • Circle
      path.circleTo(radius);\n
    • Ellipse
      path.ellipseTo(xRadius, yRadius);\n
    • Arc
      path.ellipseTo(xRadius, yRadius, startAngle, endAngle, clockwise, rotation);\n

Properties:

  • curve.p0 : Center point.
    • curve.p0.x, curve.p0.y
  • curve.xRadius, curve.yRadius : Horizontal/vertical radiuse.
  • curve.startAngle, curve.endAngle : Start/end angle, in degrees.
  • curve.clockwise : true if Clockwise, false if anti-clockwise.
  • curve.angle : Rotation, in degrees.
    • curve.rotation : Rotation, in radians.
"},{"location":"path/#spline","title":"Spline","text":"
  • Add spline object
    1. Create spline object
      var curve = new Phaser.Curves.Spline([\np0,            // {x, y}, or [x, y]\np1,            // {x, y}, or [x, y]\n// ...\n]);\n
      or
      var curve = new Phaser.Curves.Spline([\nx0, y0,\nx1, y1,\n// ...\n]);\n
    2. Add to path
      path.add(curve);\n
  • Add spline started from previous end point to next point
    var points = ;\npath.splineTo([\np0,            // {x, y}, or [x, y]\np1,            // {x, y}, or [x, y]\n// ...\n]);\n
    or
    path.splineTo([\nx0, y0,\nx1, y1,\n// ...\n]);\n
"},{"location":"path/#append-point","title":"Append point","text":"
var point = curve.addPoint(x, y);\n
"},{"location":"path/#quadratic-bezier-curve","title":"Quadratic bezier curve","text":"
  1. Create quadratic bezier curve object
    var curve = new Phaser.Curves.QuadraticBezier(startPoint, controlPoint, endPoint); // point: {x, y}\n
    or
    var points = [\nx0, y0,     // start point\nx1, y1,     // control point\nx2, y2      // end point\n];\nvar curve = new Phaser.Curves.QuadraticBezier(points);\n
  2. Add to path
    path.add(curve);\n

Add quadratic bezier curve started from previous end point to next point

path.quadraticBezierTo(endX, endY, controlX, controlY);\n
or
path.quadraticBezierTo(endPoint, controlPoint);  // point : Phaser.Math.Vector2\n

"},{"location":"path/#cubic-bezier-curve","title":"Cubic bezier curve","text":"
  1. Create quadratic bezier curve object
    var curve = new Phaser.Curves.CubicBezier(startPoint, controlPoint1, controlPoint2, endPoint); // point: {x, y}\n
    or
    var points = [\nx0, y0,     // start point\nx1, y1,     // control point1\nx2, y2,     // control point2\nx3, y3      // end point\n];\nvar curve = new Phaser.Curves.CubicBezier(points);\n
  2. Add to path
    path.add(curve);\n

Add cubic bezier curve started from previous end point to next point

path.cubicBezierTo(endX, endY, control1X, control1Y, control2X, control2Y);\n
or
path.cubicBezierTo(endPoint, controlPoint1, controlPoint2);  // point : Phaser.Math.Vector2\n

"},{"location":"path/#move-to-point","title":"Move to point","text":"
path.moveTo(x, y);\n
"},{"location":"path/#add-curves-from-json","title":"Add curves from JSON","text":"
path.fromJSON(json);\n
"},{"location":"path/#get-curves","title":"Get curves","text":"
var curves = path.curves;\n
"},{"location":"path/#get-curve-at-t","title":"Get curve at t","text":"
var curve = path.getCurveAt(t);\n
  • t : The normalized location on the Path. Between 0 and 1
"},{"location":"path/#draw-on-graphics","title":"Draw on graphics","text":"
path.draw(graphics);\n// path.draw(graphics, pointsTotal);\n
  • pointsTotal : The number of points to draw for each Curve.

or

curve.draw(graphics);\n// curve.draw(graphics, pointsTotal);\n
  • pointsTotal : The resolution of the curve.
"},{"location":"path/#point","title":"Point","text":"
  • Get point
    var out = path.getPoint(t);  // t: 0 ~ 1\n// var out = path.getPoint(t, out);  // modify out\n
    or
    var out = curve.getPoint(t);  // t: 0 ~ 1\n// var out = curve.getPoint(t, out);  // modify out\n
    Distance of path from start point to target point (out) might not linear with t.
  • Get random point
    var out = path.getRandomPoint();\n// var out = path.getRandomPoint(out);  // modify out\n
    or
    var out = curve.getRandomPoint();\n// var out = curve.getRandomPoint(out);  // modify out\n
  • Get n points
    • Path
      var points = path.getPoints(divisions);\n
      • divisions : The number of divisions per resolution per curve.
    • Curve
      var points = curve.getPoints(divisions);\n// var points = curve.getPoints(divisions, undefined, out);\n
      or
      var points = curve.getPoints(undefined, stepRate);\n// var points = curve.getPoints(undefined, stepRate, out);\n
      • divisions : The number of divisions in this curve.
        1. divisions, if divisions > 0, else
        2. this.getLength / stepRate, if stepRate > 0, else
        3. defaultDivisions
      • points : Return 1 + divisions points.
  • Get (n+1) points equally spaced out along the curve
    var points = path.getSpacedPoints(n);\n
    or
    var points = curve.getSpacedPoints(n);\n// var points = curve.getSpacedPoints(undefined, stepRate);\n// var points = curve.getSpacedPoints(divisions, stepRate, out);\n
  • Get points spaced out n distance pixels apart
    var points = curve.getDistancePoints(n)\n
    The smaller the distance, the larger the array will be. Path object does NOT support this feature yet.
  • Get start point
    var out = path.getStartPoint();\n// var out = path.getStartPoint(out);  // modify out\n
    or
    var out = curve.getStartPoint();\n// var out = curve.getStartPoint(out);  // modify out\n
  • Get end point
    var out = path.getEndPoint();\n// var out = path.getEndPoint(out);  // modify out\n
    or
    var out = curve.getEndPoint();\n// var out = curve.getEndPoint(out);  // modify out\n
  • Get t (0~1) from distance
    var t = curve.getTFromDistance(d);\n
    Path object does NOT support this feature yet.
  • Get tangent
    var out = path.getTangent(t);  // t: 0~1\n// var out = path.getTangent(t, out);  // modify out\n
    or
    var out = curve.getTangent(t);  // t: 0~1\n// var out = curve.getTangent(t, out);  // modify out\n
"},{"location":"path/#length-of-path","title":"Length of path","text":"

var l = path.getLength();\n
or
var l = curve.getLength();\n

Length of path/curve will be cached.

"},{"location":"path/#update-length","title":"Update length","text":"

path.updateArcLengths();\n
or
curve.updateArcLengths();\n

"},{"location":"path/#curves-to-json","title":"Curves to JSON","text":"

var json = path.toJSON();\n
or
var json = curve.toJSON();\n

"},{"location":"path/#bounds","title":"Bounds","text":"

Get bounds

var out = path.getBounds();    // accuracy = 16\n// var out = path.getBounds(out);\n// var out = path.getBounds(out, accuracy);\n
or
var out = curve.getBounds();    // accuracy = 16\n// var out = curve.getBounds(out);\n// var out = curve.getBounds(out, accuracy);\n

  • out : A rectangle object
"},{"location":"path/#destroy","title":"Destroy","text":"
path.destroy();\n
"},{"location":"pathfollower/","title":"Path follower","text":""},{"location":"pathfollower/#introduction","title":"Introduction","text":"

Set position of game object on a path.

  • Author: Rex
  • Behavior of game object
"},{"location":"pathfollower/#live-demos","title":"Live demos","text":"
  • Path follower
  • Spaced points
"},{"location":"pathfollower/#usage","title":"Usage","text":"

Sample code

"},{"location":"pathfollower/#install-plugin","title":"Install plugin","text":""},{"location":"pathfollower/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexpathfollowerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexpathfollowerplugin.min.js', true);\n
  • Add path-follower behavior
    var pathFollower = scene.plugins.get('rexpathfollowerplugin').add(gameObject, config);\n
"},{"location":"pathfollower/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PathFollowerPlugin from 'phaser3-rex-plugins/plugins/pathfollower-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPathFollower',\nplugin: PathFollowerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add path-follower behavior
    var pathFollower = scene.plugins.get('rexPathFollower').add(gameObject, config);\n
"},{"location":"pathfollower/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import PathFollower from 'phaser3-rex-plugins/plugins/pathfollower.js';\n
  • Add path-follower behavior
    var pathFollower = new PathFollower(gameObject, config);\n
"},{"location":"pathfollower/#create-instance","title":"Create instance","text":"
// var path = scene.add.path();\nvar pathFollower = scene.plugins.get('rexPathFollower').add(gameObject, {\n// path: path,          // path object\n// t: 0,                // t: 0~1\n// rotateToPath: false,\n// rotationOffset: 0,\n// angleOffset: 0,\n\n// spacedPoints: false,\n// spacedPoints: {\n//     divisions: undefined,\n//     stepRate: 10,\n// }\n\n});\n
  • path : Path object
  • t : Initial value of property t (0~1)
  • rotateToPath: Set true to change angle towards path
  • rotationOffset : Rotation offset in radian, or angleOffset in degrees
  • spacedPoints :
    • false, or undefined : Get point by path.getPoint(t)
    • spacedPoints.divisions, spacedPoints.stepRate :
      1. Get points by path.getSpacedPoints(divisions, stepRate)
      2. Get point from linear interpolation of points in step1.
"},{"location":"pathfollower/#move-along-path","title":"Move along path","text":"

Set pathFollower.t (0~1) to move along path

pathFollower.t = t;  // t: 0~1\n// pathFollower.setT(t);\n

or tween pathFollower.t

var tween = scene.tweens.add({\ntargets: pathFollower,\nt: 1,\nease: 'Linear', // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\nrepeat: 0,\nyoyo: false\n});\n
"},{"location":"pathfollower/#set-path","title":"Set path","text":"
pathFollower.setPath(path);\n
"},{"location":"pathfollower/#set-rotate-to-path","title":"Set rotate-to-path","text":"
pathFollower.setRotateToPath(rotateToPath, rotationOffset);\n
  • rotateToPath : Set true to change angle towards path
  • rotationOffset : Rotation offset in radian
"},{"location":"percentage/","title":"Percentage","text":""},{"location":"percentage/#introduction","title":"Introduction","text":"

Work out what percentage value is of the range between min and max, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"percentage/#usage","title":"Usage","text":"
var result = Phaser.Math.Percent(value, min, max);\n
  • result: Percentage/t (0~1).
  • value : The value to determine the percentage of.
"},{"location":"perlin/","title":"Perlin","text":""},{"location":"perlin/#introduction","title":"Introduction","text":"

Perlin2/Perlin3 noise and simplex2/simplex3 noise. (Reference)

  • Author: Rex
  • Method only
"},{"location":"perlin/#live-demos","title":"Live demos","text":"
  • Perlin2
  • Terrain generator
"},{"location":"perlin/#usage","title":"Usage","text":"

Sample code

"},{"location":"perlin/#install-plugin","title":"Install plugin","text":""},{"location":"perlin/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperlinplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperlinplugin.min.js', true);\n
  • Add perlin noise object
    var noise = scene.plugins.get('rexperlinplugin').add(seed);\n
"},{"location":"perlin/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerlinPlugin from 'phaser3-rex-plugins/plugins/perlin-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerlin',\nplugin: PerlinPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add perlin noise object
    var noise = scene.plugins.get('rexPerlin').add(seed);\n
"},{"location":"perlin/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Perlin from 'phaser3-rex-plugins/plugins/perlin.js';\n
  • Add perlin noise object
    var noise = new Perlin(seed);\n
"},{"location":"perlin/#create-noise-instance","title":"Create noise instance","text":"
var noise = scene.plugins.get('rexPerlin').add(seed);\n
  • seed : A seed for this noise, like Math.random()
"},{"location":"perlin/#perlin","title":"Perlin","text":"
  • Perlin2
    var value = noise.perlin2(x, y);\n
    • value : -1 ~ 1
  • Perlin3
    var value = noise.perlin3(x, y, z);\n
    • value : -1 ~ 1
"},{"location":"perlin/#simplex","title":"Simplex","text":"
  • Simplex2
    var value = noise.simplex2(x, y);\n
    • value : -1 ~ 1
  • Simplex3
    var value = noise.simplex3(x, y, z);\n
    • value : -1 ~ 1
"},{"location":"perlin/#set-seed","title":"Set seed","text":"
noise.setSeed(seed);\n
"},{"location":"perspective-card/","title":"Card","text":""},{"location":"perspective-card/#introduction","title":"Introduction","text":"

A container with two perspective-images.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"perspective-card/#live-demos","title":"Live demos","text":"
  • Flip card
  • Label front face
  • Change texture
"},{"location":"perspective-card/#usage","title":"Usage","text":"

Sample code

"},{"location":"perspective-card/#install-plugin","title":"Install plugin","text":""},{"location":"perspective-card/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add card object
    var card = scene.add.rexPerspectiveCard(config);\n
"},{"location":"perspective-card/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add card object
    var card = scene.add.rexPerspectiveCard(config);\n
"},{"location":"perspective-card/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveCard } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add card object
    var card = new PerspectiveCard(scene, config);\nscene.add.existing(card);\n
"},{"location":"perspective-card/#create-instance","title":"Create instance","text":"
var card = scene.add.rexPerspectiveCard({\nx: 0, y: 0,\n\nback: {key, frame},\nfront: {key, frame},\nface: 0,\n\norientation: 0,\n\n// width,\n// height,\n\n// flip : {\n//     frontToBack: 0,\n//     backToFront: 1,\n//     duration: 1000,\n//     ease: 'Cubic',\n//     delay: 0,\n// }\n// flip: false\n});\n
  • front, back : Perspective image game object for front and back face.
    • {key, frame} : Texture key and frame name, to create perspective image
    • {width, height} : Width and height, to create perspective render texture.
    • Perspective image
    • Perspective render texture
  • face : Show front or back face.
    • 'front', or 0 : Show front face.
    • 'back', or 1 : Show back face.
  • orientation : Flipping orientation.
    • 'horizontal','h', 'x', or 0 : Flipping left-to-right, or right-to-left.
    • 'vertical','v', 'y', or 1 : Flipping top-to-bottom, or bottom-to-top.
  • width, height : Specific width and height of this card container.
    • undefined : Use width and height of front and back face.
  • flip : Configuration of flipping behavior.
    • flip.frontToBack, flip.backToFront : Flipping direction.
      • 'right', 'left-to-right', or 0 : Flipping from right to left.
      • 'left', 'right-to-left', or 1 : Flipping from left to right.
    • flip.duration : Duration of flipping, in millisecond.
    • flip.delay : Initial delay.
    • flip.ease : Ease function. Default value is 'Cubic'.
    • false : Don't add flipping behavior.

Add card from JSON

var card = scene.make.rexPerspectiveCard({\nx: 0,\ny: 0,\n\nfront,\nback,\nface: 0,\n\norientation: 0,\n\nwidth,\nheight,\n\nflip,\n\nadd: true\n});\n
"},{"location":"perspective-card/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveCard extends PerspectiveCard {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var card = new MyPerspectiveCard(scene, config);\n
"},{"location":"perspective-card/#face","title":"Face","text":"
  • Get
    var face = card.face;\n
    • face:
      • 0 : Show front face.
      • 1 : Show back face.
  • Set
    card.setFace(face)\n
    • face
      • 'front', or 0 : Show front face.
      • 'back', or 1 : Show back face.
  • Toggle
    card.toggleFace()\n
"},{"location":"perspective-card/#face-instances","title":"Face instances","text":"
  • Front face
    var frontFace = card.frontFace;\n// var frontFace = card.faces.front;\n
  • Back face
    var backFace = card.backFace;\n// var backFace = card.faces.back;\n
"},{"location":"perspective-card/#face-texture","title":"Face texture","text":"
  • Set texture of front face, assume that front face is a perspective image
    card.frontFace.setTexture(key);\n// card.frontFace.setTexture(key, frame);\n
  • Set texture of back face, assume that back face is a perspective image
    card.backFace.setTexture(key);\n// card.backFace.setTexture(key, frame);\n
"},{"location":"perspective-card/#flip-behavior","title":"Flip behavior","text":""},{"location":"perspective-card/#start-flipping","title":"Start flipping","text":"
card.flip.flip();\n// card.flip.flip(duration, repeat);\n
  • duration : Overwrite default duration value.
  • repeat : Number of flipping time (repeat + 1) during duration. Default value is 0.

or

  • Flip-right
    card.flip.flipRight();\n// card.flip.flipRight(duration, repeat);\n
  • Flip-left
    card.flip.flipLeft();\n// card.flip.flipLeft(duration, repeat);\n
"},{"location":"perspective-card/#stop-flipping","title":"Stop flipping","text":"
card.flip.stop();\n
"},{"location":"perspective-card/#set-duration","title":"Set duration","text":"
card.flip.setDuration(duration);\n// card.flip.duration = duration;\n
"},{"location":"perspective-card/#set-ease","title":"Set ease","text":"
card.flip.setEase(ease);\n// card.flip.ease = ease;\n
"},{"location":"perspective-card/#events","title":"Events","text":"
  • On flipping start
    card.flip.on('start', function(flip, card){\n// ...\n});\n
  • On flipping complete
    card.flip.on('complete', function(flip, card){\n// ...\n});\n
"},{"location":"perspective-card/#status","title":"Status","text":"
  • Is flipping
    var isRunning = card.flip.isRunning;\n
"},{"location":"perspective-card/#rotation","title":"Rotation","text":"
  • Get rotation angle
    var angleX = card.angleX; // Angle in degrees\nvar angleY = card.angleY; // Angle in degrees\nvar angleZ = card.angleZ; // Angle in degrees\n
    or
    var rotationX = card.rotationX; // Angle in radians\nvar rotationY = card.rotationY; // Angle in radians\nvar rotationZ = card.rotationZ; // Angle in radians\n
  • Set rotation angle
    card.angleX = angleX; // Angle in degrees\ncard.angleY = angleY; // Angle in degrees\ncard.angleZ = angleZ; // Angle in degrees\n
    or
    card.rotationX = rotationX; // Angle in radians\ncard.rotationY = rotationY; // Angle in radians\ncard.rotationZ = rotationZ; // Angle in radians\n
"},{"location":"perspective-card/#debug","title":"Debug","text":"
  1. Set debug Graphics
    var debugGraphics = scene.add.graphics();\ncard.setDebug(debugGraphics);\n
  2. Update Graphics in scene.update() method.
    debugGraphics.clear();\ndebugGraphics.lineStyle(1, 0x00ff00);\n
"},{"location":"perspective-card/#other-properties","title":"Other properties","text":"

See container, Mesh game object, game object

"},{"location":"perspective-card/#create-mask","title":"Create mask","text":"
var mask = card.createBitmapMask();\n

See mask

"},{"location":"perspective-card/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"perspective-carousel/","title":"Carousel","text":""},{"location":"perspective-carousel/#introduction","title":"Introduction","text":"

A container with cards.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"perspective-carousel/#live-demos","title":"Live demos","text":"
  • Carousel
  • List
  • UI cards
"},{"location":"perspective-carousel/#usage","title":"Usage","text":"

Sample code

"},{"location":"perspective-carousel/#install-plugin","title":"Install plugin","text":""},{"location":"perspective-carousel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add carousel object
    var carousel = scene.add.rexPerspectiveCarousel(config);\n
"},{"location":"perspective-carousel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add carousel object
    var carousel = scene.add.rexPerspectiveCarousel(config);\n
"},{"location":"perspective-carousel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveCarousel } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add carousel object
    var carousel = new PerspectiveCarousel(scene, config);\nscene.add.existing(carousel);\n
"},{"location":"perspective-carousel/#create-instance","title":"Create instance","text":"
var carousel = scene.add.rexPerspectiveCarousel({\nx: 0, y: 0,\n\nfaces: [],\n// face: 0,\n// rtl: false,\n\n// width,\n// height,\n\n// faceWidth,\n// faceSpace: 0,\n\n// z: 1,\n// zEnd: 0,\n\n// roll : {\n//     duration: 1000,\n//     ease: 'Cubic',\n//     delay: 0,\n// }\n});\n
  • faces : Array of perspective-card, perspective-rendertexture, perspective-image, or null.
    • Assume that all faces have the same size
  • face : Index or name of current face (face at angle 0).
  • rtl
    • false : Place faces from left to right. Default behavior.
    • true : Place faces from right to left.
  • width, height : Specific width and height of this carousel container.
    • undefined : Use width and height of first face.
  • faceWidth : Width of face.
    • undefined : Use width of face. Assume that all faces have the same size.
  • faceSpace : Extra space of face width. Used when faceWidth is undefined.
  • z, zEnd : Range of faces' z-index. Default value is 1/0.
  • roll : Configuration of rolling behavior.
    • roll.duration : Duration of rolling, in millisecond.
    • roll.delay : Initial delay.
    • roll.ease : Ease function. Default value is 'Cubic'.
    • false : Don't add rolling behavior.

Add carousel from JSON

var carousel = scene.make.rexPerspectiveCarousel({\nx: 0,\ny: 0,\n\nfaces: [],\n\n// width,\n// height,\n\n// faceWidth,\n// faceSpace: 0,\n\n// z: 1,\n// zEnd: 0,\n\nadd: true\n});\n
"},{"location":"perspective-carousel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveCarousel extends PerspectiveCarousel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var carousel = new MyPerspectiveCarousel(scene, config);\n
"},{"location":"perspective-carousel/#face-instances","title":"Face instances","text":"
var faces = carousel.faces;\n
  • faces : Array of face instances.
"},{"location":"perspective-carousel/#face","title":"Face","text":"
  • Get
    var face = carousel.face;\n
    • face: Index of carousel.faces.
  • Set
    carousel.setFace(face)\n
    • face : Index or name of current face (face at angle 0).
"},{"location":"perspective-carousel/#roll-behavior","title":"Roll behavior","text":""},{"location":"perspective-carousel/#start-rolling","title":"Start rolling","text":"
  • Roll to next face
    carousel.roll.toNext(duration);\n
    • duration : Overwrite default duration value.
  • Roll to previous face
    carousel.roll.toPrevious(duration);\n
    • duration : Overwrite default duration value.
  • Roll to right face
    carousel.roll.toRight(duration);\n
    • duration : Overwrite default duration value.
  • Roll to left face
    carousel.roll.toLeft(duration);\n
    • duration : Overwrite default duration value.
  • Roll to face
    carousel.roll.to(faceIndex, duration);\n
    • faceIndex :
      • A number : Index of face in carousel.faces
      • A string : Name of face (face.setName(name))
    • duration : Overwrite default duration value.
"},{"location":"perspective-carousel/#stop-flipping","title":"Stop flipping","text":"
carousel.roll.stop();\n
"},{"location":"perspective-carousel/#set-duration","title":"Set duration","text":"
carousel.roll.setDuration(duration);\n// carousel.roll.duration = duration;\n
"},{"location":"perspective-carousel/#set-ease","title":"Set ease","text":"
carousel.roll.setEase(ease);\n// carousel.roll.ease = ease;\n
"},{"location":"perspective-carousel/#events","title":"Events","text":"
  • On rolling complete
    carousel.roll.on('complete', function(){\n// ...\n});\n
"},{"location":"perspective-carousel/#status","title":"Status","text":"
  • Is rolling
    var isRunning = carousel.roll.isRunning;\n
"},{"location":"perspective-carousel/#rotation","title":"Rotation","text":"
  • Get rotation angle
    var angleY = carousel.angleY; // Angle in degrees\n
    or
    var rotationY = carousel.rotationY; // Angle in radians\n
  • Set rotation angle
    carousel.angleY = angleY; // Angle in degrees\n
    or
    carousel.rotationY = rotationY; // Angle in radians\n
"},{"location":"perspective-carousel/#other-properties","title":"Other properties","text":"

See container, Mesh game object, game object

"},{"location":"perspective-carousel/#create-mask","title":"Create mask","text":"
var mask = carousel.createBitmapMask();\n

See mask

"},{"location":"perspective-carousel/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"perspective-image/","title":"Image","text":""},{"location":"perspective-image/#introduction","title":"Introduction","text":"

Image with perspective rotation.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"perspective-image/#live-demos","title":"Live demos","text":"
  • Flip image
"},{"location":"perspective-image/#usage","title":"Usage","text":"

Sample code

"},{"location":"perspective-image/#install-plugin","title":"Install plugin","text":""},{"location":"perspective-image/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexPerspectiveImage(x, y, texture, frame, config);\n
"},{"location":"perspective-image/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexPerspectiveImage(x, y, texture, frame, config);\n
"},{"location":"perspective-image/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveImage } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add image object
    var image = new PerspectiveImage(scene, x, y, texture, frame, config);\nscene.add.existing(image);\n
"},{"location":"perspective-image/#create-instance","title":"Create instance","text":"
var image = scene.add.rexPerspectiveImage(x, y, texture, frame, {\n// hideCCW: true,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

or

var image = scene.add.rexPerspectiveImage({\n// x: 0,\n// y: 0,\nkey,\n// frame: null,\n// hideCCW: true,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

Add perspectiveimage from JSON

var perspectiveimage = scene.make.rexPerspectiveImage({\nx: 0,\ny: 0,\n\nkey: null,\nframe: null,\n\n// hideCCW: false,\n// gridWidth: 32,\n// girdHeight: 32,\n\nadd: true\n});\n
"},{"location":"perspective-image/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveImage extends PerspectiveImage {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyPerspectiveImage(scene, x, y, texture, frame, config);\n
"},{"location":"perspective-image/#transform-vertices","title":"Transform vertices","text":"

Offset then rotate all vertices.

image.transformVerts(x, y, z, rotateX, rotateY, rotateZ);\n
  • x, y, z : Offset vertices
    • z+ : Near
    • z- : Far
    • x- : Left
    • x+ : Right
    • y+ : Up
    • y- : Down
  • rotateX, rotateY, rotateZ : Rotate vertices
"},{"location":"perspective-image/#rotation","title":"Rotation","text":"
  • Get rotation angle
    var angleX = image.angleX; // Angle in degrees\nvar angleY = image.angleY; // Angle in degrees\nvar angleZ = image.angleZ; // Angle in degrees\n
    or
    var rotationX = image.rotationX; // Angle in radians\nvar rotationY = image.rotationY; // Angle in radians\nvar rotationZ = image.rotationZ; // Angle in radians\n
  • Set rotation angle
    image.angleX = angleX; // Angle in degrees\nimage.angleY = angleY; // Angle in degrees\nimage.angleZ = angleZ; // Angle in degrees\n
    or
    image.rotationX = rotationX; // Angle in radians\nimage.rotationY = rotationY; // Angle in radians\nimage.rotationZ = rotationZ; // Angle in radians\n
"},{"location":"perspective-image/#flip","title":"Flip","text":"
scene.tweens.add({\ntargets: image,\nangleY: { start: 0, to: -180}\n})\n
"},{"location":"perspective-image/#tint-color","title":"Tint color","text":"
  • Get
    var color = image.tint;\n
  • Set
    image.tint = color;\n
    or
    image.setTint(color);\n
"},{"location":"perspective-image/#texture","title":"Texture","text":"
image.setTexture(key);\n// image.setTexture(key, frame);\n
"},{"location":"perspective-image/#other-properties","title":"Other properties","text":"

See Mesh game object, game object

"},{"location":"perspective-image/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"perspective-image/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"perspective-imagecarousel/","title":"Image carousel","text":""},{"location":"perspective-imagecarousel/#introduction","title":"Introduction","text":"

Display list of images.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"perspective-imagecarousel/#live-demos","title":"Live demos","text":"
  • List
"},{"location":"perspective-imagecarousel/#usage","title":"Usage","text":"

Sample code

"},{"location":"perspective-imagecarousel/#install-plugin","title":"Install plugin","text":""},{"location":"perspective-imagecarousel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add carousel object
    var carousel = scene.add.rexPerspectiveImageCarousel(config);\n
"},{"location":"perspective-imagecarousel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add carousel object
    var carousel = scene.add.rexPerspectiveImageCarousel(config);\n
"},{"location":"perspective-imagecarousel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveImageCarousel } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add carousel object
    var carousel = new PerspectiveImageCarousel(scene, config);\nscene.add.existing(carousel);\n
"},{"location":"perspective-imagecarousel/#create-instance","title":"Create instance","text":"
var carousel = scene.add.rexPerspectiveImageCarousel({\nx: 0, y: 0,\n\nimages: [],  // Array of {key, frame}\n// index: 0,\n// rtl: false,\n// repeat: true,\n\n// width,\n// height,\n// faceCount: 4,\n\n// z: 1,\n// zEnd: 0,\n\n// roll : {\n//     duration: 1000,\n//     ease: 'Cubic',\n//     delay: 0,\n// }\n});\n
  • images : Array of textures {key, frame}
    • Assume that all textures have the same size
  • index : Index of current image.
  • rtl
    • false : Place images from left to right. Default behavior.
    • true : Place images from right to left.
  • repeat : Set true to roll to first image from last, or last to first.
  • width, height : Specific width and height of this carousel container.
    • undefined : Use width and height of first image.
  • faceCount : Faces count of this carousel. A integer which >=3.
  • z, zEnd : Range of faces' z-index. Default value is 1/0.
  • roll : Configuration of rolling behavior.
    • roll.duration : Duration of rolling, in millisecond.
    • roll.delay : Initial delay.
    • roll.ease : Ease function. Default value is 'Cubic'.
    • false : Don't add rolling behavior.

Add perspectiveimage from JSON

var perspectiveimage = scene.make.rexPerspectiveImageCarousel({\nx: 0,\ny: 0,\n\nimages: [],  // Array of {key, frame}\n// index: 0,\n// rtl: false,\n// repeat: true,\n\n// width,\n// height,\n// faceCount: 4,\n\n// z: 1,\n// zEnd: 0,\n\n// roll : {\n//     duration: 1000,\n//     ease: 'Cubic',\n//     delay: 0,\n// }\n\nadd: true\n});\n
"},{"location":"perspective-imagecarousel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveImageCarousel extends PerspectiveImageCarousel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var carousel = new MyPerspectiveImageCarousel(scene, config);\n
"},{"location":"perspective-imagecarousel/#roll-behavior","title":"Roll behavior","text":""},{"location":"perspective-imagecarousel/#start-rolling","title":"Start rolling","text":"
  • Roll to next image
    carousel.roll.toNext(duration);\n
    • duration : Overwrite default duration value.
  • Roll to previous image
    carousel.roll.toPrevious(duration);\n
    • duration : Overwrite default duration value.
  • Roll to right image
    carousel.roll.toRight(duration);\n
    • duration : Overwrite default duration value.
  • Roll to left image
    carousel.roll.toLeft(duration);\n
    • duration : Overwrite default duration value.
  • Roll to image
    carousel.roll.to(faceIndex, duration);\n
    • faceIndex :
      • A number : Index of image.
    • duration : Overwrite default duration value.
"},{"location":"perspective-imagecarousel/#set-duration","title":"Set duration","text":"
carousel.roll.setDuration(duration);\n// carousel.roll.duration = duration;\n
"},{"location":"perspective-imagecarousel/#set-ease","title":"Set ease","text":"
carousel.roll.setEase(ease);\n// carousel.roll.ease = ease;\n
"},{"location":"perspective-imagecarousel/#events","title":"Events","text":"
  • On rolling complete
    carousel.roll.on('complete', function(){\n// ...\n});\n
"},{"location":"perspective-imagecarousel/#status","title":"Status","text":"
  • Is rolling
    var isRunning = carousel.roll.isRunning;\n
"},{"location":"perspective-imagecarousel/#other-properties","title":"Other properties","text":"

See container, Mesh game object, game object

"},{"location":"perspective-imagecarousel/#create-mask","title":"Create mask","text":"
var mask = carousel.createBitmapMask();\n

See mask

"},{"location":"perspective-imagecarousel/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"perspective-imagecarousel/#compare-with-plane-game-object","title":"Compare with Plane game object","text":"
  • Size
    • Size of Plane is equal to current render size.
    • Size of PerspectiveImage is equak to texture size, like normal Image game object.
  • Animation
    • Plane hae animation feature.
    • Useing PerspectiveSprite for animation feature, PerspectiveImage does not have this feature.
  • Checkerboard
    • Plane hae checkerboard feature.
    • PerspectiveImage does not have this feature.
"},{"location":"perspective-rendertexture/","title":"Render texture","text":""},{"location":"perspective-rendertexture/#introduction","title":"Introduction","text":"

Render texture with perspective rotation.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"perspective-rendertexture/#live-demos","title":"Live demos","text":"
  • RenderTexture
"},{"location":"perspective-rendertexture/#usage","title":"Usage","text":"

Sample code

"},{"location":"perspective-rendertexture/#install-plugin","title":"Install plugin","text":""},{"location":"perspective-rendertexture/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add render texture object
    var image = scene.add.rexPerspectiveRenderTexture(x, y, width, height, config);\n
"},{"location":"perspective-rendertexture/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add render texture object
    var image = scene.add.rexPerspectiveRenderTexturege(x, y, width, height, config);\n
"},{"location":"perspective-rendertexture/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveRenderTexture } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add render texture object
    var image = new PerspectiveRenderTexture(scene, x, y, width, height, config);\nscene.add.existing(image);\n
"},{"location":"perspective-rendertexture/#create-instance","title":"Create instance","text":"
var image = scene.add.rexPerspectiveRenderTexturege(x, y, width, height, {\n// hideCCW: true,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

or

var image = scene.add.rexPerspectiveRenderTexturege({\n// x: 0,\n// y: 0,\n// width: 32,\n// height: 32,\n// hideCCW: true,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

Add prespective render texture from JSON

var image = scene.make.rexPerspectiveRenderTexturege({\nx: 0,\ny: 0,    width: 32,\nheight: 32,\n\n// hideCCW: false,\n// gridWidth: 32,\n// girdHeight: 32,\n\nadd: true\n});\n
"},{"location":"perspective-rendertexture/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveRenderTexturege extends PerspectiveRenderTexturege {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyPerspectiveRenderTexturege(scene, x, y, width, height, config);\n
"},{"location":"perspective-rendertexture/#internal-render-texture","title":"Internal render texture","text":"
var rt = image.rt;\n
  • rt : Render texture
"},{"location":"perspective-rendertexture/#paste-texture","title":"Paste texture","text":"
  • Paste game object
    image.rt.draw(gameObject, x, y);\n// image.rt.draw(gameObject, x, y, alpha, tint);\n
  • gameObject : a game object, or an array of game objects
  • Paste game objects in a group
    image.rt.draw(group, x, y);\n// image.rt.draw(group, x, y, alpha, tint);\n
  • Paste game objects in a scene
    image.rt.draw(scene.children, x, y);\n// image.rt.draw(scene.children, x, y, alpha, tint);\n
  • Paste texture
    image.rt.draw(key, x, y);\n// image.rt.draw(key, x, y, alpha, tint);\n
    or
    image.rt.drawFrame(key, frame, x, y);\n// image.rt.drawFrame(key, frame, x, y, alpha, tint);\n
    • key : The key of the texture to be used, as stored in the Texture Manager.
  • Snapshop game objects
    image.snapshot(gameObjects);\n
    • gameObjects : Array of game objects.
"},{"location":"perspective-rendertexture/#erase","title":"Erase","text":"
image.rt.erase(gameObject, x, y);\n
  • gameObject : a game object, or an array of game objects
"},{"location":"perspective-rendertexture/#clear","title":"Clear","text":"
image.rt.clear();\n
"},{"location":"perspective-rendertexture/#fill","title":"Fill","text":"
image.rt.fill(rgb, alpha);\n// image.rt.fill(rgb, alpha, x, y, width, height);\n
"},{"location":"perspective-rendertexture/#other-properties","title":"Other properties","text":"

See Perspective image game object, Mesh game object, game object

"},{"location":"perspective-rendertexture/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"perspective-rendertexture/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"perspective-sprite/","title":"Sprite","text":""},{"location":"perspective-sprite/#introduction","title":"Introduction","text":"

Play animation on perspective-image.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"perspective-sprite/#live-demos","title":"Live demos","text":"
  • Play animation
"},{"location":"perspective-sprite/#usage","title":"Usage","text":"

Sample code

"},{"location":"perspective-sprite/#install-plugin","title":"Install plugin","text":""},{"location":"perspective-sprite/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexperspectiveimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexperspectiveimageplugin.min.js', true);\n
  • Add sprite object
    var sprite = scene.add.rexPerspectiveSprite(x, y, texture, frame, config);\n
"},{"location":"perspective-sprite/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PerspectiveImagePlugin from 'phaser3-rex-plugins/plugins/perspectiveimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPerspectiveImagePlugin',\nplugin: PerspectiveImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add sprite object
    var sprite = scene.add.rexPerspectiveSprite(x, y, texture, frame, config);\n
"},{"location":"perspective-sprite/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveSprite } from 'phaser3-rex-plugins/plugins/perspectiveimage.js';\n
  • Add sprite object
    var sprite = new PerspectiveSprite(scene, x, y, texture, frame, config);\nscene.add.existing(sprite);\n
"},{"location":"perspective-sprite/#create-instance","title":"Create instance","text":"
var sprite = scene.add.rexPerspectiveSprite(x, y, texture, frame, {\n// width: undefined,\n// height: undefined,\n// hideCCW: true,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

or

var sprite = scene.add.rexPerspectiveImage({\n// x: 0,\n// y: 0,\nkey,\n// frame: null,\n// width: undefined,\n// height: undefined,\n// hideCCW: true,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

Add perspectiveimage from JSON

var perspectiveimage = scene.make.rexPerspectiveImage({\nx: 0,\ny: 0,\n\nkey: null,\nframe: null,\n\n// width: undefined,\n// height: undefined,\n// hideCCW: false,\n// gridWidth: 32,\n// girdHeight: 32,\n\nadd: true\n});\n
"},{"location":"perspective-sprite/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveSprite extends PerspectiveSprite {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var sprite = new MyPerspectiveSprite(scene, x, y, texture, frame, config);\n
"},{"location":"perspective-sprite/#play-animation","title":"Play animation","text":"
  • Play
    sprite.play(key);\n// sprite.play(key, ignoreIfPlaying);\n
    • key : Animation key string, or animation config
      • String key of animation
      • Animation config, to override default config
        {\nkey,\nframeRate,\nduration,\ndelay,\nrepeat,\nrepeatDelay,\nyoyo,\nshowOnStart,\nhideOnComplete,\nstartFrame,\ntimeScale\n}\n
  • Play in reverse
    sprite.playReverse(key);\n// sprite.playReverse(key, ignoreIfPlaying);\n
    • key : Animation key string, or animation config
  • Play after delay
    sprite.playAfterDelay(key, delay);\n
    • key : Animation key string, or animation config
  • Play after repeat
    sprite.playAfterRepeat(key, repeatCount);\n
    • key : Animation key string, or animation config
"},{"location":"perspective-sprite/#chain","title":"Chain","text":"
  • Chain next animation
    sprite.chain(key);\n
    • key : Animation key string, or animation config
  • Chain next and next animation
    sprite.chain(key0).chain(key1);\n
    • key0, key1 : Animation key string, or animation config
"},{"location":"perspective-sprite/#stop","title":"Stop","text":"
  • Immediately stop
    sprite.stop();\n
  • Stop after delay
    sprite.stopAfterDelay(delay);\n
  • Stop at frame
    sprite.stopOnFrame(frame);\n
    • frame : Frame object in current animation.
      var currentAnim = sprite.anims.currentAnim;\nvar frame = currentAnim.getFrameAt(index);\n
  • Stop after repeat
    sprite.stopAfterRepeat(repeatCount);\n
"},{"location":"perspective-sprite/#restart","title":"Restart","text":"
sprite.anims.restart();\n// sprite.anims.restart(includeDelay, resetRepeats);\n
"},{"location":"perspective-sprite/#other-properties","title":"Other properties","text":"

See Perspective image game object, Mesh game object, game object

"},{"location":"perspective-sprite/#create-mask","title":"Create mask","text":"
var mask = sprite.createBitmapMask();\n

See mask

"},{"location":"perspective-sprite/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"plane/","title":"Plane","text":""},{"location":"plane/#introduction","title":"Introduction","text":"

A Plane is a kind of Mesh game object with one-sided grid of cells. which can have a texture that is either repeated (tiled) across each cell, or applied to the full Plane.

  • Author: Richard Davey

WebGL only

It only works in WebGL render mode.

"},{"location":"plane/#usage","title":"Usage","text":""},{"location":"plane/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"plane/#add-plane-object","title":"Add plane object","text":"
var plane = scene.add.plane(x, y, key);\n// var plane = scene.add.plane(x, y, key, frame);\n// var plane = scene.add.plane(x, y, texture, frame, width, height, tile);\n
  • x, y : Position
  • key, frame : Texture key of
  • width, height : The width/height of this Plane, in cells, not pixels.
  • tile : Is the texture tiled? I.e. repeated across each cell.

Add plane from JSON

var plane = scene.make.plane({\nx: 0,\ny: 0,\nkey: '',\n// frame: '',\n// width: 8,\n// height: 8,\n// tile: false,\n// checkerboard: null,\n// checkerboard: { color1, color2, alpha1, alpha2, height }\n\n// angle: 0,\n// alpha: 1,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
"},{"location":"plane/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPlane extends Phaser.GameObjects.Plane {\nconstructor(scene, x, y, texture, frame, width, height, tile) {\nsuper(scene, x, y, texture, frame, width, height, tile);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var plane = new MyPlane(scene, x, y, texture, frame, width, height, tile);\n
"},{"location":"plane/#texture","title":"Texture","text":"

See game object - texture

"},{"location":"plane/#animation","title":"Animation","text":"

See Sprite's animation section.

"},{"location":"plane/#play-animation","title":"Play animation","text":"
  • Play
    plane.play(key);\n// plane.play(key, ignoreIfPlaying);\n
    • key : Animation key string, or animation config
      • String key of animation
      • Animation config, to override default config
        {\nkey,\nframeRate,\nduration,\ndelay,\nrepeat,\nrepeatDelay,\nyoyo,\nshowOnStart,\nhideOnComplete,\nstartFrame,\ntimeScale\n}\n
  • Play in reverse
    plane.playReverse(key);\n// plane.playReverse(key, ignoreIfPlaying);\n
    • key : Animation key string, or animation config
  • Play after delay
    plane.playAfterDelay(key, delay);\n
    • key : Animation key string, or animation config
  • Play after repeat
    plane.playAfterRepeat(key, repeatCount);\n
    • key : Animation key string, or animation config
"},{"location":"plane/#stop","title":"Stop","text":"
  • Immediately stop
    plane.stop();\n
  • Stop after delay
    plane.stopAfterDelay(delay);\n
  • Stop at frame
    plane.stopOnFrame(frame);\n
    • frame : Frame object in current animation.
      var currentAnim = plane.anims.currentAnim;\nvar frame = currentAnim.getFrameAt(index);\n
  • Stop after repeat
    plane.stopAfterRepeat(repeatCount);\n
"},{"location":"plane/#properties","title":"Properties","text":"
  • Has started
    var hasStarted = plane.anims.hasStarted;\n
  • Is playing
    var isPlaying = plane.anims.isPlaying;\n
  • Is paused
    var isPaused = plane.anims.isPaused;\n
  • Total frames count
    var frameCount = plane.anims.getTotalFrames();\n
  • Delay
    var delay = plane.anims.delay;\n
  • Repeat
    • Total repeat count
      var repeatCount = plane.anims.repeat;\n
    • Repeat counter
      var repeatCount = plane.anims.repeatCounter;\n
    • Repeat delay
      var repeatDelay = plane.anims.repeatDelay;\n
    • Yoyo
      var repeatDelay = plane.anims.yoyo;\n
  • Current animation key
    var key = plane.anims.getName();\n
    • key : Return '' if not playing any animation.
  • Current frame name
    var frameName = plane.anims.getFrameName();\n
    • frameName : Return '' if not playing any animation.
  • Current animation
    var currentAnim = plane.anims.currentAnim;\n
  • Current frame
    var currentFrame = plane.anims.currentFrame;\n
"},{"location":"plane/#interactive","title":"Interactive","text":"

To test if pointer is at any face of this mesh game object.

plane.setInteractive();\n
"},{"location":"plane/#other-properties","title":"Other properties","text":"

See Mesh game object, game object

"},{"location":"plane/#checkerboard","title":"Checkerboard","text":"

Creates a checkerboard style texture, based on the given colors and alpha values and applies it to this Plane, replacing any current texture it may have.

  • Create
    plane.createCheckerboard(color1, color2, alpha1, alpha2, height)\n
  • Remove
    plane.removeCheckerboard();\n
"},{"location":"plane/#other-properties_1","title":"Other properties","text":"

See Mesh game object, game object

"},{"location":"plane/#create-mask","title":"Create mask","text":"
var mask = plane.createBitmapMask();\n

See mask

"},{"location":"plane/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"plugin-list/","title":"Plugin list","text":""},{"location":"plugin-list/#list-of-my-plugins","title":"List of my plugins","text":"

Version of phaser3

Please upgrade your phaser3 to version >= 3.80.0.

  1. Achievements: Achievements in a csv table.
  2. Alpha mask image: Load a texture, then apply an alpha mask from another texture.
  3. Anchor: Set size and position based on visible window.
  4. Arcade-TCRP/Player: Run commands on step of Arcade.
  5. Arcade-TCRP/Recorder: Store commands with step of Arcade.
  6. AwaitLoader: Await custom task in preload stage.
  7. Away time: Get time from previous closing application to now.
  8. BBCode-text: Drawing text with BBCode protocol.
  9. Board: Core object of Board system.
  10. Board/Image: Image chess object.
  11. Board/Field of view: Visible testing, to find field of view.
  12. Board/Hexagon map: Create tile positions in hexagon/triangle/parallelogram geometry in hexagon grid.
  13. Board/Match: Get matched chess.
  14. Board/Mini board: Chess Container, to rotate/mirror/drag chess together.
  15. Board/Monopoly: Move through path tiles.
  16. Board/Move To: Move chess towards target position with a steady speed.
  17. Board/Path finder: Find moveable area or moving path.
  18. Board/Shape: Grid (polygon) shape chess object.
  19. Board/Sprite: Sprite chess object.
  20. Board/Tilemap: Create board from tilemap.
  21. Board/Tile texture: Create canvas-texture of tile.
  22. Bounds: Clamp or wrap position of game object inside target bounds.
  23. Bracket parser: A lite-weight bracket parser.
  24. Bracket parser2: A lite-weight bracket parser.
  25. Buff data: Data manager with buffs.
  26. Build arcade object: Create arcade body, and inject arcade object methods.
  27. Bullet: Move game object toward current angle of game object, with a constant speed.
  28. Button: Fires 'click' event when touch releasd after pressed.
  29. Camera controller: Control camera's scroll by pan/cursor-at-bounds(scroll), and zoom by pinch/mouse-wheel.
  30. Canvas: Drawing on canvas.
  31. CanvasInput: An invisible Input DOM element to receive character input and display on DynamicText.
  32. Canvas/Circular progress: Circular progress bar on canvas.
  33. Canvas/Line progress: Horizontal line progress bar filled with gradient color on canvas.
  34. Canvas/Round rectangle: Round rectangle on canvas.
  35. Canvas image data: Get image data from texture, or text object.
  36. Circle mask image: Load a texture, then apply a circle mask.
  37. Click outside: Fires 'clickoutside' event when pointer-down or pointer-up outside of game object.
  38. Clock: A clock to count elapsed time.
  39. Character cache: Generate bitmapfont from text game object, or bbcode text game object.
  40. Color/TintRGB: Attach tintR, tintG, tintB, and tintGray properties to a game object.
  41. Conditions table: Check conditions to find passed tests listed in a csv table.
  42. ContainerLite: Control the position and angle of children game objects.
  43. Containerlite-perspective: Snapshot children of containerlite, to a perspective render texture.
  44. Containerlite-skew: Snapshot children of containerlite, to a skew render texture.
  45. CSV-scenario: Run script in csv format.
  46. CSV-to-hash-table: Hash table indexed by (col-key, row-key) from csv string.
  47. Cursor at bound: Map position pf cursor to cursor key state.
  48. Curve/Spiral: Spiral curve.
  49. Cut Jigsaw Image: Cut image into pieces for jigsaw application.
  50. Drag: Drag game object.
  51. Drag-rotate: Get dragging angle around a specific point.
  52. Drop down: Drop down game object below another target game object.
  53. Dynamic text: Control position, angle of each character drawn on a canvas.
  54. Ease-data: Easing data value of game object's data-manager.
  55. Ease-move: Ease-move game object.
  56. Effect properties: Attach properties to a game object or camera, to add/remove/control builtin preFX or postFX effects.
  57. Eight direction: Move game object by cursor keys, with a constant speed.
  58. Event promise: Return a promise of an event.
  59. Expression parser: Parse expression string into function.
  60. Fade-out-destroy: Fade out game object then destroy it.
  61. Fade-volume: Fade-in/fade-out volume of sound.
  62. File chooser: Create a transparent file chooser button.
  63. File drop zone: Create a div element for dropping file(s).
  64. Firebase/Broadcast: Broadcast real-time messages, using firebase-database.
  65. Firebase/Files: Save JSON data, using firebase-firestore.
  66. Firebase/ID-alias: Map an unique ID to another unique ID, using firebase-firestore.
  67. Firebase/Item-table: 1d/2d/3d table, using firebase-database.
  68. Firebase/Leaderboard: Descending sort scores, using firebase-firestore.
  69. Firebase/Messages: Store messages in firebase-firestore.
  70. Firebase/Online-user-list: Online user list, using firebase-database.
  71. Firebase/Single-room: Chat room, using firebase-database.
  72. Flash: Flashing (set invisible then visible) game object.
  73. Flip: Flipping game object to another face by scaling width/height.
  74. Frame manager: Draw frames on canvas texture, or dynamic texture.
  75. FSM: Finite state machine.
  76. Fuzzy: A wrap of fuzzy logic.
  77. Gashapon: Pick random item from box.
  78. Geom/Hexagon: Hexagon geometry object.
  79. Geom/Rhombus: Rhombus shape and methods.
  80. Gesture/Pan: Get pan events of a game object.
  81. Gesture/Pinch: Get scale factor from 2 dragging touch pointers.
  82. Gesture/Press: Get press events of a game object.
  83. Gesture/Rotate: Get spin angle from 2 dragging touch pointers.
  84. Gesture/Swipe: Get swipe events of a game object.
  85. Gesture/Tap: Get tap/multi-taps events of a game object.
  86. Grid align: Align objects on quadrilateral or hexagon grid.
  87. Grid cut image: Grid cut image texture to frames, then create image game objects from these frames.
  88. Grid table: Viewer of grid table, to manipulate game object of each visible cell.
  89. Group navigator: Navigate between existing game objects, focus on next/previous/next-row/previous row game object.
  90. Hidden input text: An invisible Input DOM element to receive character input and display on text game object.
  91. Image box: Keep aspect ratio of image game object after scale-down resizing.
  92. Input text: Input DOM element.
  93. Interception: Predict the intersection position of two game objects with constant moving speed.
  94. In touching: Fires 'intouch' event every tick when pressing on a game object.
  95. Keys hub: Key object interface mapping from multiple source of key objects.
  96. Layer manager: A container of Layer game objects.
  97. Level counter: Map level value from experience value, by callback or a number array.
  98. Life time: Destroy game object when time-out.
  99. Line: Draw a line with start/end/body textures.
  100. Live2d: Display live2d model.
  101. Loading animation scene: Start loading animation scene, stop this scene when loading complete.
  102. Loading-progress: Pop-up dialog for loading-progress, then scale-down this dialog.
  103. LocalForage/Files: Save JSON data, using localforage.
  104. LocalStorage/Data: Sync data from data manager to local-storage.
  105. LZ-string: Compress string using LZ-based compression algorithm.
  106. Markdown event sheets: Event sheets contains main condition(s) and actions, in simple markdown format (headings, code block).
  107. Modal promise: Modal behavior wrapped into promise.
  108. Mouse-wheel to up/down: Map mouse-wheeling to (up/down) cursor key state.
  109. Mouse-wheel scroller: Emit scroll event when mouse-wheeling.
  110. Move to: Move game object towards target position with a steady speed.
  111. Nine patch: Stretchable image.
  112. Nine patch2: Stretchable image. Has better performance than nine-patch.
  113. Particles-along-bounds: Emit particles along bounds of game object.
  114. Particles/Bitmap-zone: Particles' emitter zone from canvas bitmap of text/canvas game object.
  115. Path follower: Set position of game object on a path.
  116. Perlin: Perlin2/Perlin3 noise and simplex2/simplex3 noise.
  117. Perspective/Card: A container with two perspective-images.
  118. Perspective/Carousel: A container with cards.
  119. Perspective/Image: Image with perspective rotation.
  120. Perspective/ImageCarousel: Display list of images.
  121. Perspective/Render texture: Render texture with perspective rotation.
  122. Perspective/Sprite: Play animation on perspective-image..
  123. PNG appender: Append user data below tail of PNG data, or extract this user data from PNG data.
  124. polar-coordinate: Attach polarOX, polarOY, polarRotation, polarAngle, and polarRadius properties to a game object.
  125. Pop up: Scale up game object.
  126. Quad/Image: Image with 4 or 9 vertex control points.
  127. Quad/Render texture: Render texture with 4 or 9 vertex control points.
  128. Quest: Question manager.
  129. Raycaster: Raycaster between obstacles.
  130. Random place: Place objects randomly inside an area without overlapping.
  131. Real-time timers: Start and counting timer by real-time timestamp.
  132. Repeat Image: Stamp image repeatly on canvas.
  133. Restorable data: Restorable data manager.
  134. RotateTo: Rotate game object towards target position with a steady speed.
  135. Rotate: Rotate game object continually with a steady speed.
  136. Run-commands: Run commands in array.
  137. Scale-down-destroy: Scale down game object then destroy it.
  138. Scale outer: Scroll and zoom camera to make default game window fit the display area, in RESIZE scale mode.
  139. Script-tag loader: Load script tag in preload stage.
  140. Scroller: Drag content. Slow down when dragging released, pull back when out of bounds.
  141. Sequence: Run sequence commands in array.
  142. Shader/Barrel: Barrel post processing filter.
  143. Shader/Color-replace: Replace color post processing filter.
  144. Shader/Cross-stitching: Cross-stitching post processing filter.
  145. Shader/CRT: CRT post processing filter.
  146. Shader/Dissolve: Dissolve transition post processing filter.
  147. Shader/Drop-shadow: Drop-shadow post processing filter.
  148. Shader/Fish-eye: Fish-eye post processing filter.
  149. Shader/Glow-filter: Glow post processing filter.
  150. Shader/Glow-filter: Glow post processing filter, ported from pixi.
  151. Shader/Gray-scale: Gray scale post processing filter.
  152. Shader/Horri-fi: 6-in-1 post processing filter.
  153. Shader/Hsl-adjust: Adjust color in HSL domain, post processing filter.
  154. Shader/Inverse: Inverse color post processing filter.
  155. Shader/Kawaseblur: Kawase-blur post processing filter.
  156. Shader/Outline: Outline post processing filter, ported from pixi.
  157. Shader/Pixelation: Pixelation post processing filter.
  158. Shader/Shockwave: Shockwave post processing filter.
  159. Shader/Split: Split image into 4 parts.
  160. Shader/Swirl: Swirl post processing filter.
  161. Shader/Toonify: Draw outlines and quantize color in HSV domain, post processing filter.
  162. Shader/Warp: Warp post processing filter.
  163. Shake-position: Shake position of game object.
  164. Shape/Checkbox: Checkbox input with drawing checker path animation.
  165. Shape/Circular progress: Circular progress bar shape.
  166. Shape/Cover: Rectangle shape covered full window, and block all touch events.
  167. Shape/Custom progress: Custom progress bar shape.
  168. Shape/Custom shapes: Custom shapes on shape.
  169. Shape/Full window rectangle: Rectangle shape covered full window.
  170. Shape/Line progress: Horizontal line progress bar shape.
  171. Shape/Quad: Quad shape, offsets can be given on four vertices, and additional points can be added on the four sides.
  172. Shape/Round-Rectangle: Round rectangle shape.
  173. Shape/Spinner: Loading animations on shape.
  174. Shape/Toggle-switch: Toggle-switch input.
  175. Shape/Triangle: Trangle shape inside a rectangle bounds.
  176. Shatter/Image: Shatter image to triangle faces.
  177. Shatter/Render texture: Shatter render texture to triangle faces.
  178. Ship: Move game object as a space ship by cursor keys.
  179. Skew/Image: Skewable Image.
  180. Skew/RenderTexture: Skewable render texture.
  181. Slider: Drag thumb on a slider bar.
  182. State manager: Another version of Finite state machine.
  183. Step: Interpolate points between previous position and current position with fixed step length.
  184. Tag-player: Text commands to control sprites, texts, sound effect or backgroun music.
  185. Tag-text: Displays text with multi-color, font face, or font size with tags.
  186. TCRP/Player: Run commands on time.
  187. TCRP/Recorder: Store commands with time.
  188. Text/Edit: Create an input text object above a text object to edit string content.
  189. Text/Typing: Typing text on text object.
  190. Text/Page: Display text page by page on text object.
  191. Text/Translation: Apply translated string (i18next) to text object.
  192. Text/Truncator: Constraints text game object size by truncating text with padding symbol on text object.
  193. Text player: Typing characters on dynamic text, waiting click or key enter, play sound effect or backgroun music.
  194. Touch event stop: Stop touch events propagation.
  195. Touch state: Store current touch input properties.
  196. Transition image: Transit texture to another one.
  197. Transition image pack: Transit texture to another one, with some pre-build effects.
  198. UI/Badge label: A container with badges above a main item.
  199. UI/Buttons: A container with a group of buttons.
  200. UI/Chart: Draw chart on canvas.
  201. UI/Color components: Edit color value by RGB, or HSV input fields.
  202. UI/Color input: Color value input field.
  203. UI/Color picker: Pick color value from H and SV palettes.
  204. UI/Confirm action: Create a modal confirm dialog temporary, invoke callback after clicking button.
  205. UI/Confirm action button: Create a modal confirm dialog temporary, invoke callback after clicking button.
  206. UI/Confrim dialog: Using json style to create confirm dialog.
  207. UI/Dialog: A container with a title, content, buttons and backgrounds.
  208. UI/Drop down list: A label can open a drop-down list panel.
  209. UI/Exp bar: Disply experience bar on NameValueLabel.
  210. UI/File selector button: A transparent file chooser button above a Label.
  211. UI/Fixwidthbuttons: A container with a group of fix-width buttons.
  212. UI/Fixwidthsizer: Layout children game objects into lines.
  213. UI/Folder: A container with a title, foldable child, and background.
  214. UI/Grid buttons: A container with a group of buttons in grids.
  215. UI/Grid sizer: Layout children game objects in grids.
  216. UI/Gird table: A container with a grid table, slider, and scroller.
  217. UI/Holy grail: Layout elements in Holy grail style.
  218. UI/Image input label: A container with a canvas icon, text, and background. Click icon to popup a (image) file chooser dialog, display selected image on canvas.
  219. UI/Knob: A knob button based on circular progress.
  220. UI/Label: A game object container with an icon, text, and background.
  221. UI/Menu: A container with buttons and sub-menu.
  222. UI/Name-input dialog: Enter first name and last name via a dialog.
  223. UI/Name-value label: A container with name text, value text in a row, with a horizontal line progress bar, 1d an icon, background.
  224. UI/Number bar: A container with an icon, slider, text, and background.
  225. UI/Overlap sizer: Layout children game objects overlapped.
  226. UI/Pages: A container with pages, only current page is visible.
  227. UI/Perspective card: A container with front and back faces.
  228. UI/Scroll-able panel: A container with a panel, slider, and scroller.
  229. UI/Scroll bar: A container with slider, two buttons, and background.
  230. UI/Simple drop down list: Using plain object to create drop down list.
  231. UI/Simple label: Using json style to create label.
  232. UI/Simple title label: Using json style to create title label.
  233. UI/Simple text box: Using json style to create text box.
  234. UI/Sizer: Layout children game objects.
  235. UI/Slider: A container with a track, indicator, thumb and background.
  236. UI/Split panels: A container with left(top) panel, right(bottom) panel, splitter, and background. Drag splitter to resize with left(top) panel, right(bottom) panel.
  237. UI/Tab-pages: A container with tabs and pages, only current page is visible.
  238. UI/Tabs: A container with 4 groups of buttons around a center panel.
  239. UI/Text area: A container with a text, slider, and scroller.
  240. UI/Text area input: A container with a canvasInput, and slider.
  241. UI/Text box: A container with an icon, (typing and paging) text, and background.
  242. UI/Title label: A container with title, text in two rows, and an icon, background.
  243. UI/Toast: Show text message for a short while.
  244. UI/Toast queue: Queue messages for a short while.
  245. UI/Trees: A container with trees and leaf-nodes.
  246. UI/Tweaker: Fine-tuning properties of target object.
  247. Unique item list: List of unique items. Support array and set methods.
  248. Viewport-coordinate: Attach vpx, vpy properties to a game object, to set position according to proportion of viewport.
  249. Virtual joystick: Simulate cursor keys according to touch events.
  250. Wait events: Wait fired events or callbacks.
  251. Webfont-loader: Load web font by google webfont loader in preload stage.
  252. XOR: Encrypt or decrypt string by XOR algorithm.
  253. YML-Achievements: Achievements in a YAML table.
  254. YML-Conditions table: Check conditions to find passed tests listed in a YAML table.
  255. Youtube player: Play youtube video on iframe.
"},{"location":"pluginsystem/","title":"Plugin system","text":""},{"location":"pluginsystem/#introduction","title":"Introduction","text":"

Plugin system, built-in system of phaser.

  • Author: Richard Davey
"},{"location":"pluginsystem/#usage","title":"Usage","text":""},{"location":"pluginsystem/#global-plugin","title":"Global plugin","text":""},{"location":"pluginsystem/#load-plugin","title":"Load plugin","text":"
  • Load plugin before any scene start In game configuration
    // import pluginKlass from '...';\nvar config = {\n// ...\nplugins: {\nglobal: [\n{\nkey: key,\nplugin: pluginKlass,\nstart: true\n// mapping: memberName  // member name in each scene instance, optional\n// data: undefined\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • pluginKlass : Class instance
    • start : Whether the plugin should be started automatically.
    • mapping : If this plugin is to be injected into the Scene Systems, this is the property key map used.
    • data : Arbitrary data passed to the plugin's init() method.
  • Load plugin in scene
    scene.load.plugin(key, url, true);\n// scene.load.plugin(key, url, true, mapping);\n
    • url : File url or class instance.
"},{"location":"pluginsystem/#get-instance","title":"Get instance","text":"
var pluginInst = scene.plugins.get(key);\n
"},{"location":"pluginsystem/#scene-plugin","title":"Scene plugin","text":""},{"location":"pluginsystem/#load-plugin_1","title":"Load plugin","text":"
  • Load plugin before any scene start In game configuration
    // import pluginKlass from '...';\nvar config = {\n// ...\nplugins: {\nscene: [\n{\nkey: key,\nplugin: pluginKlass,\nmapping: sceneKey,    // member name in each scene instance\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • pluginKlass : Class instance
  • Load plugin in scene
    scene.load.scenePlugin(key, url, systemKey, sceneKey);\n
    • url : File url or class instance.
"},{"location":"pluginsystem/#get-instance_1","title":"Get instance","text":"
var pluginInst = scene[sceneKey];\n
"},{"location":"pluginsystem/#plugin-cache","title":"Plugin cache","text":"
  • Has custom plugin
    var hasPlugin = Phaser.Plugins.PluginCache.hasCustom(key);\n
"},{"location":"png-appender/","title":"PNG Appender","text":""},{"location":"png-appender/#introduction","title":"Introduction","text":"

Append user data below tail of PNG data, or extract this user data from PNG data.

  • Author: Rex
  • Methods
"},{"location":"png-appender/#live-demos","title":"Live demos","text":"
  • Append-extract
"},{"location":"png-appender/#usage","title":"Usage","text":"

Sample code

"},{"location":"png-appender/#install-plugin","title":"Install plugin","text":""},{"location":"png-appender/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexpngappenderplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexpngappenderplugin.min.js', true);\n
  • Append, or extract data
    var resultBuffer = scene.plugins.get('rexpngappenderplugin').append(pngBuffer, data);\nvar data = scene.plugins.get('rexpngappenderplugin').extract(pngBuffer);\n
"},{"location":"png-appender/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PNGAppenderPlugin from 'phaser3-rex-plugins/plugins/pngappender-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPNGAppender',\nplugin: PNGAppenderPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Append, or extract data
    var resultBuffer = scene.plugins.get('rexPNGAppender').append(pngBuffer, data);\nvar data = scene.plugins.get('rexPNGAppender').extract(pngBuffer);\n
"},{"location":"png-appender/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import PNGAppender from 'phaser3-rex-plugins/plugins/pngappender.js';\n
  • Append, or extract data
    var resultBuffer = PNGAppender.append(pngBuffer, data);\nvar data = PNGAppender.extract(pngBuffer);\n
"},{"location":"png-appender/#append-data","title":"Append data","text":"
var resultBuffer = scene.plugins.get('rexPNGAppender').append(pngBuffer, data);\n
  • pngBuffer : PNG data loaded from binary loader.
  • data : JSON. dictionary, array, string, number, or Uint8Array.
  • resultBuffer : PNG data with custom data (data).
    • Can add to texture cache via scene.load.image(...)
      1. Create blob from resultBuffer : var blob = new Blob([buffer], { type: 'image/png' })
      2. Create object url from blob : var url = window.URL.createObjectURL(blob)
      3. Load texture from object url : scene.load.image(textureKey, url)
      4. Start loader if in create stage of scene : scene.load.start()
    • Can download and display on image viewer as normal PNG file.
"},{"location":"png-appender/#extract-data","title":"Extract data","text":"
var data = scene.plugins.get('rexPNGAppender').extract(pngBuffer);\n
  • pngBuffer : PNG data loaded from binary loader.
  • data : User data.
    • null : This pngBuffer does not have user data.
"},{"location":"point-light/","title":"Point light","text":""},{"location":"point-light/#introduction","title":"Introduction","text":"

A point light with gradient color in a circle.

  • Author: Richard Davey

WebGL only

It only works in WebGL render mode.

"},{"location":"point-light/#usage","title":"Usage","text":""},{"location":"point-light/#add-point-light","title":"Add point light","text":"
var pointLight = scene.add.pointlight(x, y, color, radius, intensity, attenuation);\n
  • x, y : The horizontal/vertical position of this Game Object in the world.
  • color : Color of this light.
  • radius : Radius of this light.
  • intensity : 0~1, intensity of color.
  • attenuation : 0~1, decay intensity along radius.
"},{"location":"point-light/#position","title":"Position","text":"
  • Set
    pointLight.setPosition(x, y);\n
    or
    pointLight.x = x;\npointLight.y = y;\n
  • Get
    var x = pointLight.x;\nvar y = pointLight.y;\n
"},{"location":"point-light/#color","title":"Color","text":"
  • Set
    • Red, green, blue
      pointLight.color.set(red, green, blue);\n
      or
      pointLight.color.r = red;\npointLight.color.g = green;\npointLight.color.b = blue;\n
      • red, green, blue : 0~1.
  • Get
    • Red, green, blue
      var red = pointLight.color.r;\nvar green = pointLight.color.g;\nvar blue = pointLight.color.b;\n
      • red, green, blue : 0~1.
"},{"location":"point-light/#radius","title":"Radius","text":"
  • Set
    pointLight.radius = radius;\n
  • Get
    var radius = pointLight.radius;\n
"},{"location":"point-light/#intensity","title":"Intensity","text":"
  • Set
    pointLight.intensity = intensity;\n
  • Get
    var intensity = pointLight.intensity;\n
"},{"location":"point-light/#attenuation","title":"Attenuation","text":"
  • Set
    pointLight.attenuation = attenuation;\n
  • Get
    var attenuation = pointLight.attenuation;\n
"},{"location":"polar-coordinate/","title":"Polar-coordinate","text":""},{"location":"polar-coordinate/#introduction","title":"Introduction","text":"

Attach polarOX, polarOY, polarRotation, polarAngle, and polarRadius properties to a game object.

  • Author: Rex
  • Method only
"},{"location":"polar-coordinate/#live-demos","title":"Live demos","text":"
  • Circle
  • Spiral
"},{"location":"polar-coordinate/#usage","title":"Usage","text":"

Sample code

"},{"location":"polar-coordinate/#install-plugin","title":"Install plugin","text":""},{"location":"polar-coordinate/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexpolarcoordinateplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexpolarcoordinateplugin.min.js', true);\n
  • Attach polarOX, polarOY, polarRotation, polarAngle, and polarRadius properties.
    scene.plugins.get('rexpolarcoordinateplugin').add(gameObject, ox, oy, rotation, radius);\ngameObject.polarRadius = 200;\ngameObject.polarAngle = -45;\n
"},{"location":"polar-coordinate/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PolarCoordinatePlugin from 'phaser3-rex-plugins/plugins/polarcoordinate-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPolarCoordinate',\nplugin: PolarCoordinatePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Attach polarOX, polarOY, polarRotation, polarAngle, and polarRadius properties.
    scene.plugins.get('rexPolarCoordinate').add(gameObject, ox, oy, rotation, radius);\ngameObject.polarRadius = 200;\ngameObject.polarAngle = -45;\n
"},{"location":"polar-coordinate/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import AddPolarCoordinateProperties from 'phaser3-rex-plugins/plugins/polarcoordinate.js';\n
  • Attach polarOX, polarOY, polarRotation, polarAngle, and polarRadius properties.
    AddPolarCoordinateProperties(gameObject, ox, oy, rotation, radius);\ngameObject.polarOX = 400;\ngameObject.polarOY = 300;\ngameObject.polarRadius = 200;\ngameObject.polarAngle = -45;\n
"},{"location":"polar-coordinate/#attach-properties","title":"Attach properties","text":"
scene.plugins.get('rexPolarCoordinate').add(gameObject, ox, oy, rotation, radius);\ngameObject.polarOX = 400;\ngameObject.polarOY = 300;\ngameObject.polarRadius = 200;\ngameObject.polarAngle = -45;\n
  • ox, oy : Position of origin point.
  • rotation : Polar angle, in radian.
  • radius : Polar radius.
x = ( polarRadius * cos(polarRotation) ) + polarOX\ny = ( polarRadius * sin(polarRotation) ) + polarOY\n
"},{"location":"polar-coordinate/#circle","title":"Circle","text":"
scene.tweens.add({\ntargets: gameObject,\npolarAngle: 360,\nduration: 3000\n})\n
"},{"location":"popup/","title":"Pop up","text":""},{"location":"popup/#introduction","title":"Introduction","text":"

Scale up from 0 to current scale of game object.

  • Author: Rex
  • Method only
"},{"location":"popup/#usage","title":"Usage","text":"

Sample code

"},{"location":"popup/#install-plugin","title":"Install plugin","text":""},{"location":"popup/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexscaleplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexscaleplugin.min.js', true);\n
  • Pop-up object
    scene.plugins.get('rexscaleplugin').popup(gameObject, duration);\n
"},{"location":"popup/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ScalePlugin from 'phaser3-rex-plugins/plugins/scale-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexScale',\nplugin: ScalePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Pop-up object
    scene.plugins.get('rexScale').popup(gameObject, duration);\n
"},{"location":"popup/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import PopUp from 'phaser3-rex-plugins/plugins/popup.js';\n
  • Pop-up object
    PopUp(gameObject, duration);\n
"},{"location":"popup/#pop-up","title":"Pop up","text":"
  • Pop up width and height
    var scale = scene.plugins.get('rexScale').popup(gameObject, duration);\n// var scale = popUp(gameObject, duration, undefined, ease);\n
    • ease : Ease function, default is 'Cubic'.
  • Pop up width only
    var scale = scene.plugins.get('rexScale').popup(gameObject, duration, 'x');\n// var scale = popUp(gameObject, duration, 'x', ease);\n
    • ease : Ease function, default is 'Cubic'.
  • Pop up height only
    var scale = scene.plugins.get('rexScale').popup(gameObject, duration, 'y');\n// var scale = popUp(gameObject, duration, 'y', ease);\n
    • ease : Ease function, default is 'Cubic'.
"},{"location":"popup/#events","title":"Events","text":"

See Events of tween task

  • Scale completes or is stopped.
    scale.on('complete', function(gameObject, scale){\n\n}, scope);\n
"},{"location":"postfx-pipeline/","title":"Post fx pipeline","text":""},{"location":"postfx-pipeline/#introduction","title":"Introduction","text":"

Post fx pipelines for game objects or camera. A game object or a camera can stack many post-fx effect.

  • Author: Richard Davey

WebGL only

All kinds of post fx pipelines only work in WebGL render mode.

"},{"location":"postfx-pipeline/#usage","title":"Usage","text":""},{"location":"postfx-pipeline/#post-fx-pipeline-class","title":"Post fx pipeline class","text":"
class MyPostFxClass extends Phaser.Renderer.WebGL.Pipelines.PostFXPipeline {\nconstructor(game) {\nsuper({\ngame: game,\nrenderTarget: true,\nfragShader: '...',  // GLSL shader\nuniforms: []\n});\n}\n\nonPreRender() {\nthis.set1f('intensity', this._intensity);\n}\n\nonDraw(renderTarget) {\n}\n}\n
"},{"location":"postfx-pipeline/#set-uniform-values","title":"Set uniform values","text":"
  • Property with 1 value
    • Float
      pipelineInstance.set1f(name, value0);\n// pipelineInstance.set1f(name, value0, shader);\n
    • uniform1fv
      pipelineInstance.set1fv(name, value0);\n// pipelineInstance.set1fv(name, value0, shader);\n
    • Int
      pipelineInstance.set1i(name, value0);\n// pipelineInstance.set1i(name, value0, shader);\n
  • Property with 2 values
    • Float
      pipelineInstance.set2f(name, value0, value1);\n// pipelineInstance.set2f(name, value0, value1, shader);\n
    • uniform2fv
      pipelineInstance.set2fv(name, value0, value1);\n// pipelineInstance.set2fv(name, value0, value1, shader);\n
    • Int
      pipelineInstance.set2i(name, value0, value1);\n// pipelineInstance.set2i(name, value0, value1, shader);\n
  • Property with 3 value
    • Float
      pipelineInstance.set3f(name, value0, value1, value2);\n// pipelineInstance.set3f(name, value0, value1, value2, shader);\n
    • uniform3fv
      pipelineInstance.set3fv(name, value0, value1, value2);\n// pipelineInstance.set3fv(name, value0, value1, value2, shader);\n
    • Int
      pipelineInstance.set3i(name, value0, value1, value2);\n// pipelineInstance.set3i(name, value0, value1, value2, shader);\n
  • Property with 4 values
    • Float
      pipelineInstance.set4f(name, value0, value1, value2, value3);\n// pipelineInstance.set4f(name, value0, value1, value2, value3, shader);\n
    • uniform4fv
      pipelineInstance.set4fv(name, value0, value1, value2, value3);\n// pipelineInstance.set4fv(name, value0, value1, value2, value3, shader);\n
    • Int
      pipelineInstance.set4i(name, value0, value1, value2, value3);\n// pipelineInstance.set4i(name, value0, value1, value2, value3, shader);\n
"},{"location":"postfx-pipeline/#onprerender","title":"onPreRender","text":"
  • Set uniform values in onPreRender method.
"},{"location":"postfx-pipeline/#ondraw","title":"onDraw","text":"
  • Ping-pong drawing
    • Variables :
      • renderTarget : Render target, parameter of onDraw method.
      • pipelineInstance.fullFrame1, pipelineInstance.fullFrame2 : Ping-pong render texture.
    • Steps
      1. Copy frame to pipelineInstance.fullFrame1
        pipelineInstance.copyFrame(source, target);\n// pipelineInstance.copyFrame(source, target, brightness, clear, clearAlpha);\n
      2. Set uniform values
      3. Bind and draw on pipelineInstance.fullFrame1, pipelineInstance.fullFrame2.
        pipelineInstance.bindAndDraw(source, target);\n// pipelineInstance.bindAndDraw(source, target, clear, clearAlpha, shader);\n
      4. Draw result back
        pipelineInstance.bindAndDraw(source);\n
"},{"location":"postfx-pipeline/#register-post-fx-pipeline","title":"Register post-fx pipeline","text":"
  • Register post-fx pipeline in game config
    import MyPostFxClass from 'path';\nvar config = {\n// ...\npipeline: [MyPostFxClass]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Or register post-fx pipeline at runtime
    var pipelineManager = scene.sys.renderer.pipelines;\npipelineManager.addPostPipeline(PostFxName, MyPostFxClass);\n
"},{"location":"postfx-pipeline/#apply-effect","title":"Apply effect","text":"

gameObject.setPostPipeline(MyPostFxClass);\n
camera.setPostPipeline(MyPostFxClass);\n

Will create an effect instance then push it into postPipelines list.

"},{"location":"postfx-pipeline/#get-post-fx-pipeline","title":"Get post-fx pipeline","text":"

var pipelineInstance = gameObject.getPostPipeline(MyPostFxClass);\n
var pipelineInstance = camera.getPostPipeline(MyPostFxClass);\n

"},{"location":"postfx-pipeline/#remove-post-fx-pipeline","title":"Remove post-fx pipeline","text":"

gameObject.removePostPipeline(MyPostFxClass);\n
camera.removePostPipeline(MyPostFxClass);\n

"},{"location":"postfx-pipeline/#unregister-post-fx-pipeline","title":"Unregister post-fx pipeline","text":"
var pipelineManager = scene.sys.renderer.pipelines;\npipelineManager.remove(PostFxName);\n
"},{"location":"postfx-pipeline/#color-matrix","title":"Color matrix","text":"

Use color martix to change RGB render result, and more...

class MyPostFxClass extends Phaser.Renderer.WebGL.Pipelines.PostFXPipeline {\nconstructor(game) {\nsuper({\ngame: game,\nrenderTarget: true,\nfragShader: '...',  // GLSL shader\nuniforms: []\n});\n}\n\nonPreRender() {\n// this.set1f('intensity', this._intensity);\nthis.colorMatrix.grayscale(this._intensity);\n}\n\nonDraw(renderTarget) {\nthis.colorMatrix.grayscale(this._intensity);\nthis.drawFrame(renderTarget, this.fullFrame1);\nthis.bindAndDraw(this.fullFrame1);\n}\n}\n
"},{"location":"postfx-pipeline/#color-adjusting","title":"Color adjusting","text":"

Invoke before drawFrame().

  • Grayscale
    this.colorMatrix.grayscale(value);\n// this.colorMatrix.grayscale(value, true); // Cascade\n
    • value : 0 ~ 1
  • Night vision tone
    this.colorMatrix.night(value);\n// this.colorMatrix.night(value, true); // Cascade\n
    • value : 0 ~ 1
  • Sepia tone
    this.colorMatrix.sepia();\n// this.colorMatrix.sepia(true); // Cascade\n
  • Trippy color tone
    this.colorMatrix.lsd();\n// this.colorMatrix.lsd(true); // Cascade\n
  • Brown tone
    this.colorMatrix.brown();\n// this.colorMatrix.brown(true); // Cascade\n
  • Vintage pinhole color effect
    this.colorMatrix.vintagePinhole();\n// this.colorMatrix.vintagePinhole(true); // Cascade\n
  • Kodachrome color effect
    this.colorMatrix.kodachrome();\n// this.colorMatrix.kodachrome(true); // Cascade\n
  • Technicolor color effect
    this.colorMatrix.technicolor();\n// this.colorMatrix.technicolor(true); // Cascade\n
  • Polaroid color effect
    this.colorMatrix.polaroid();\n// this.colorMatrix.polaroid(true); // Cascade\n
  • Brightness
    this.colorMatrix.brightness(value);\n// this.colorMatrix.brightness(value, true); // Cascade\n
    • value : 0(black) ~ 1
  • Saturation
    this.colorMatrix.saturate(value);\n// this.colorMatrix.saturate(value, true); // Cascade\n
    • value : -1 ~ 1
  • Desaturate
    this.colorMatrix.desaturate();\n// this.colorMatrix.desaturate(true); // Cascade\n
  • Hue
    this.colorMatrix.hue(rotation);\n// this.colorMatrix.hue(rotation, true); // Cascade\n
    • rotation : Hue rotation, in degree.
  • Black and white
    this.colorMatrix.blackWhite();\n// this.colorMatrix.blackWhite(true); // Cascade\n
  • Negative
    this.colorMatrix.negative();\n// this.colorMatrix.negative(true); // Cascade\n
  • Contrast
    this.colorMatrix.contrast(value);\n// this.colorMatrix.contrast(value, true); // Cascade\n
  • Desaturate luminance
    this.colorMatrix.desaturateLuminance();\n// this.colorMatrix.desaturateLuminance(true); // Cascade\n
  • Shifts RGB to BGR order
    this.colorMatrix.shiftToBGR();\n// this.colorMatrix.shiftToBGR(true); // Cascade\n
"},{"location":"postfx-pipeline/#draw","title":"Draw","text":"

Invoke under onDraw(renderTarget).

this.drawFrame(renderTarget, this.fullFrame1);\nthis.bindAndDraw(this.fullFrame1);\n
"},{"location":"prefx-pipeline/","title":"Pre fx pipeline","text":""},{"location":"prefx-pipeline/#introduction","title":"Introduction","text":"

Pre fx pipelines for texture-base game objects. A texture-base game object has a pre-fx effect.

  • Author: Richard Davey

WebGL only

All kinds of post fx pipelines only work in WebGL render mode.

"},{"location":"prefx-pipeline/#usage","title":"Usage","text":""},{"location":"prefx-pipeline/#post-fx-pipeline-class","title":"Post fx pipeline class","text":"
class MyPreFxClass extends Phaser.Renderer.WebGL.Pipelines.PreFXPipeline {\nconstructor(game) {\nsuper({\ngame: game,\nfragShader: '...',  // GLSL shader\n});\n}\n\nonDraw(renderTarget) {\nvar sprite = this.tempSprite;\nthis.set1f('intensity', sprite._intensity);\n\nsuper.onDraw(renderTarget);\n}\n}\n
"},{"location":"prefx-pipeline/#set-uniform-values","title":"Set uniform values","text":"
  • Property with 1 value
    • Float
      pipelineInstance.set1f(name, value0);\n// pipelineInstance.set1f(name, value0, shader);\n
    • uniform1fv
      pipelineInstance.set1fv(name, value0);\n// pipelineInstance.set1fv(name, value0, shader);\n
    • Int
      pipelineInstance.set1i(name, value0);\n// pipelineInstance.set1i(name, value0, shader);\n
  • Property with 2 values
    • Float
      pipelineInstance.set2f(name, value0, value1);\n// pipelineInstance.set2f(name, value0, value1, shader);\n
    • uniform2fv
      pipelineInstance.set2fv(name, value0, value1);\n// pipelineInstance.set2fv(name, value0, value1, shader);\n
    • Int
      pipelineInstance.set2i(name, value0, value1);\n// pipelineInstance.set2i(name, value0, value1, shader);\n
  • Property with 3 value
    • Float
      pipelineInstance.set3f(name, value0, value1, value2);\n// pipelineInstance.set3f(name, value0, value1, value2, shader);\n
    • uniform3fv
      pipelineInstance.set3fv(name, value0, value1, value2);\n// pipelineInstance.set3fv(name, value0, value1, value2, shader);\n
    • Int
      pipelineInstance.set3i(name, value0, value1, value2);\n// pipelineInstance.set3i(name, value0, value1, value2, shader);\n
  • Property with 4 values
    • Float
      pipelineInstance.set4f(name, value0, value1, value2, value3);\n// pipelineInstance.set4f(name, value0, value1, value2, value3, shader);\n
    • uniform4fv
      pipelineInstance.set4fv(name, value0, value1, value2, value3);\n// pipelineInstance.set4fv(name, value0, value1, value2, value3, shader);\n
    • Int
      pipelineInstance.set4i(name, value0, value1, value2, value3);\n// pipelineInstance.set4i(name, value0, value1, value2, value3, shader);\n
"},{"location":"prefx-pipeline/#ondraw","title":"onDraw","text":"
  • Set uniform values in onDraw method.
"},{"location":"prefx-pipeline/#add-pre-fx-pipeline-instance","title":"Add pre-fx pipeline instance","text":"
var pipelineManager = scene.sys.renderer.pipelines;\nvar pipelineInstance = pipelineManager.add(PreFxName, new MyPreFxClass(scene.game));\n
"},{"location":"prefx-pipeline/#apply-effect","title":"Apply effect","text":"
gameObject.setPipeline(pipelineInstance);\n

Will replace current effect instance.

"},{"location":"prefx-pipeline/#get-pre-fx-pipeline","title":"Get pre-fx pipeline","text":"
var pipelineInstance = gameObject.pipeline;\n
"},{"location":"prefx-pipeline/#reset-to-default-effect","title":"Reset to default effect","text":"
gameObject.resetPipeline();\n
"},{"location":"prefx-pipeline/#unregister-pre-fx-pipeline","title":"Unregister pre-fx pipeline","text":"
var pipelineManager = scene.sys.renderer.pipelines;\npipelineManager.remove(PreFxName);\n
"},{"location":"quad-image/","title":"Image","text":""},{"location":"quad-image/#introduction","title":"Introduction","text":"

Image with 4 or 9 vertex control points.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"quad-image/#live-demos","title":"Live demos","text":"
  • Quad image
  • Nine points
"},{"location":"quad-image/#usage","title":"Usage","text":"

Sample code

"},{"location":"quad-image/#install-plugin","title":"Install plugin","text":""},{"location":"quad-image/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquadimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquadimageplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexQuadImage(x, y, texture, frame, config);\n
"},{"location":"quad-image/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuadImagePlugin from 'phaser3-rex-plugins/plugins/quadimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuadImagePlugin',\nplugin: QuadImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexQuadImage(x, y, texture, frame, config);\n
"},{"location":"quad-image/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { QuadImage } from 'phaser3-rex-plugins/plugins/quadimage.js';\n
  • Add image object
    var image = new QuadImage(scene, x, y, texture, frame, config);\nscene.add.existing(image);\n
"},{"location":"quad-image/#create-instance","title":"Create instance","text":"
var image = scene.add.rexQuadImage(x, y, texture, frame, {\n// ninePointMode: false,\n});\n

or

var image = scene.add.rexQuadImage({\n// x: 0,\n// y: 0,\nkey,\n// frame: null,\n// ninePointMode: false,\n// rtl: false\n});\n
  • ninePointMode :
    • true : Add 9 vertex control points.
    • false : Add 4 vertex control points. Default behavior.
  • rtl : Diagonal direction in 4 vertices mode.
    • true : Diagonal from right to left
    • false : Diagonal from left to right. Default behavior.

Add quadimage from JSON

var quadimage = scene.make.rexQuadImage({\nx: 0,\ny: 0,\n\nkey: null,\nframe: null,\n\n// ninePointMode: false,\n// rtl: false\n\nadd: true\n});\n
"},{"location":"quad-image/#custom-class","title":"Custom class","text":"
  • Define class
    class MyQuadImage extends QuadImage {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyQuadImage(scene, x, y, texture, frame, config);\n
"},{"location":"quad-image/#vertex-control-points","title":"Vertex control points","text":"
  • Array of vertex control points
    var controlPoints = image.controlPoints;\n
    • 4, or 9 vertex control points
  • 4 vertex control points
    var topLeftPoint = image.topLeft;         // image.controlPoints[0]\nvar topRightPoint = image.topRight;       // image.controlPoints[1]\nvar bottomLeftPoint = image.bottomLeft;   // image.controlPoints[2]\nvar bottomRightPoint = image.bottomRight; // image.controlPoints[3]\n
  • 9 vertex control points
    var topLeft = image.topLeft;               // image.controlPoints[0]\nvar topCenter = image.topCenter;           // image.controlPoints[1]\nvar topRight = image.topRight;             // image.controlPoints[2]\nvar centerLeft = image.centerLeft;         // image.controlPoints[3]\nvar center = image.center;                 // image.controlPoints[4]\nvar centerRight = image.centerRight;       // image.controlPoints[5]\nvar bottomLeft = image.bottomLeft;         // image.controlPoints[6]\nvar bottomCenter = image.bottomCenter;     // image.controlPoints[7]\nvar bottomRight = image.bottomRight;       // image.controlPoints[8]\n
"},{"location":"quad-image/#position","title":"Position","text":"
  • Get
    var worldXY = controlPoint.getWorldXY();\nvar x = worldXY.x;\nvar y = worldXY.y;\n
    or
    var x = controlPoint.x;\nvar y = controlPoint.y;\n
  • Set
    controlPoint.setPosition(x, y);\n// controlPoint.setWorldXY(x, y);\n
    or
    controlPoint.x = x;\ncontrolPoint.y = y;\n
"},{"location":"quad-image/#tint-color","title":"Tint color","text":"
  • Get
    var color = image.tint;\n
  • Set
    image.tint = color;\n
    or
    image.setTint(color);\n
"},{"location":"quad-image/#other-properties","title":"Other properties","text":"

See Mesh game object, game object

"},{"location":"quad-image/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"quad-image/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"quad-rendertexture/","title":"Render texture","text":""},{"location":"quad-rendertexture/#introduction","title":"Introduction","text":"

Render texture with 4 or 9 vertex control points.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"quad-rendertexture/#live-demos","title":"Live demos","text":"
  • RenderTexture
"},{"location":"quad-rendertexture/#usage","title":"Usage","text":"

Sample code

"},{"location":"quad-rendertexture/#install-plugin","title":"Install plugin","text":""},{"location":"quad-rendertexture/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquadimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquadimageplugin.min.js', true);\n
  • Add render texture object
    var image = scene.add.rexQuadRenderTexture(x, y, width, height, config);\n
"},{"location":"quad-rendertexture/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuadImagePlugin from 'phaser3-rex-plugins/plugins/quadimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuadImagePlugin',\nplugin: QuadImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add render texture object
    var image = scene.add.rexQuadRenderTexturege(x, y, width, height, config);\n
"},{"location":"quad-rendertexture/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { QuadRenderTexture } from 'phaser3-rex-plugins/plugins/quadimage.js';\n
  • Add render texture object
    var image = new QuadRenderTexture(scene, x, y, width, height, config);\nscene.add.existing(image);\n
"},{"location":"quad-rendertexture/#create-instance","title":"Create instance","text":"
var image = scene.add.rexQuadRenderTexturege(x, y, width, height, {\n// hideCCW: true,\n// ninePointMode: false,\n});\n

or

var image = scene.add.rexQuadRenderTexturege({\n// x: 0,\n// y: 0,\n// width: 32,\n// height: 32,\n// hideCCW: true,\n// ninePointMode: false,\n});\n
  • ninePointMode :
    • true : Add 9 vertex control points.
    • false : Add 4 vertex control points. Default behavior.

Add prespective render texture from JSON

var image = scene.make.rexQuadRenderTexturege({\nx: 0,\ny: 0,    width: 32,\nheight: 32,\n\n// hideCCW: false,\n// ninePointMode: false,\n\nadd: true\n});\n
"},{"location":"quad-rendertexture/#custom-class","title":"Custom class","text":"
  • Define class
    class MyQuadRenderTexturege extends QuadRenderTexturege {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyQuadRenderTexturege(scene, x, y, width, height, config);\n
"},{"location":"quad-rendertexture/#internal-render-texture","title":"Internal render texture","text":"
var rt = image.rt;\n
  • rt : Render texture
"},{"location":"quad-rendertexture/#paste-texture","title":"Paste texture","text":"
  • Paste game object
    image.rt.draw(gameObject, x, y);\n// image.rt.draw(gameObject, x, y, alpha, tint);\n
  • gameObject : a game object, or an array of game objects
  • Paste game objects in a group
    image.rt.draw(group, x, y);\n// image.rt.draw(group, x, y, alpha, tint);\n
  • Paste game objects in a scene
    image.rt.draw(scene.children, x, y);\n// image.rt.draw(scene.children, x, y, alpha, tint);\n
  • Paste texture
    image.rt.draw(key, x, y);\n// image.rt.draw(key, x, y, alpha, tint);\n
    or
    image.rt.drawFrame(key, frame, x, y);\n// image.rt.drawFrame(key, frame, x, y, alpha, tint);\n
    • key : The key of the texture to be used, as stored in the Texture Manager.
  • Snapshop game objects
    image.snapshot(gameObjects);\n
    • gameObjects : Array of game objects.
"},{"location":"quad-rendertexture/#erase","title":"Erase","text":"
image.rt.erase(gameObject, x, y);\n
  • gameObject : a game object, or an array of game objects
"},{"location":"quad-rendertexture/#clear","title":"Clear","text":"
image.rt.clear();\n
"},{"location":"quad-rendertexture/#fill","title":"Fill","text":"
image.rt.fill(rgb, alpha);\n// image.rt.fill(rgb, alpha, x, y, width, height);\n
"},{"location":"quad-rendertexture/#other-properties","title":"Other properties","text":"

See Quad image game object, Mesh game object, game object

"},{"location":"quad-rendertexture/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"quad-rendertexture/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"quest/","title":"Quest","text":""},{"location":"quest/#introduction","title":"Introduction","text":"

Question manager.

  • Author: Rex
  • Member of scene, or game object
"},{"location":"quest/#live-demos","title":"Live demos","text":"
  • (CSV) Branch
  • (YAML) Branch
  • Shuffle
"},{"location":"quest/#usage","title":"Usage","text":"

Sample code

"},{"location":"quest/#install-plugin","title":"Install plugin","text":""},{"location":"quest/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquestplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquestplugin.min.js', true);\n
  • Add quest-manager object
    var questionManager = scene.plugins.get('rexquestplugin').add(config);\n
"},{"location":"quest/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuestPlugin from 'phaser3-rex-plugins/plugins/quest-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuest',\nplugin: QuestPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add quest-manager object
    var questionManager = scene.plugins.get('rexQuest').add(config);\n
"},{"location":"quest/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Quest from 'phaser3-rex-plugins/plugins/quest.js';\n
  • Add quest-manager object
    var questionManager = new Quest(config);\n
"},{"location":"quest/#question-manager","title":"Question manager","text":""},{"location":"quest/#create-question-manager-instance","title":"Create question manager instance","text":"
var questionManager = scene.plugins.get('rexQuest').add({\nquestions: undefined,\n// format: undefined,\n// delimiter: ',',\n// types: {\n//     question: 'q',\n//     option: '',\n// },\n// convert: true,\n\nquest: undefined,\n// quest: {\n//     shuffleQuestions: false,\n//     shuffleOptions: false,\n// }\n});\n
  • format : Input data (parameter question) format.
    • 'csv' : Input data is a csv string
    • 'yaml' : Input data is a yaml string represented multiple documents, or an array of yaml string for each document.
    • 'json' : Input data is a json string.
    • undefined : Input data is a plain array of questions, don' parse it.
  • questions : Input data of questions.
    • A plain array of questions. Parsing result of other input formats.
      [\n{\nkey: q0,\nparam0: value0,\nparam1: value1,\nparam2: value2,\noptions: [\n{\nkey: o0,\nparam0: value0,\nparam1: value1,\n// ...\n},\n{\nkey: o1,\nparam0: value0,\nparam1: value1,\n// ...\n}\n]\n},\n{\nkey: q1,\nparam0: value0,\nparam1: value1,\nparam2: value2,\noptions: [\n{\nkey: o0,\nparam0: value0,\nparam1: value1,\n// ...\n},\n{\nkey: o1,\nparam0: value0,\nparam1: value1,\n// ...\n}\n]\n},\n]\n
      • Question object : {key, options, param, ...}
        • key : An unique key string. Create a key string '_' + serialNumber if not given.
        • options : An array of option objects.
        • Other key-value parameters.
      • Option object : {key, param, ...}
        • key : An unique key string. Create a key string '_' + serialNumber if not given.
        • Other key-value parameters.
    • A yaml string represented multiple documents, will parse it to array of questions.
      key: q0\nparam0: value0\nparam1: value1\noptions:\n- key: o0\nparam0: value0\nparam1: value1\n- key: o1\nparam0: value0\nparam1: value1\n---\nkey: q1\nparam0: value0\nparam1: value1\noptions:\n- key: o0\nparam0: value0\nparam1: value1\n- key: o1\nparam0: value0\nparam1: value1\n
    • An array of yaml strings for each document, will parse them to array of questions.
    • A csv string, will parse it to array of questions.
      type,key,param0,param1,...\nq,q0,value0,value1,...\n,o0,value0,value1,...\n,o1,value0,value1,...\nq,q1,value0,value1,...\n,o0,value0,value1,...\n,o1,value0,value1,...\n
      • Fields in first row
        • type : Type of this row. These values can be redefined via types in configuration object.
        • q : A row of question object.
        • Empty string : A row of option object belong a question object.
        • key : Unique key string. Create a key string '_' + serialNumber if this field does not exist.
        • Other fields.
    • A json string, will parse it to array of questions.
  • delimiter : Delimiter of csv string. Default value is ','
  • types : Define value of row type.
    • types.question : Define value of question row. Default value is q.
    • types.option : Define value of option row. Default value is '' (empty string).
  • convert : Convert string values to other types.
    • Default type converting : Convert string to number, boolean, null, or string
      • '0', '1', ... (number string) -> number
      • 'true', or 'false' -> true or false
      • '' (empty string) -> null
      • Others : string.
    • Set false to ignore types converting, i.e. all values are string.
    • A custom type converting function :
      function(stringValue, key) {\n// return value;\n}\n
  • quest : Create a private quest task object.
    • undefined : Don't create a private quest task object.
    • true : Create a private quest task object with default configuration.
    • Configuration of quest task :
      • quest.shuffleQuestions : Set true to shuffle questions.
      • quest.shuffleOptions : Set true to shuffle options.
"},{"location":"quest/#add-questions","title":"Add questions","text":"
questionManager.add(questions, config);\n
  • questions : An array of question objects, or a csv string. See questions section in Create question manager instance section.
  • config :
    • delimiter : Delimiter of csv string. Default value is ','
    • types : Define value of row type.
      • types.question : Define value of question row. Default value is q.
      • types.option : Define value of option row. Default value is '' (empty string).
    • convert : Convert string values to other types.
      • Default type converting : Convert string to number, boolean, null, or string
        • '0', '1', ... (number string) -> number
        • 'true', or 'false' -> true or false
        • '' (empty string) -> null
        • Others : string.
      • Set false to ignore types converting, i.e. all values are string.
      • A custom type converting function :
        function(stringValue, key) {\n// return value;\n}\n
"},{"location":"quest/#remove-question","title":"Remove question","text":"
  • Remove a question object
    questionManager.remove(key);\n
    • key : An unique key string.
  • Remove all question objects
    questionManager.removeAll();\n
"},{"location":"quest/#get-question","title":"Get question","text":"
  • Get a question object
    var question = questionManager.get(key);\n
  • Get all keys of question objects
    var questionKeys = questionManager.getKeys();\n// var out = questionManager.getKeys(out);\n
    • questionKeys : Array of question key string.
"},{"location":"quest/#question-is-existed","title":"Question is existed","text":"
var isExisted = questionManager.has(key);\n
"},{"location":"quest/#array-of-questions","title":"Array of questions","text":"
var questions = questionManager.questions;\n

Rearrange items of this questions array to reorder questions in quest task.

"},{"location":"quest/#get-option","title":"Get option","text":"
var option = questionManager.getOption(question, optionKey);\n
  • question : A question object, or a question key string.
  • optionKey : A option key string.
"},{"location":"quest/#private-quest-task","title":"Private quest task","text":""},{"location":"quest/#create-private-quest-task","title":"Create private quest task","text":"

Each question manager can hava a private quest task object, created when creating question manager, or

questionManager.startQuest(config);\n
  • config :
    • shuffleQuestions : Set true to shuffle questions.
    • shuffleOptions : Set true to shuffle options.
"},{"location":"quest/#get-next-question-object","title":"Get next question object","text":"
  • Get next question object
    var question = questionManager.getNextQuestion();\n
  • Get next question object via question key
    var question = questionManager.getNextQuestion(questionKey);\n
"},{"location":"quest/#event","title":"Event","text":"
  • Fire 'quest' when calling questionManager.getNextQuestion()
    questionManager.on('quest', function(question, questionManager, quest){\n// questionManager.getNextQuestion();\n})\n
    • question : Question object.
      • question.options : Option objects of this question.
    • questionManager : Question manager.
    • quest : Quest task.
"},{"location":"quest/#is-last-question","title":"Is last question","text":"
var isLast = questionManager.isLastQuestion();\n
"},{"location":"quest/#restart-quest-task","title":"Restart quest task","text":"
questionManager.restartQuest();\n
"},{"location":"quest/#private-data","title":"Private data","text":"
  • Get data
    var value = questionManager.getData(key, defaultValue);\n
  • Get all data
    var data = questionManager.getData();\n
  • Set value
    questionManager.setData(key, value);\n
  • Increase value
    questionManager.incData(key, inc, defaultValue);\n
  • Multiple value
    questionManager.mulData(key, mul, defaultValue);\n
  • Clear all data
    questionManager.clearData();\n
"},{"location":"quest/#quest-task","title":"Quest task","text":"

Create new quest task if user needs more then 1 quest task.

"},{"location":"quest/#create-quest-task","title":"Create quest task","text":"
var quest = questionManager.newQuest(config);\n
  • config :
    • shuffleQuestions : Set true to shuffle questions.
    • shuffleOptions : Set true to shuffle options.
"},{"location":"quest/#get-next-question-object_1","title":"Get next question object","text":"
  • Get next question object
    var question = quest.getNextQuestion();\n
  • Get next question object via question key
    var question = quest.getNextQuestion(questionKey);\n
"},{"location":"quest/#event_1","title":"Event","text":"
  • Fire 'quest' when calling questionManager.getNextQuestion()
    quest.on('quest', function(question, questionManager, quest){\n// questionManager.getNextQuestion();\n})\n
    • question : Question object.
      • question.options : Option objects of this question.
    • questionManager : Question manager.
    • quest : Quest task.
"},{"location":"quest/#is-last-question_1","title":"Is last question","text":"
var isLast = quest.isLastQuestion();\n
"},{"location":"quest/#restart-quest-task_1","title":"Restart quest task","text":"
quest.start();\n
"},{"location":"quest/#private-data_1","title":"Private data","text":"
  • Get data
    var value = quest.getData(key, defaultValue);\n
  • Get all data
    var data = quest.getData();\n
  • Set value
    quest.setData(key, value);\n
  • Increase value
    quest.incData(key, inc, defaultValue);\n
  • Multiple value
    quest.mulData(key, inc, defaultValue);\n
  • Clear all data
    quest.clearData();\n
"},{"location":"quest/#get-option_1","title":"Get option","text":"
var option = quest.getOption(question, optionKey);\n
  • question : A question object, or a question key string, or undefined to get current question object.
  • optionKey : A option key string.
"},{"location":"random-data-generator/","title":"Random data generator","text":""},{"location":"random-data-generator/#introduction","title":"Introduction","text":"

Get random value from a random generator, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"random-data-generator/#usage","title":"Usage","text":""},{"location":"random-data-generator/#random-data-generator","title":"Random data generator","text":"
  • Pre-defined random data generator
    var rnd = Phaser.Math.RND;\n
  • New random generator
    var rnd = new Phaser.Math.RandomDataGenerator(seed);\n
"},{"location":"random-data-generator/#set-seed","title":"Set seed","text":"
  • Set seed in game config for pre-defined random data generator
    var config = {\n// ...\nseed: seed,\n// ...\n}\nvar game = new Phaser.Game(config);\n
    • seed :
      • An array of string, like [(Date.now() * Math.random()).toString()]
  • Set seed
    rnd.init(seed);\n
    • seed : A string or an array of string.
"},{"location":"random-data-generator/#get-random-value","title":"Get random value","text":"
  • Random real number between 0 and 1.
    var value = rnd.frac();\n
  • Random integer between 0 and 2^32.
    var value = rnd.integer();\n
  • Random real number between 0 and 2^32.
    var value = rnd.real();\n
  • Random integer between and including min and max.
    var value = rnd.between(min, max);\n// var value = rnd.integerInRange(min, max);\n
  • Random real number between min and max.
    var value = rnd.realInRange(min, max);\n
  • Random real number between -1 and 1.
    var value = rnd.normal();\n
  • Random angle between -180 and 180.
    var angle = rnd.angle();\n
  • Random rotation in radians, between -3.141 and 3.141.
    var angle = rnd.rotation();\n
  • Random timestamp between min and max.
    var timestamp = rnd.timestamp(min, max);\n
    • min : Default value is the beginning of 2000.
    • max : Default value is the end of 2020.
  • UUID
    var uuid = rnd.uuid();\n
  • Random sign value
    var sign = rnd.sign();\n
    • sign : -1 or 1
"},{"location":"random-data-generator/#get-random-item","title":"Get random item","text":"
  • Random element from within the given array.
    var item = rnd.pick(arr);\n
  • Random element from within the given array, favoring the earlier entries.
    var item = rnd.weightedPick(arr);\n
"},{"location":"random-data-generator/#shuffle-array","title":"Shuffle array","text":"
var arr = rnd.shuffle(arr);\n
"},{"location":"random/","title":"Random number","text":""},{"location":"random/#introduction","title":"Introduction","text":"

Get random value, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"random/#usage","title":"Usage","text":""},{"location":"random/#get-random-value-between-min-max","title":"Get random value between (min, max)","text":"
  • Random integer
    var value = Phaser.Math.Between(min, max);\n
  • Random floating point number
    var value = Phaser.Math.FloatBetween(min, max);\n
"},{"location":"random/#get-random-vector","title":"Get random vector","text":"
  • 2D vector
    var vec = Phaser.Math.RandomXY(vec);    // return vec {x, y}\n// var vec = Phaser.Math.RandomXY(vec, scale);\n
  • 3D vector
    var vec = Phaser.Math.RandomXYZ(vec);    // return vec {x, y, z}\n// var vec = Phaser.Math.RandomXYZ(vec, scale);\n
  • 4D vector
    var vec = Phaser.Math.RandomXYZW(vec);    // return vec {x, y, z, w}\n// var vec = Phaser.Math.RandomXYZW(vec, scale);\n
"},{"location":"randomplace/","title":"Random place","text":""},{"location":"randomplace/#introduction","title":"Introduction","text":"

Place objects randomly inside an area without overlapping.

  • Author: Rex
  • Methods
"},{"location":"randomplace/#live-demos","title":"Live demos","text":"
  • Random place
"},{"location":"randomplace/#usage","title":"Usage","text":"

Sample code

"},{"location":"randomplace/#install-plugin","title":"Install plugin","text":""},{"location":"randomplace/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrandomplaceplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrandomplaceplugin.min.js', true);\n
  • Random place objects
    scene.plugins.get('rexrandomplaceplugin').randomPlace(gameObjects, config);\n
"},{"location":"randomplace/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RandomPlacePlugin from 'phaser3-rex-plugins/plugins/randomplace-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRandomPlace',\nplugin: RandomPlacePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Random place objects
    scene.plugins.get('rexRandomPlace').randomPlace(gameObjects, config);\n
"},{"location":"randomplace/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RandomPlace from 'phaser3-rex-plugins/plugins/randomplace.js';\n
  • Random place objects
    RandomPlace(gameObjects, config);\n
"},{"location":"randomplace/#random-place","title":"Random place","text":"
scene.plugins.get('rexRandomPlace').randomPlace(gameObjects, {\nradius: radius,\n\ngetPositionCallback: undefined,\narea: areaGeomObject,\n});\n
  • gameObjects : An array of gameObjects. Each item can be
    • A game objects.
    • A plain object contains
      {\ngameObject: gameObject,\nradius: radius,\n}\n
      • radius : Collision radius of this game object.
  • radius : Default collision radius of each game object.
  • getPositionCallback : A callback to get a random position.
    • undefined : Use area.getRandomPoint(out) as callback.
    • A function object :
      function(out) {\nout.x = 0;\nout.y = 0;\n}\n
  • area : A geom object, which has getRandomPoint method.
    • A circle : new Phaser.Geom.Circle(x, y, radius)
    • A rectangle : new Phaser.Geom.Rectangle(x, y, width, height)
    • A triangle : new Phaser.Geom.Triangle(x1, y1, x2, y2, x3, y3)
    • An ellipse : new Phaser.Geom.Ellipse(x, y, width, height)
    • undefined : A rectangle (0, 0, gameWidth, gameHeight)
"},{"location":"raycaster/","title":"Raycaster","text":""},{"location":"raycaster/#introduction","title":"Introduction","text":"

Raycaster between obstacles.

  • Author: Rex
  • Member of scene
"},{"location":"raycaster/#live-demos","title":"Live demos","text":"
  • Reflaction
"},{"location":"raycaster/#usage","title":"Usage","text":"

Sample code

"},{"location":"raycaster/#install-plugin","title":"Install plugin","text":""},{"location":"raycaster/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexraycasterplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexraycasterplugin.min.js', true);\n
  • Add raycaster object
    var raycaster = scene.plugins.get('rexraycasterplugin').add(config);\n
"},{"location":"raycaster/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RaycasterPlugin from 'phaser3-rex-plugins/plugins/raycaster-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRaycaster',\nplugin: RaycasterPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add raycaster object
    var raycaster = scene.plugins.get('rexRaycaster').add(config);\n
"},{"location":"raycaster/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Raycaster from 'phaser3-rex-plugins/plugins/raycaster.js';\n
  • Add raycaster object
    var raycaster = new Raycaster(config);\n
"},{"location":"raycaster/#create-instance","title":"Create instance","text":"
var raycaster = scene.plugins.get('rexRaycaster').add({\n// maxRayLength: 10000\n});\n
  • maxRayLength : Max length of ray.
"},{"location":"raycaster/#obstacle","title":"Obstacle","text":""},{"location":"raycaster/#add","title":"Add","text":"
raycaster.addObstacle(gameObject);\n// raycaster.addObstacle(gameObject, polygon);\n
  • polygon : A polygon.
    • undefined : Created polygon from 4 vertics of game object.

or

raycaster.addObstacle(gameObjects);\n
  • gameObjects : Array of game object.
"},{"location":"raycaster/#remove","title":"Remove","text":"
raycaster.removeObstacle(gameObject);\n
  • gameObject : A game object, or an array of game objects.
"},{"location":"raycaster/#clear","title":"Clear","text":"
raycaster.clearObstacle();\n
"},{"location":"raycaster/#update-shape","title":"Update shape","text":"
raycaster.updateObstacle(gameObject);\n// raycaster.updateObstacle(gameObject, polygon);\n
  • polygon : A polygon.
    • undefined : Created polygon from 4 vertics of game object.
"},{"location":"raycaster/#raycaster","title":"Raycaster","text":"
var result = raycaster.rayToward(x, y, angle);\n
  • x, y : Emit ray from world-position.
  • angle : Emit ray toward to angle, in radian.
  • result :
    • false : Ray dose not hit any game object.
    • An object : Hit to a game object.
      {\ngameObject,\npolygon,\nsegment,\nx, y,\nreflectAngle\n}\n
      • gameObject : Hitting game object.
      • polygon : Polygon of hitting game object.
      • segment : Segment(line) of hitting polygon.
      • x, y : World position of hitting
      • reflectAngle : Reflect angle, in radian.

Reflection

Use result.x, result.y, result.reflectAngle for next reflection ray.

raycaster.rayToward(result.x, result.y, result.reflectAngle)\n

"},{"location":"realtimetimers/","title":"Real time timers","text":""},{"location":"realtimetimers/#introduction","title":"Introduction","text":"

Start and counting timer by real-time timestamp.

Note

Not support pause, or timescale features.

  • Author: Rex
  • Member of scene, or game object
"},{"location":"realtimetimers/#live-demos","title":"Live demos","text":"
  • Progress
"},{"location":"realtimetimers/#usage","title":"Usage","text":"

Sample code

"},{"location":"realtimetimers/#install-plugin","title":"Install plugin","text":""},{"location":"realtimetimers/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrealtimetimersplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrealtimetimersplugin.min.js', true);\n
  • Add real-time timers object
    var realTimeTimers = scene.plugins.get('rexrealtimetimersplugin').add(config);\n
"},{"location":"realtimetimers/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RealTimeTimersPlugin from 'phaser3-rex-plugins/plugins/realtimetimers-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRealTimeTimers',\nplugin: RealTimeTimersPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add real-time timers object
    var realTimeTimers = scene.plugins.get('rexRealTimeTimers').add(config);\n
"},{"location":"realtimetimers/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RealTimeTimers from 'phaser3-rex-plugins/plugins/realtimetimers.js';\n
  • Add real-time timers object
    var realTimeTimers = new RealTimeTimers(config);\n
"},{"location":"realtimetimers/#create-instance","title":"Create instance","text":"
var realTimeTimers = scene.plugins.get('rexRealTimeTimers').add({\n// startTimestamp: new Date().getTime(),\n// getTimestampCallback: functio() { return timestamp; }\n});\n
  • getTimestampCallback : Custom callback of get current timestamp, optional.
    • Default behavior is getting current timestamp from system.
  • startTimestamp : Start time, optional. Use this start-timestamp if getTimestampCallback is not given.
    • Default value is current timestamp new Date().getTime().
"},{"location":"realtimetimers/#set-start-timestamp","title":"Set start timestamp","text":"

Start-timestamp is set when creating this real-time timers object.

User still can change Start-timestamp by

realTimeTimers.setStartTimestamp(timestamp);\n

This changing won't affect existed timers.

"},{"location":"realtimetimers/#add-a-timer","title":"Add a timer","text":"
realTimeTimers.addTimer(name, period);\n// realTimeTimers.addTimer(name, period, data);\n// realTimeTimers.addTimer(name, period, data, currentTimestamp);\n
  • name : Any name string of this timer.
  • period : Will expire after period time, in millisecond.
  • data : Any kind of custom data.
  • currentTimestamp : Start this time in current time, optional.
    • undefined : Get current timestamp from getTimestampCallback callback.

or

realTimeTimers.addTimer(name, {\nday: dayCount,        // d: dayCount,\nhour: hourCount,      // h: hourCount,\nminute: minuteCount,  // m: minuteCount,\nsecond: secondCount,  // s: secondCount,\n}, data, currentTimestamp);\n
  • Sum period by
    • day, or d : Day count
    • hour, or h : Hour count
    • minute, or m : Minute count
    • second, or s : Second count
"},{"location":"realtimetimers/#increase-period","title":"Increase period","text":"
realTimeTimers.incTimerPeriod(name, period);\n
  • name : Any name string of this timer.
  • period : Will expire after period time, in millisecond.

or

realTimeTimers.incTimerPeriod(name, {\nday: dayCount,        // d: dayCount,\nhour: hourCount,      // h: hourCount,\nminute: minuteCount,  // m: minuteCount,\nsecond: secondCount,  // s: secondCount,\n});\n

Will trigger 'update' event.

"},{"location":"realtimetimers/#expire-timers","title":"Expire timers","text":"
  • Get expired timers
    var timers = realTimeTimers.getExpiredTimers();\n// var timers = realTimeTimers.getExpiredTimers(currentTimestamp);\n
    • timers : Array of expired timers. Each timer include these properties -
      {\nname: name,\nstart: timestamp,\nperiod: time\n}\n
    • currentTimestamp : Start this time in current time, optional.
      • undefined : Get current timestamp from getTimestampCallback callback.
  • Pop(get and remove) expired timers
    var timers = realTimeTimers.popExpiredTimers();\n// var timers = realTimeTimers.popExpiredTimers(currentTimestamp);\n
    • currentTimestamp : Start this time in current time, optional.
      • undefined : Get current timestamp from getTimestampCallback callback.
  • Get progress of timer
    var result = realTimeTimers.getTimersProgress()\n// var result = realTimeTimers.getTimersProgress(currentTimestamp);\n
    • currentTimestamp : Start this time in current time, optional.
      • undefined : Get current timestamp from getTimestampCallback callback.
    • result : Array of timer's progress. Include these properties -
      {\nname: name,\nperiod: time,\nelapsed: time,\nprogress: t    // elapsed/period\ntimer: timerObject\n}\n
      • timer : Timer object, can remove this timer object by
        realTimeTimers.removeTimers(timer);\n
"},{"location":"realtimetimers/#get-timers","title":"Get timers","text":"
  • Get last added timer
    var timer = realtimetimers.lastTimer;\n
  • Get all timers
    var timers = realtimetimers.getTimers();\n
  • Get timers by name.
    var timers = realtimetimers.getTimers(name);\n
  • Amount of total timers
    var amount = realtimetimers.length;\n
"},{"location":"realtimetimers/#remove-timers","title":"Remove timers","text":"
  • Remove timers by name
    realtimetimers.removeTimers(name);\n
  • Remove timer object
    realtimetimers.removeTimers(timer);\n
    • timer : A timer object, or an array of timer objects.
  • Remove all timers
    realtimetimers.clearTimers();\n
"},{"location":"realtimetimers/#states","title":"States","text":"
  • Get states in plain object
    var states = realtimetimers.toJSON();\n
  • Get states in JSON string. Can store this JSON string into webstorage or server.
    var s = JSON.stringify(realtimetimers);\n
  • Set states by plain object
    realtimetimers.resetFromJSON(states)\n
"},{"location":"realtimetimers/#events","title":"Events","text":"
  • On add a timer
    realtimetimers.on('add', function(timer, timers){ })\n
    • timer : Added timer.
      {\nname: name,\nstart: timestamp,\nperiod: time\n}\n
    • timers : Total timers after adding.
  • On remove a timer
    realtimetimers.on('remove', function(timer, timers){ })\n
    • timer : Removed timer.
      {\nname: name,\nstart: timestamp,\nperiod: time\n}\n
    • timers : Total timers after removing.
  • On timers updated (add, remove, or increas period).
    realtimetimers.on('update', function(timers){ var s = JSON.stringify(realtimetimers);\n// Store current states to webstorage or server here.\n})\n
    • timers : Total timers after updating.
"},{"location":"rendertexture/","title":"Render texture","text":""},{"location":"rendertexture/#introduction","title":"Introduction","text":"

Paste game objects or textures on dynaimc texture, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"rendertexture/#usage","title":"Usage","text":""},{"location":"rendertexture/#add-render-texture-object","title":"Add render texture object","text":"
  • Create an empty render texture object.
    var rt = scene.add.renderTexture(x, y, width, height);\n

Add render texture from JSON

var rt = scene.make.renderTexture({\nx: 0,\ny: 0,\nwidth: 32,\nheight: 32,\n\n// angle: 0,\n// alpha: 1\n// flipX: true,\n// flipY: true,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n

Origin position

Origin position of this render texture is (0,0) (top-left)

"},{"location":"rendertexture/#custom-class","title":"Custom class","text":"
  • Define class
    class MyRenderTexture extends Phaser.GameObjects.RenderTexture {\nconstructor(scene, x, y, width, height) {\nsuper(scene, x, y, width, height);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var rt = new MyRenderTexture(scene, x, y, width, height);\n
"},{"location":"rendertexture/#set-size","title":"Set size","text":"
rt.setSize(width, height);\n
"},{"location":"rendertexture/#fill-color","title":"Fill color","text":"
rt.fill(rgb);\n// rt.fill(rgb, alpha, x, y, width, height);\n
  • rgb : The number color to fill this Dynamic Texture with.
  • alpha : The alpha value used by the fill. Default value is 1.
  • x, y, width, height : The area of the fill rectangle. Default behavior is filling whole size.
"},{"location":"rendertexture/#clear","title":"Clear","text":"
rt.clear();\n
rt.clear(x, y, width, height);\n
"},{"location":"rendertexture/#draw-game-object","title":"Draw game object","text":"
rt.draw(entries);\n// rt.draw(entries,x, y);\n// rt.draw(entries, x, y, alpha, tint);\n
  • entries :
    • Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
    • Tilemap Layers.
    • A Group. The contents of which will be iterated and drawn in turn.
    • A Container. The contents of which will be iterated fully, and drawn in turn.
    • A Scene Display List. Pass in Scene.children to draw the whole list.
    • Another Dynamic Texture, or a Render Texture.
    • A Texture Frame instance.
    • A string. This is used to look-up the texture from the Texture Manager.
  • x, y : The x/y position to draw the Frame at, or the offset applied to the object.
    • If the object is a Group, Container or Display List, the coordinates are added to the positions of the children.
    • For all other types of object, the coordinates are exact.
  • alpha, tint : Only used by Texture Frames.
    • Game Objects use their own alpha and tint values when being drawn.
"},{"location":"rendertexture/#erase","title":"Erase","text":"
rt.erase(entries);\n// rt.erase(entries, x, y);\n
  • entries :
    • Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
    • Tilemap Layers.
    • A Group. The contents of which will be iterated and drawn in turn.
    • A Container. The contents of which will be iterated fully, and drawn in turn.
    • A Scene Display List. Pass in Scene.children to draw the whole list.
    • Another Dynamic Texture, or a Render Texture.
    • A Texture Frame instance.
    • A string. This is used to look-up the texture from the Texture Manager.
  • x, y : The x/y position to draw the Frame at, or the offset applied to the object.
    • If the object is a Group, Container or Display List, the coordinates are added to the positions of the children.
    • For all other types of object, the coordinates are exact.
"},{"location":"rendertexture/#draw-frame","title":"Draw frame","text":"
rt.stamp(key, frame, x, y, {\nalpha: 1,\ntint: 0xffffff,\nangle: 0,\nrotation: 0,\nscale: 1,\nscaleX: 1,\nscaleY: 1,\noriginX: 0.5,\noriginY: 0.5,\nblendMode: 0,\nerase: false,\nskipBatch: false\n})\n

or

rt.drawFrame(key, frame, x, y);\n// rt.drawFrame(key, frame, x, y, alpha, tint);\n
  • x, y : Top-left position
"},{"location":"rendertexture/#draw-repeat-frames","title":"Draw repeat frames","text":"
  • Repeat frames full of size
    rt.repeat(key, frame);\n
  • Repeat in an area
    rt.repeat(key, frame, x, y, width, height);\n// rt.repeat(key, frame, x, y, width, height, alpha, tint, skipBatch);\n
"},{"location":"rendertexture/#batch-draw","title":"Batch draw","text":"
  1. Begin
    rt.beginDraw();\n
  2. Draw
    • Draw game object
      rt.batchDraw(entries, x, y, alpha, tint);\n
      • entries :
        • Any renderable Game Object, such as a Sprite, Text, Graphics or TileSprite.
        • Tilemap Layers.
        • A Group. The contents of which will be iterated and drawn in turn.
        • A Container. The contents of which will be iterated fully, and drawn in turn.
        • A Scene Display List. Pass in Scene.children to draw the whole list.
        • Another Dynamic Texture, or a Render Texture.
        • A Texture Frame instance.
        • A string. This is used to look-up the texture from the Texture Manager.
    • Draw frame
      rt.batchDrawFrame(key, frame, x, y, alpha, tint);\n
    • Draw image
      rt.stamp(key, frame, x, y, {\n// ...\nskipBatch: true\n})\n
    • Draw repeat images
      rt.repeat(key, frame, x, y, width, height, alpha, tint, true);\n
  3. End
    rt.endDraw();\n
"},{"location":"rendertexture/#internal-camera","title":"Internal camera","text":"

Internal camera rt.camera

  • Scroll (offset)
    rt.camera.setScroll(x, y);\n
  • Zoom (scale)
    rt.camera.setZoom(zoom);\n
  • Rotate
    rt.camera.setAngle(angle);  // angle in degrees\n
"},{"location":"rendertexture/#snapshot","title":"Snapshot","text":""},{"location":"rendertexture/#snapshot-area","title":"Snapshot area","text":"
texture.snapshot(callback);\n// texture.snapshot(callback, type, encoderOptions);\n

or

texture.snapshotArea(x, y, width, height, callback, type, encoderOptions);\n
  • callback : The Function to invoke after the snapshot image is created.
    function(imageElement) {\n}\n
    • imageElement : HTMLImageElement.
  • type : The format of the image to create, usually 'image/png' or 'image/jpeg'. Default value is 'image/png'.
  • encoderOptions : The image quality, between 0 and 1. Used for image formats with lossy compression, such as 'image/jpeg'. Default value is 0.92.
  • x, y, width, height : Snapshot area.
"},{"location":"rendertexture/#get-color-of-a-pixel","title":"Get color of a pixel","text":"
texture.snapshotPixel(x, y, callback);\n
  • x, y : The x/y coordinate of the pixel to get.
  • callback : The Function to invoke after the snapshot image is created.
    function(color) {        }\n
    • color : Color object.
"},{"location":"rendertexture/#global-alpha","title":"Global alpha","text":"
rt.setGlobalAlpha(alpha);\n// rt.globalAlpha = alpha;\n
"},{"location":"rendertexture/#global-tint","title":"Global tint","text":"
rt.setGlobalTint(tint);\n// rt.globalTint = tint;\n
"},{"location":"rendertexture/#save-texture","title":"Save texture","text":"

Stores a copy of this Render Texture in the Texture Manager using the given key.

rt.saveTexture(key);\n

Calling saveTexture again will not save another copy of the same texture, it will just rename the key of the existing copy.

"},{"location":"rendertexture/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"rendertexture/#create-mask","title":"Create mask","text":"
var mask = rt.createBitmapMask();\n

See mask

"},{"location":"rendertexture/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"repeatimage/","title":"Repeat image","text":""},{"location":"repeatimage/#introduction","title":"Introduction","text":"

Stamp image repeatly on canvas, similar with TileSprite. It has better rendering result when the texture size is not power of 2, in WebGL and pixelArt mode.

  • Author: Rex
  • Game object
"},{"location":"repeatimage/#live-demos","title":"Live demos","text":"
  • PixelArt, compared with TileSprite
  • Scroll
"},{"location":"repeatimage/#usage","title":"Usage","text":"

Sample code

"},{"location":"repeatimage/#install-plugin","title":"Install plugin","text":""},{"location":"repeatimage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrepeatimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrepeatimageplugin.min.js', true);\n
  • Add repeat-image object
    var image = scene.add.rexRepeatImage(x, y, width, height, key, frame);\n
"},{"location":"repeatimage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RepeatImagePlugin from 'phaser3-rex-plugins/plugins/repeatimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRepeatImagePlugin',\nplugin: RepeatImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add repeat-image object
    var image = scene.add.rexRepeatImage(x, y, width, height, key, frame);\n
"},{"location":"repeatimage/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RepeatImage from 'phaser3-rex-plugins/plugins/repeatimage.js';\n
  • Add repeat-image object
    var image = new RepeatImage(scene, x, y, key, frame, config);\nscene.add.existing(image);\n
"},{"location":"repeatimage/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRepeatImagePlugin',\nplugin: RepeatImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"repeatimage/#create-instance","title":"Create instance","text":"
var image = scene.add.rexRepeatImage(x, y, width, height, key, frame);\n

Add image from JSON

var image = scene.make.rexRepeatImage({\nx: 0,\ny: 0,\nwidth: 512,\nheight: 512,\nkey: '',\n\nadd: true\n});\n
"},{"location":"repeatimage/#custom-class","title":"Custom class","text":"
  • Define class
    class MyImage extends RepeatImage {\nconstructor(scene, x, y, width, height, key, frame) {\nsuper(scene, x, y, width, height, key, frame);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyImage(scene, x, y, width, height, key, frame);\n
"},{"location":"repeatimage/#set-texture","title":"Set texture","text":"
image.setTexture(key, frame);\n
"},{"location":"repeatimage/#properties-of-tiles","title":"Properties of tiles","text":"
  • Position
    image.setTilePosition(x, y);\n
    or
    image.tilePositionX = x;\nimage.tilePositionY = y;\n
  • Scale
    image.setTileScale(scaleX, scaleY);\n
    or
    image.tileScaleX = scaleX;\nimage.tileScaleY = scaleY;\n
"},{"location":"repeatimage/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"repeatimage/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"repeatimage/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"repeatimage/#compare-with-tilesprite","title":"Compare with TileSprite","text":"

Using this RepeatImage when the texture size is not power of 2, in WebGL and pixelArt mode. Otherwise, using tileSprite

"},{"location":"restorabledata/","title":"Restorable data","text":""},{"location":"restorabledata/#introduction","title":"Introduction","text":"

Restorable data manager, extends from built-in data manager.

  • Author: Rex
  • Member of scene
"},{"location":"restorabledata/#live-demos","title":"Live demos","text":"
  • Restorable canvas
"},{"location":"restorabledata/#usage","title":"Usage","text":"

Sample code

"},{"location":"restorabledata/#install-plugin","title":"Install plugin","text":""},{"location":"restorabledata/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrestorabledataplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrestorabledataplugin.min.js', true);\n
  • Add restorable data object
    var data = scene.plugins.get('rexrestorabledataplugin').add(parent);\n
"},{"location":"restorabledata/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RestorableDataPlugin from 'phaser3-rex-plugins/plugins/restorabledata-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRestorableData',\nplugin: RestorableDataPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add restorable data object
    var data = scene.plugins.get('rexRestorableData').add(parent);\n
"},{"location":"restorabledata/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RestorableData from 'phaser3-rex-plugins/plugins/restorabledata.js';\n
  • Add restorable data object
    var data = new RestorableData(parent);\n
"},{"location":"restorabledata/#create-instance","title":"Create instance","text":"
var data = scene.plugins.get('rexRData').add(parent);\n// var data = scene.plugins.get('rexRData').add(parent, eventEmitter);\n
  • parent : The object (a scene, or a game object) that this DataManager belongs to.
  • eventEmitter : The DataManager's event emitter.
"},{"location":"restorabledata/#getsetremove-value","title":"Get/set/remove value","text":"

See built-in data manager.

"},{"location":"restorabledata/#commit","title":"Commit","text":"

Commit current data status into repository, and increase current version number.

data.commit();\n

or

data.commit(alias);\n
  • alias : A version alias string.
"},{"location":"restorabledata/#restore","title":"Restore","text":"
  • Restore data status to a specific version.
    data.restore(version);\n
    or
    data.version = version;\n
    • version : Version number or version alias string.
  • Rebuild data status from version 0 to a specific version.
    data.restore(version, true);\n
    • version : Version number or version alias string.
  • Reverse data status to last version.
    data.restore();\n
"},{"location":"restorabledata/#version","title":"Version","text":"
  • Get current version alias string
    var version = data.versionAlias;\n
  • Get all version alias strings
    var aliases = data.versionAliases;\n
  • Get current version number
    var version = data.version;\n
  • Get last version number
    var version = data.lastVersion;\n

Version starts from 0 which has no data. Each data.commit() will increase this version number.

"},{"location":"restorabledata/#saveload-status","title":"Save/load status","text":"
  • Get current status
    var o = data.toJSON();\n
  • Load status
    data.resetFromJSON(o);\n

or

  • Get current status via JSON string
    var s = JSON.stringify(data);\n
  • Load status via JSON string
    data.resetFromJSON(JSON.parse(s));\n
"},{"location":"reverse-string/","title":"Reverse","text":""},{"location":"reverse-string/#introduction","title":"Introduction","text":"

Reverses string, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"reverse-string/#usage","title":"Usage","text":"
var result = Phaser.Utils.String.ReverseString(str);\n
"},{"location":"rexvideo/","title":"Rexvideo","text":"

Warning

This plugin is abandoned, please using built-in video.

"},{"location":"rexvideo/#introduction","title":"Introduction","text":"

Play video on DOM, or on canvas.

  • Author: Rex
  • DOM Game object, or Canvas Game object
"},{"location":"rexvideo/#live-demos","title":"Live demos","text":""},{"location":"rexvideo/#usage","title":"Usage","text":"

Sample code

"},{"location":"rexvideo/#install-plugin","title":"Install plugin","text":""},{"location":"rexvideo/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexvideoplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexvideoplugin.min.js', true);\n
  • Add video object
    var video = scene.add.rexVideoCanvas(x, y, width, height, config);    // var video = scene.add.rexVideo(x, y, width, height, config);\n
"},{"location":"rexvideo/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import VideoPlugin from 'phaser3-rex-plugins/plugins/video-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexVideo',\nplugin: VideoPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add video object
    var video = scene.add.rexVideoCanvas(x, y, width, height, config);\n// var video = scene.add.rexVideo(x, y, width, height, config);\n
"},{"location":"rexvideo/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import VideoCanvas from 'phaser3-rex-plugins/plugins/videocanvas/VideoCanvas.js';\n// import VideoDOM from 'phaser3-rex-plugins/plugins/videodom/VideoDOM.js';\n
  • Add text object
    var video = new VideoCanvas(scene, x, y, width, height, config);\nscene.add.existing(video);\n// var video = new VideoDOM(scene, x, y, width, height, config);\n// scene.add.existing(video);\n
"},{"location":"rexvideo/#add-video-object","title":"Add video object","text":"
  • Video on DOM
    var video = scene.add.rexVideo(x, y, width, height, config);\n// var video = scene.add.rexVideo(x, y, config);\n// var video = scene.add.rexVideo(config);\n
  • Video on canvas
    var video = scene.add.rexVideoCanvas(x, y, width, height, config);\n// var video = scene.add.rexVideoCanvas(x, y, config);\n// var video = scene.add.rexVideoCanvas(config);\n

Default configuration

{\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\n\n// Element properties\nsrc: url,\n// src: {\n//     webm: webmFileURL,\n//     ogg: oggFileURL,\n//     mp4: mp4FileURL,\n//     h264: h264FileURL,\n// }\nid: undefined,\nautoPlay: true,\ncontrols: false,\nloop: false,\nmuted: false,\nplaysInline: true,\ncrossOrigin: 'anonymous',\nplaybackTimeChangeEventEnable: true,\n}\n
  • x, y : Position
  • width, height : Size of element
  • Element properties
    • src : Specifies the URL of the video file.
      • A string : url of the video file.
      • A plain object : { videoType: fileURL }
        1. Get webmFileURL if browser supports webm video format.
        2. Get oggFileURL if browser supports ogg video format.
        3. Get mp4FileURL if browser supports mp4 video format.
        4. Get h264FileURL if browser supports h264 video format.
    • id : id element property.
    • autoPlay : autoplay element property.
    • controls : controls element property.
    • loop : loop element property.
    • muted : muted element property.
    • playsInline : playsInline element property.
    • crossOrigin : crossOrigin element property.
  • playbackTimeChangeEventEnable : Set false to disable playbacktimechange event.
"},{"location":"rexvideo/#different-between-rexvideo-and-rexvideocanvas","title":"Different between rexVideo and rexVideoCanvas","text":"
  • rexVideo plays video on DOM.
    • DOM object always above game canvas.
    • Won't be affected by webgl shader.
    • Right clicks to pop up a menu.
  • rexVideoCanvas plays video on canvas.
    • Can be placed between game objects via depth setting.
    • Can be affected by webgl shader.
"},{"location":"rexvideo/#custom-class","title":"Custom class","text":"
  • Define class
    class MyVideo extends Video {  // or VideoCanvas\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config) {\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     if (super.preUpdate) {\n//         super.preUpdate(time, delta)\n//     }\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var video = new MyVideo(scene, x, y, width, height, config);\n
"},{"location":"rexvideo/#load","title":"Load","text":"
video.load(src);\n
  • src : Specifies the URL of the video file.
    • A string : url of the video file.
    • A plain object : { videoType: fileURL }
      1. Get webmFileURL if browser supports webm video format.
      2. Get oggFileURL if browser supports ogg video format.
      3. Get mp4FileURL if browser supports mp4 video format.
      4. Get h264FileURL if browser supports h264 video format.
"},{"location":"rexvideo/#play","title":"Play","text":"
video.play();\n
"},{"location":"rexvideo/#pause","title":"Pause","text":"
video.pause();\n
"},{"location":"rexvideo/#playback-time","title":"Playback time","text":"
  • Get
    var playbackTime = video.playbackTime; // time in seconds\n
    var t = video.t; // t: 0~1\n
  • Set
    video.setPlaybackTime(time); // time in seconds\n// video.playbackTime = time;\n
    video.setT(t); // t: 0~1\n// video.t = t;\n
"},{"location":"rexvideo/#duration","title":"Duration","text":"
var duration = video.duration;  // time in seconds\n
"},{"location":"rexvideo/#volume","title":"Volume","text":"
  • Get
    var volume = video.volume;  // volume: 0~1\n
  • Set
    video.setVolume(volume);  // volume: 0~1\n// video.volume = volume;\n
"},{"location":"rexvideo/#mute","title":"Mute","text":"
  • Get
    var muted = video.muted;  // muted: true/false\n
  • Set
    video.setMute(muted);  // muted: true/false\n// video.muted = muted;\n
"},{"location":"rexvideo/#loop","title":"Loop","text":"
  • Get
    var loop = video.loop;  // loop: true/false\n
  • Set
    video.setLoop(loop);  // loop: true/false\n// video.loop = loop;\n
"},{"location":"rexvideo/#resize","title":"Resize","text":"
video.resize(width, height);\n
"},{"location":"rexvideo/#status","title":"Status","text":"
  • Is playing
    var isPlaying = video.isPlaying;\n
  • Is paused
    var isPaused = video.isPaused;\n
  • Has end
    var hasEnded = video.hasEnded;\n
  • Ready state
    var readyState = video.readyState;\n
    • 0 = HAVE_NOTHING - no information whether or not the audio/video is ready
    • 1 = HAVE_METADATA - metadata for the audio/video is ready
    • 2 = HAVE_CURRENT_DATA - data for the current playback position is available, but not enough data to play next frame/millisecond
    • 3 = HAVE_FUTURE_DATA - data for the current and at least the next frame is available
    • 4 = HAVE_ENOUGH_DATA - enough data available to start playing
"},{"location":"rexvideo/#events","title":"Events","text":"
  • Load start
    video.on('loadstart', function(video){ }, scope);\n
  • Can play
    video.on('canplay', function(video){ }, scope);\n
  • Can play through
    video.on('canplaythrough', function(video){ }, scope);\n
  • Playing
    video.on('playing', function(video){ }, scope);\n
  • Pause
    video.on('pause', function(video){ }, scope);\n
  • Stalled
    video.on('stalled', function(video){ }, scope);\n
  • Ended
    video.on('ended', function(video){ }, scope);\n
  • Error
    video.on('error', function(video){ }, scope);\n
  • Playback time changed
    video.on('playbacktimechange', function(video){ }, scope);\n
    • Set playbackTimeChangeEventEnable to true to enable this event.
"},{"location":"rope/","title":"Rope","text":""},{"location":"rope/#introduction","title":"Introduction","text":"

Manipulate the vertices of images, built-in game object of phaser.

  • Author: Richard Davey

WebGL only

It only works in WebGL render mode.

"},{"location":"rope/#usage","title":"Usage","text":""},{"location":"rope/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"rope/#add-object","title":"Add object","text":"
var rope = scene.add.rope(x, y, texture, frame, points, horizontal);\n// var rope = scene.add.rope(x, y, texture, frame, points, horizontal, colors, alphas);\n
  • points :
    • A number : Segments to split the texture frame into.
    • An number array : An array containing the vertices data.
  • horizontal :
    • true : Vertices of this Rope be aligned horizontally.
    • false : Vertices of this Rope be aligned vertically.
  • colors : An optional array containing the color data for this Rope. One color value per pair of vertices.
  • alphas : An optional array containing the alpha data for this Rope. One alpha value per pair of vertices.

Add rope from JSON

var rope = scene.make.rope({\nx: 0,\ny: 0,\nkey: '',\nframe: null,\nhorizontal: true,\npoints: undefined,\ncolors: undefined,\nalphas: undefined,\n\n// angle: 0,\n// alpha: 1\n// flipX: true,\n// flipY: true,\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
"},{"location":"rope/#custom-rope-class","title":"Custom rope class","text":"
  • Define class
    class MyRope extends Phaser.GameObjects.Rope {\nconstructor(scene, x, y, texture, frame, points, horizontal, colors, alphas) {\nsuper(scene, x, y, texture, frame, points, horizontal, colors, alphas);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var rope = new MyRope(scene, x, y, texture, frame, points, horizontal);\n
"},{"location":"rope/#origin","title":"Origin","text":"

A Ropes origin is always 0.5 x 0.5 and cannot be changed.

"},{"location":"rope/#set-vertices","title":"Set vertices","text":"

Set vertices via

rope.setPoints(points);\n// rope.setPoints(points, colors, alphas);\n
  • points :
    • A number : Segments to split the texture frame into.
    • An number array : An array containing the vertices data.
  • colors : An optional array containing the color data for this Rope. One color value per pair of vertices.
  • alphas : An optional array containing the alpha data for this Rope. One alpha value per pair of vertices.

Also change horizontal mode :

  • Change vertical rope to horizontal rope, do nothing if rope is horizontal mode already
    rope.setHorizontal(points);\n// rope.setHorizontal(points, colors, alphas);\n
  • Change horizontal rope to vertical rope, do nothing if rope is vertical mode already
    rope.setVertical(points);\n// rope.setVertical(points, colors, alphas);\n

Or set rope.points directly :

  1. Change rope.points
    • Horizontal rope : rope.points[i].y = newY
    • Vertical rope : rope.points[i].x = newX
  2. Call rope.setDirty(), or rope.updateVertices()

Each point is relative to position of rope object, get points of world via

var worldX = rope.points[i].x + rope.x;\nvar worldY = rope.points[i].y + rope.y;\n
"},{"location":"rope/#play-animation","title":"Play animation","text":"
rope.play(key);\n// rope.play(key, ignoreIfPlaying, startFrame);\n
  • ignoreIfPlaying : If an animation is already playing then ignore this call. Default value is false.
  • startFrame : Optionally start the animation playing from this frame index. Default value is 0.
"},{"location":"rope/#alpha","title":"Alpha","text":"
  • Single alpha
    rope.setAlphas(alpha);\n
  • Top - bottom alpha
    rope.setAlphas(topAlpha, bottomAlpha);\n
  • Alpha array for each point
    rope.setAlphas(alphaArray);\n
    • alphaArray : Array of alpha value.
"},{"location":"rope/#color-tint","title":"Color tint","text":"
  • Single color tint
    rope.setColors(color);\n
  • Color tint array for each point
    rope.setAlphas(colorArray);\n
    • colorArray : Array of color tint value.
"},{"location":"rope/#tint-fill-mode","title":"Tint fill mode","text":"

Sets the tint fill mode.

rope.setTintFill(mode);\n
  • mode :
    • 0 : Additive tint, blends the vertices colors with the texture. Default behavior.
    • 1 : Fill tint with alpha.
    • 2 : Fill tint without alpha.
"},{"location":"rope/#flip","title":"Flip","text":"
rope.flipX = flip;\nrope.flipY = flip;\n

If this Game Object has a physics body, it will not change the body. This is a rendering toggle only.

"},{"location":"rope/#debug","title":"Debug","text":"

Draw debug mesh each render tick.

rope.setDebug(graphic);\n// rope.setDebug(graphic, callback);\n
  • graphic : Graphics game object
  • callback : Callback of rendering debug graphics (default callback)
    function(rope, meshLength, verts) {\n// var graphic = rope.debugGraphic;\n}\n
    • rope : Rope instance.
      • rope.debugGraphic : Graphics game object
    • meshLength : The number of mesh vertices in total.
    • verts : An array of the translated vertex coordinates.

Note

Clear Debug graphics (rope.debugGraphic.clear()) during scene's update stage (scene.update() { })

"},{"location":"rotate/","title":"Rotate","text":""},{"location":"rotate/#introduction","title":"Introduction","text":"

Rotate game object continually with a steady speed.

  • Author: Rex
  • Behavior of game object
"},{"location":"rotate/#live-demos","title":"Live demos","text":"
  • Change speed
"},{"location":"rotate/#usage","title":"Usage","text":"

Sample code

"},{"location":"rotate/#install-plugin","title":"Install plugin","text":""},{"location":"rotate/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrotateplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrotateplugin.min.js', true);\n
  • Add rotate behavior
    var rotate = scene.plugins.get('rexrotateplugin').add(gameObject, config);\n
"},{"location":"rotate/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RotatePlugin from 'phaser3-rex-plugins/plugins/rotate-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRotate',\nplugin: RotatePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add rotate behavior
    var rotate = scene.plugins.get('rexRotate').add(gameObject, config);\n
"},{"location":"rotate/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Rotate from 'phaser3-rex-plugins/plugins/rotate.js';\n
  • Add rotate behavior
    var rotate = new Rotate(gameObject, config);\n
"},{"location":"rotate/#create-instance","title":"Create instance","text":"
var rotate = scene.plugins.get('rexRotate').add(gameObject, {\n// speed: 180,\n// enable: true,\n// timeScale: 1,\n});\n
  • speed : Turn speed, degrees in second
"},{"location":"rotate/#enable","title":"Enable","text":"
  • Enable (default)
    rotate.setEnable();\n
    or
    rotate.enable = true;\n
  • Disable
    rotate.setEnable(false);\n
    or
    rotate.enable = false;\n
"},{"location":"rotate/#set-speed","title":"Set speed","text":"
rotate.setSpeed(speed);\n// rotate.speed = speed;\n
  • speed : Turn speed, degrees in second
"},{"location":"rotate/#status","title":"Status","text":"
  • Is rotating
    var enable = rotate.enable;\n// var isRunning = rotate.isRunning;\n
"},{"location":"rotateto/","title":"Rotate to","text":""},{"location":"rotateto/#introduction","title":"Introduction","text":"

Rotate game object towards target position with a steady speed.

  • Author: Rex
  • Behavior of game object
"},{"location":"rotateto/#usage","title":"Usage","text":"

Sample code

"},{"location":"rotateto/#install-plugin","title":"Install plugin","text":""},{"location":"rotateto/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexrotatetoplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexrotatetoplugin.min.js', true);\n
  • Add rotate-to behavior
    var rotateTo = scene.plugins.get('rexrotatetoplugin').add(gameObject, config);\n
"},{"location":"rotateto/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RotateToPlugin from 'phaser3-rex-plugins/plugins/rotateto-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRotateTo',\nplugin: RotateToPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add rotate-to behavior
    var rotateTo = scene.plugins.get('rexRotateTo').add(gameObject, config);\n
"},{"location":"rotateto/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RotateTo from 'phaser3-rex-plugins/plugins/rotateto.js';\n
  • Add rotate-to behavior
    var rotateTo = new RotateTo(gameObject, config);\n
"},{"location":"rotateto/#create-instance","title":"Create instance","text":"
var rotateTo = scene.plugins.get('rexRotateTo').add(gameObject, {\n// speed: 180,\n// enable: true,\n// timeScale: 1,\n});\n
  • speed : Turn speed, degrees in second
"},{"location":"rotateto/#start-moving","title":"Start moving","text":""},{"location":"rotateto/#rotate-game-object-towards-position","title":"Rotate game object towards position","text":"
  • Shortest angle
    rotateTo.rotateTowardsPosition(x, y);\n
    • x , y : Target position
  • Clockwise/counter-clockwise
    rotateTo.rotateTowardsPosition(x, y, dir);\n// rotateTo.rotateTowardsPosition(x, y, dir, speed);\n
    • dir :
      • 0 : Shortest angle
      • 1, or 'cw' : Clockwise
      • 2, or 'ccw' : Counter-clockwise
    • speed : Turn speed, degrees in second
"},{"location":"rotateto/#rotate-game-object-to-angle","title":"Rotate game object to angle","text":"
  • Shortest angle
    rotateTo.rotateTo(angle);\n
    • angle : Target angle in degrees
  • Clockwise/counter-clockwise
    rotateTo.rotateTo(angle, dir);\n// rotateTo.rotateTo(angle, dir, speed);\n
    • dir :
      • 0 : Shortest angle
      • 1, or cw : Clockwise
      • 2, or ccw : Counter-clockwise
    • speed : Turn speed, degrees in second
"},{"location":"rotateto/#enable","title":"Enable","text":"
  • Enable (default)
    rotateTo.setEnable();\n
    or
    rotateTo.enable = true;\n
  • Disable
    rotateTo.setEnable(false);\n
    or
    rotateTo.enable = false;\n
"},{"location":"rotateto/#pause-resume-stop-rotating","title":"Pause, Resume, stop rotating","text":"
rotateTo.pause();\nrotateTo.resume();\nrotateTo.stop();\n
"},{"location":"rotateto/#set-speed","title":"Set speed","text":"
rotateTo.setSpeed(speed);\n// rotateTo.speed = speed;\n
  • speed : Turn speed, degrees in second
"},{"location":"rotateto/#events","title":"Events","text":"
  • On rotating start
    rotateTo.on('start', function(gameObject, rotateTo){});\n
  • On reached target
    rotateTo.on('complete', function(gameObject, rotateTo){});\n
"},{"location":"rotateto/#status","title":"Status","text":"
  • Is moving
    var isRunning = rotateTo.isRunning;\n
"},{"location":"round-to/","title":"Round to","text":""},{"location":"round-to/#introduction","title":"Introduction","text":"

Round/ceil/floor to the given precision, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"round-to/#usage","title":"Usage","text":""},{"location":"round-to/#round-to","title":"Round to","text":"

var result = Phaser.Math.RoundTo(value);\n
or
var result = Phaser.Math.RoundTo(value, place, base);\n

  • value : The value to round.
  • place : The place to round to. Positive to round the units, negative to round the decimal. Default is 0.
  • base : The base to round in. Default is 10 for decimal.

Examples

RoundTo(123.456789, 0) = 123\nRoundTo(123.456789, -1) = 123.5\nRoundTo(123.456789, -2) = 123.46\nRoundTo(123.456789, -3) = 123.457\n
"},{"location":"round-to/#ceil-to","title":"Ceil to","text":"

var result = Phaser.Math.CeilTo(value);\n
or
var result = Phaser.Math.CeilTo(value, place, base);\n

  • value : The value to round.
  • place : The place to round to. Positive to round the units, negative to round the decimal. Default is 0.
  • base : The base to round in. Default is 10 for decimal.
"},{"location":"round-to/#floor-to","title":"Floor to","text":"

var result = Phaser.Math.floorTo(value);\n
or
var result = Phaser.Math.floorTo(value, place, base);\n

  • value : The value to round.
  • place : The place to round to. Positive to round the units, negative to round the decimal. Default is 0.
  • base : The base to round in. Default is 10 for decimal.
"},{"location":"runcommands/","title":"Run commands","text":""},{"location":"runcommands/#introduction","title":"Introduction","text":"

Run commands in array.

  • Author: Rex
  • Method only
"},{"location":"runcommands/#usage","title":"Usage","text":"

Sample code

"},{"location":"runcommands/#install-plugin","title":"Install plugin","text":""},{"location":"runcommands/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexruncommandsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexruncommandsplugin.min.js', true);\n
  • Run commands
    scene.plugins.get('rexruncommandsplugin').run(commands, scope);\n
"},{"location":"runcommands/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RunCommandsPlugin from 'phaser3-rex-plugins/plugins/runcommands-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRunCommands',\nplugin: RunCommandsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Run commands
    scene.plugins.get('rexRunCommands').run(commands, scope);\n
"},{"location":"runcommands/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RunCommands from 'phaser3-rex-plugins/plugins/runcommands.js';\n
  • Run commands
    RunCommands(commands, scope);\n
"},{"location":"runcommands/#run-commands","title":"Run commands","text":"
scene.plugins.get('rexRunCommands').run(commands, scope);\n
  • Format of command :
    [fnName, param0, param1, ...]\n
    or
    [callback, param0, param1, ...]\n
  • Commands in nested array :
    [\ncommand0,\ncommand1\n[\ncommand2,\ncommand3\n]\n]\n
  • Run command :
    scope[fnName].call(scope, param0, param1 ...)\n
    or
    callback.call(scope, param0, param1 ...)\n
"},{"location":"scaledowndestroy/","title":"Scale down destroy","text":""},{"location":"scaledowndestroy/#introduction","title":"Introduction","text":"

Scale down (i.e. ease scaleX, scaleY to 0) game object then destroy it.

  • Author: Rex
  • Method only
"},{"location":"scaledowndestroy/#usage","title":"Usage","text":"

Sample code

"},{"location":"scaledowndestroy/#install-plugin","title":"Install plugin","text":""},{"location":"scaledowndestroy/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexscaleplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexscaleplugin.min.js', true);\n
  • Scale down, then destroy object
    scene.plugins.get('rexscaleplugin').scaleDownDestroy(gameObject, duration);\n
"},{"location":"scaledowndestroy/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ScalePlugin from 'phaser3-rex-plugins/plugins/scale-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexScale',\nplugin: ScalePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Scale down, then destroy object
    scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration);\n
"},{"location":"scaledowndestroy/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ScaleDownDestroy from 'phaser3-rex-plugins/plugins/scale-down-destroy.js';\n
  • Scale down, then destroy object
    ScaleDownDestroy(gameObject, duration);\n
"},{"location":"scaledowndestroy/#scale-down","title":"Scale down","text":"
  • Scale down width and height
    var scale = scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration);\n// var scale = scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration, undefined, ease);\n
    • ease : Ease function, default is 'Linear'.
  • Scale down width only
    var scale = scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration, 'x');\n// var scale = scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration, 'x', ease);\n
  • Scale down height only
    var scale = scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration, 'y');\n// var scale = scene.plugins.get('rexScale').scaleDownDestroy(gameObject, duration, 'y', ease);\n
"},{"location":"scaledowndestroy/#events","title":"Events","text":"

See Events of tween task

  • Scale completes or is stopped.
    scale.on('complete', function(gameObject, scale){\n\n}, scope);\n
"},{"location":"scaledowndestroy/#inject-methods","title":"Inject methods","text":"
  • Inject methods into game object
    scene.plugins.get('rexScale').injectMethods(gameObject);\n
  • Inject methods into class of game object
    scene.plugins.get('rexScale').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexScale').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into class of game object
    scene.plugins.get('rexScale').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexScale').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into root class of game object
    scene.plugins.get('rexScale').injectMethodsToRootClass(e);\n// scene.plugins.get('rexScale').injectMethods(Phaser.GameObjects.GameObject.prototype);\n
"},{"location":"scaledowndestroy/#injected-methods","title":"Injected methods","text":"
  • Scale up from 0 to current scale of game object.
    • Pop-up width and height
      gameObject\n//.setScale(scaleX, scaleY)\n.popUp(duration);\n\n// gameObject.popUp(duration, undefined, ease);\n
      or
      gameObject\n//.setScale(scaleX, scaleY)\n.popUpPromise(duration)\n.then(function() {\n// ....\n})\n
      • ease : Ease function, default is 'Cubic'.
    • Pop-up width only
      gameObject\n//.setScaleX(scaleX)\n.popUp(duration, 'x');\n\n// gameObject.popUp(duration, 'x', ease);\n
      or
      gameObject\n//.setScaleX(scaleX)\n.popUpPromise(duration, 'x')\n.then(function() {\n// ....\n})\n
    • Pop-up height only
      gameObject\n//.setScaleY(scaleY)\n.popUp(duration, 'y');\n\n// gameObject.popUp(duration, 'y', ease);\n
      or
      gameObject\n//.setScaleY(scaleY)\n.popUpPromise(duration, 'y')\n.then(function() {\n// ....\n})\n
    • Pop-up via config
      gameObject\n//.setScale(scaleX, scaleY)\n.popUp({\nduration: undefined,\norientation: undefined,\nease: undefined,\n})\n
      or
      gameObject\n//.setScale(scaleX, scaleY)\n.popUpPromise(config)\n.then(function() {\n// ....\n})\n
      • orientation : undefined, x, or y
  • Scale-down destroy
    • Scale-down width and height
      gameObject.scaleDownDestroy(duration);\n// gameObject.scaleDownDestroy(duration, undefined, ease);\n
      or
      gameObject.scaleDownDestroyPromise(duration)\n.then(function() {\n// ....\n})\n
      • ease : Ease function, default is 'Linear'.
    • Scale-down width only
      gameObject.scaleDownDestroy(duration, 'x');\n// gameObject.scaleDownDestroy(duration, 'x', ease);\n
      or
      gameObject.scaleDownDestroyPromise(duration, 'x');\n.then(function() {\n// ....\n})\n
    • Scale-down height only
      gameObject.scaleDownDestroy(duration, 'y');\n// gameObject.scaleDownDestroy(duration, 'y', ease);\n
      or
      gameObject.scaleDownDestroyPromise(duration, 'y')\n.then(function() {\n// ....\n})\n
  • Scale-down without destroy
    • Scale-down width and height
      gameObject.scaleDown(duration);\n// gameObject.scaleDown(duration, undefined, ease);\n
      or
      gameObject.scaleDownPromise(duration, undefined, ease)\n.then(function() {\n// ....\n})\n
    • Scale-down width only
      gameObject.scaleDowny(duration, 'x');\n// gameObject.scaleDowny(duration, 'x', ease);\n
      or
      gameObject.scaleDownPromise(duration, 'x', ease)\n.then(function() {\n// ....\n})\n
    • Scale-down height only
      gameObject.scaleDown(duration, 'y');\n// gameObject.scaleDown(duration, 'y', ease);\n
      or
      gameObject.scaleDownPromise(duration, 'y', ease)\n.then(function() {\n// ....\n})\n
  • Scale up/down, then scale back (yoyo)
    • Scale up/down, then scale back width and height
      gameObject\n//.setScale(scaleX, scaleY)\n.scaleYoyo(duration, peakValue);\n\n// gameObject.scaleYoyo(duration, peakValue, repeat, undefined, ease);\n
      or
      gameObject\n//.setScale(scaleX, scaleY)\n.scaleYoyoPromise(duration, peakValue, repeat)\n.then(function() {\n// ....\n})\n
      • peakValue : Scale to this peak value, then scale back
      • repeat : Yoyo repeat, default value is 0.
      • ease : Ease function, default is 'Cubic'.
    • Scale up/down, then scale back width only
      gameObject\n//.setScaleX(scaleX)\n.scaleYoyo(duration, peakValue, 0, 'x');\n\n// gameObject.popUp(duration, peakValue, repeat, 'x', ease);\n
      or
      gameObject\n//.setScaleX(scaleX)\n.scaleYoyoPromise(duration, peakValue, repeat, 'x')\n.then(function() {\n// ....\n})\n
    • Scale up/down, then scale back height only
      gameObject\n//.setScaleY(scaleY)\n.scaleYoyo(duration, peakValue, 0, 'y');\n\n// gameObject.popUp(duration, peakValue, repeat, 'y', ease);\n
      or
      gameObject\n//.setScaleY(scaleY)\n.scaleYoyoPromise(duration, peakValue, repeat, 'y')\n.then(function() {\n// ....\n})\n
    • Scale up/down via config
      gameObject\n//.setScale(scaleX, scaleY)\n.scaleYoyo({\nduration: undefined,\npeakValue: 1.2,\nrepeat: 0,\norientation: undefined,\nease: undefined,\n})\n
      or
      gameObject\n//.setScale(scaleX, scaleY)\n.scaleYoyoPromise(config)\n.then(function() {\n// ....\n})\n
      • orientation : undefined, x, or y
  • Events
    • Pop-up complete
      gameObject.on('popup.complete', function(gameObject) { });\n
    • Scale-down, scale-down destroy complete
      gameObject.on('scaledown.complete', function(gameObject) { });\n
    • Scale up/down, then scale back (yoyo)
      gameObject.on('scaleyoyo.complete', function(gameObject) { });\n
"},{"location":"scalemanager/","title":"Scale manager","text":""},{"location":"scalemanager/#introduction","title":"Introduction","text":"

Scale game window, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"scalemanager/#usage","title":"Usage","text":""},{"location":"scalemanager/#setup","title":"Setup","text":"

Setup scale mode in game configuration.

var config = {\n// ...\nparent: divId,\n\n// Game size\nwidth: 1024,\nheight: 768,\n\nscale: {\n// Or set parent divId here\nparent: divId,\n\nmode: Phaser.Scale.FIT,\nautoCenter: Phaser.Scale.CENTER_BOTH,\n\n// Or put game size here\n// width: 1024,\n// height: 768,\n\n// Minimum size\nmin: {\nwidth: 800,\nheight: 600\n},\n// Or set minimum size like these\n// minWidth: 800,\n// minHeight: 600,\n\n// Maximum size\nmax: {\nwidth: 1600,\nheight: 1200\n},\n// Or set maximum size like these\n// maxWidth: 1600,\n// maxHeight: 1200,\n\nzoom: 1,  // Size of game canvas = game size * zoom\n},\nautoRound: false\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • scale.mode :
    • Phaser.Scale.NONE : No scaling happens at all.
    • Phaser.Scale.FIT : The width and height are automatically adjusted to fit inside the given target area, while keeping the aspect ratio. Depending on the aspect ratio there may be some space inside the area which is not covered.
    • Phaser.Scale.ENVELOP : The width and height are automatically adjusted to make the size cover the entire target area while keeping the aspect ratio. This may extend further out than the target size.
    • Phaser.Scale.WIDTH_CONTROLS_HEIGHT : The height is automatically adjusted based on the width.
    • Phaser.Scale.HEIGHT_CONTROLS_WIDTH : The width is automatically adjusted based on the height.
    • Phaser.Scale.EXPAND : The Canvas's visible area is resized to fit all available parent space like RESIZE mode, and scale canvas size to fit inside the visible area like FIT mode.
    • Phaser.Scale.RESIZE : The Canvas is resized to fit all available parent space, regardless of aspect ratio.
  • scale.autoCenter :
    • Phaser.Scale.NO_CENTER : The game canvas is not centered within the parent by Phaser.
    • Phaser.Scale.CENTER_BOTH : The game canvas is centered both horizontally and vertically within the parent.
    • Phaser.Scale.CENTER_HORIZONTALLY : The game canvas is centered horizontally within the parent.
    • Phaser.Scale.CENTER_VERTICALLY : The game canvas is centered both vertically within the parent.
"},{"location":"scalemanager/#resize-canvas-element","title":"Resize canvas element","text":"
scene.scale.resize(width, height);\n

Modify the size of the Phaser canvas element directly. You should only use this if you are using the NO_SCALE scale mode,

"},{"location":"scalemanager/#set-game-size","title":"Set game size","text":"
scene.scale.setGameSize(width, height);\n

It should only be used if you're looking to change the base size of your game and are using one of the Scale Manager scaling modes, i.e. FIT. If you're using NO_SCALE and wish to change the game and canvas size directly, then please use the resize method instead.

"},{"location":"scalemanager/#get-view-port","title":"Get view port","text":"
var viewport = scene.scale.getViewPort();\n// var viewport = scene.scale.getViewPort(camera, out);\n
  • viewport : The Rectangle of visible area.
  • camera : The camera this viewport is respond upon.
  • out : The Rectangle of visible area.
"},{"location":"scalemanager/#members","title":"Members","text":"
  • The un-modified game size, as requested in the game config (the raw width / height), as used for world bounds, cameras, etc
    var gameSize = scene.scale.gameSize;\n
    • gameSize.width, gameSize.height
  • The modified game size, which is the auto-rounded gameSize, used to set the canvas width and height (but not the CSS style)
    var baseSize = scene.scale.baseSize;\n
    • baseSize.width, baseSize.height
  • The size used for the canvas style, factoring in the scale mode, parent and other values.
    var displaySize = scene.scale.displaySize;\n
    • displaySize.width, displaySize.height
  • The size of parent dom element
    var parentSize = scene.scale.parentSize;\n
    • parentSize.width, parentSize.height
"},{"location":"scalemanager/#events","title":"Events","text":"
scene.scale.on('resize', function(gameSize, baseSize, displaySize, previousWidth, previousHeight) {});\n
  • gameSize : The un-modified game size, as requested in the game config (the raw width / height)
    • gameSize.width, gameSize.height
  • baseSize : The canvas width and height (actually size of canvas)
    • baseSize.width, baseSize.height
  • displaySize : Size used for the canvas style (display size of canvas)
    • displaySize.width, displaySize.height
"},{"location":"scalemanager/#update-bounds","title":"Update bounds","text":"

This method dose not have to be invoked, unless the canvas position, or visibility is changed via any other method (i.e. via an Angular route).

scene.scale.updateBounds();\n
"},{"location":"scalemanager/#full-screen","title":"Full screen","text":"

Under 'pointerup' touch event :

  • Start full screen
    scene.scale.startFullscreen();\n
  • Stop full screen
    scene.scale.stopFullscreen();\n
  • Toggle full screen
    scene.scale.toggleFullscreen();\n
  • Is full screen
    var isFullscreen = scene.scale.isFullscreen;\n

Games within an iframe will also be blocked from fullscreen unless the iframe has the allowfullscreen attribute.

Performing an action that navigates to another page, or opens another tab, will automatically cancel fullscreen mode, as will the user pressing the ESC key.

"},{"location":"scalemanager/#events_1","title":"Events","text":"
  • Enter full screen
    scene.scale.on('enterfullscreen', function() {}, scope);\n
  • Enter full screen failed
    scene.scale.on('fullscreenfailed', function(error) {}, scope);\n
  • Leave full screen
    scene.scale.on('leavefullscreen', function() {}, scope);\n
  • Full screen unsupport
    scene.scale.on('fullscreenunsupported', function() {}, scope);\n
  • Leave full screen
    scene.scale.on('leavefullscreen', function() {}, scope);\n
"},{"location":"scalemanager/#orientation","title":"Orientation","text":""},{"location":"scalemanager/#properties","title":"Properties","text":"
  • Is portrait orientation
    var isPortrait = scene.scale.isPortrait;\n
  • Is landscape orientation
    var isLandscape = scene.scale.isLandscape;\n
"},{"location":"scalemanager/#lock-orientation","title":"Lock orientation","text":"
scene.scale.lockOrientation(orientation);\n
  • orientation : 'landscape', or 'portrait';
"},{"location":"scalemanager/#events_2","title":"Events","text":"
scene.scale.on('orientationchange', function(orientation) {\nif (orientation === Phaser.Scale.PORTRAIT) {\n\n} else if (orientation === Phaser.Scale.LANDSCAPE) {\n\n}\n}, scope);\n
"},{"location":"scaleouter/","title":"Scale outer","text":""},{"location":"scaleouter/#introduction","title":"Introduction","text":"

Scroll and zoom camera to make default game window fit the display area, in RESIZE scale mode.

  • Author: Rex
  • Member of scene
"},{"location":"scaleouter/#live-demos","title":"Live demos","text":"
  • Viewport
  • Static camera
  • Tween camera
"},{"location":"scaleouter/#usage","title":"Usage","text":"

Sample code

"},{"location":"scaleouter/#install-plugin","title":"Install plugin","text":""},{"location":"scaleouter/#set-scale-mode-to-resize","title":"Set scale mode to RESIZE","text":"
var config = {\n// ...\nscale: {\nparent: divId,\nmode: Phaser.Scale.RESIZE,\nwidth: 1024,    // Default game window width\nheight: 768,    // Default game window height\n// ...\n}\n}\nvar game = new Phaser.Game(config);\n
"},{"location":"scaleouter/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexscaleouterplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexscaleouterplugin.min.js', 'rexScaleOuter', 'rexScaleOuter');\n
  • Scale outer is created as a member of scene (scene.rexScaleOuter) for each scene. It will control main camera (scene.cameras.main) by default.
"},{"location":"scaleouter/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install scene plugin in configuration of game
    import ScaleOuterPlugin from 'phaser3-rex-plugins/plugins/scaleouter-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexScaleOuter',\nplugin: ScaleOuterPlugin,\nmapping: 'rexScaleOuter'\n}]\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Scale outer is created as a member of scene (scene.rexScaleOuter) for each scene. It will control main camera (scene.cameras.main) by default.
"},{"location":"scaleouter/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ScaleOuter from 'phaser3-rex-plugins/plugins/scaleouter.js';\n
  • Add scaleouter object
    var scaleouter = new ScaleOuter(scene);\n
"},{"location":"scaleouter/#create-instance","title":"Create instance","text":"

ScaleOuter plugin is a scene plugin, which created as a member of scene (scene.rexScaleOuter) for each scene. It does not have to create other scale outer instance.

"},{"location":"scaleouter/#remove-instance","title":"Remove instance","text":"

Invoke scene.rexScaleOuter.destroy() under scene.create() { ... }.

"},{"location":"scaleouter/#add-camera","title":"Add camera","text":"
  • Add camera manually, under scene.create() { ... }
    scene.rexScaleOuter.add(camera);\n
  • Scale outer will control main camera (scene.cameras.main) if no camera added.
"},{"location":"scaleouter/#viewport","title":"Viewport","text":"
  • Inner viewport, a recangle object, for area of default size in game config after camera zoom/scroll.
    var innerViewport = scene.rexScaleOuter.innerViewport;\n
  • Outer viewport, a recangle object, for the visible area after camera zoom/scroll.
    var outerViewport = scene.rexScaleOuter.outerViewport;\n
"},{"location":"scaleouter/#manual-scale","title":"Manual scale","text":"
  1. Stop resize callback
    scene.rexScaleOuter.stop()\n
  2. Manual scale
    scene.rexScaleOuter.scale();\n
"},{"location":"scene/","title":"Scene","text":""},{"location":"scene/#define-a-scene","title":"Define a scene","text":""},{"location":"scene/#configuration-of-scene","title":"Configuration of scene","text":"
var config = {\nkey: \"\",\n// active: false,\n// visible: true,\n// pack: false,\n// cameras: null,\n// map: {},\n// physics: {},\n// loader: {},\n// plugins: false,\n// input: {}\n};\n
  • key : The unique key of this Scene. Must be unique within the entire Game instance.
  • active : Does the Scene start as active or not? An active Scene updates each step.
  • visible : Does the Scene start as visible or not? A visible Scene renders each step.
  • pack : An optional Loader Packfile to be loaded before the Scene begins.
  • cameras : An optional Camera configuration object.
    {\nname: '',\nx: 0,\ny: 0,\nwidth: scene.sys.scale.width,\nheight: scene.sys.scale.height,\nzoom: 1,\nrotation: 0,\nscrollX: 0,\nscrollY: 0,\nroundPixels: false,\nvisible: true,\nbackgroundColor: false,\nbounds: null, // {x, y, width, height}\n}\n
  • map : Overwrites the default injection map for a scene.
  • physics : The physics configuration object for the Scene.
    {\ndefault: 'arcade', // 'arcade', or 'matter'\narcade: {...},\nmatter: {...}\n}\n
  • arcade : Arcade Physics configuration.
  • matter : Matter Physics configuration.
  • loader : The loader configuration object for the Scene.
    {\nbaseURL: '',\npath: '',\nenableParallel: true,\nmaxParallelDownloads: 4,\ncrossOrigin: undefined,\nresponseType: '',\nasync: true,\nuser: '',\npassword: '',\ntimeout: 0\n}\n
  • plugins : The plugin configuration object for the Scene.
    {\nglobal: [\n//{key, plugin, start}\n],\nscene: [\n// ...\n]\n}\n
  • input : The input configuration object for the Scene.
    {\nkeyboard: {\ntarget: window\n},\nmouse: {\ntarget: null,\ncapture: true\n},\nactivePointers: 1,\ntouch: {\ntarget: null,\ncapture: true\n},\nsmoothFactor: 0,\ngamepad: false,\nwindowEvents: true,\n}\n
"},{"location":"scene/#es6-class","title":"ES6 class","text":"
class MyScene extends Phaser.Scene {\nconstructor(config) {\nsuper(config);\n}\n\ninit(data) {}\npreload() {}\ncreate(data) {}\nupdate(time, delta) {}\n}\n
  • data : Parameters passed from adding new scene, or starting scene
"},{"location":"scene/#class","title":"Class","text":"
var MyScene = new Phaser.Class({\nExtends: Phaser.Scene,\n\ninitialize: function MyScene(config) {\nPhaser.Scene.call(this, config);\n},\n\ninit: function (data) {},\npreload: function () {},\ncreate: function (data) {},\nupdate: function (time, delta) {},\n});\n
  • data : Parameters passed from adding new scene, or starting scene
var MyGame = {};\n\nMyGame.Boot = function () {};\n\nMyGame.Boot.prototype.constructor = MyGame.Boot;\n\nMyGame.Boot.prototype = {\ninit: function (data) {},\npreload: function () {},\ncreate: function (data) {},\nupdate: function (time, delta) {},\n};\n
  • data : Parameters passed from adding new scene, or starting scene
"},{"location":"scene/#override","title":"Override","text":"
var demo = new Phaser.Scene(\"Demo\");\n\ndemo.init = function (data) {};\ndemo.preload = function () {};\ndemo.create = function (data) {};\ndemo.update = function (time, delta) {};\n
  • data : Parameters passed from adding new scene, or starting scene
"},{"location":"scene/#flow-chart","title":"Flow chart","text":"
graph TB\n\nsubgraph Stop\nSceneEventDestroy>\"scene.events: destroy\"]\nShutdown[\"Shutdown<br>Free game objects\"]\nend\n\nsubgraph Update\nSceneUpdate[\"Run: Every tick<br>scene.update()\"]\nSceneEventPauseSleep>\"scene.events: pause<br>scene.events: sleep\"]\nPause[\"Pause: render but no update<br>Sleep: no update, no render\"]\nSceneEventResumeWake>\"scene.events: resume<br>scene.events: wake\"]\nend\n\nsubgraph Create\nSceneEventStart>\"scene.events: start\"]\nSceneEventReady>\"scene.events: ready\"]\nSceneInit[\"scene.init()\"]\nScenePreLoad[\"Load assets<br>scene.preload()\"]\nSceneCreate[\"Create game objects<br>scene.create()\"]\nend\n\nStart((Start)) --> SceneEventStart\nSceneEventStart --> SceneEventReady\nSceneEventReady --> SceneInit\nSceneInit --> ScenePreLoad\nScenePreLoad --> SceneCreate\nSceneCreate --> SceneUpdate\nSceneUpdate --> SceneUpdate\nSceneUpdate --> |\"scene.scene.pause()<br>scene.scene.sleep()\"|SceneEventPauseSleep\nSceneEventPauseSleep --> Pause\nPause --> |\"scene.scene.resume()<br>scene.scene.wake()\"|SceneEventResumeWake\nSceneEventResumeWake --> SceneUpdate\n\nSceneUpdate --> |\"scene.scene.stop()<br>scene.scene.restart()\"|Stop\nPause --> |\"scene.scene.stop()<br>scene.scene.restart()\"|SceneEventDestroy\nSceneEventDestroy --> Shutdown\n\nShutdown --> |\"scene.scene.start()<br>scene.scene.launch()<br>scene.scene.restart()\"|SceneEventStart
  • Run : Update and render
  • Pause : Render but no update
  • Sleep : No update, no render
  • Stop : Shutdown

See also

  • Pause/resume
  • Stop
  • Main loop
"},{"location":"scene/#start","title":"Start","text":"
  1. Invoke scene.preload()
  2. Invoke scene.create()

scene.scene.restart() is equal to

scene.scene.stop();\nscene.scene.start();\n
"},{"location":"scene/#stop","title":"Stop","text":"
  • All game objects will be destroyed.
  • Registered events on game objects will also be clear, too.
  • Touch, keyboard and GamePad events will be clear.
  • Cameras will be destroyed.
  • Loader will be stopped.
  • Assets will be stored in global cache.
  • Events registered on scene plugin (scene.events.on) won't be clear.
"},{"location":"scene/#members","title":"Members","text":"
  • plugins
  • load : Loader
  • events : Local events
  • input : Touch, keyboard
  • tweens : Tween tasks
  • time : Timer
  • cameras : Camera
  • scene : scenePlugin
  • anims
  • physics : ArcadePhysics
  • matter :\u3000 MatterPhysics
  • registry : Global data manager across all scenes
    scene.registry.set(key, value);\nvar value = scene.registry.get(key);\n
  • data : Local data manager
    scene.data.set(key, value);\nvar value = scene.data.get(key);\n
  • sys
  • game
  • render
  • cache
  • sound
  • textures
  • add
  • make
  • children : DisplayList
    scene.children.bringToTop(child);\nscene.children.sendToBack(child);\nscene.children.moveUp(child);\nscene.children.moveDown(child);\nscene.children.moveUp(child);\nscene.children.moveTo(child, index);\nscene.children.moveAbove(child1, child2); // Move child1 above child2\nscene.children.moveBelow(child1, child2); // Move child1 below child2\nscene.children.swap(child1, child2);\n
  • lights

Preserve word in a scene.

"},{"location":"scene/#events","title":"Events","text":"
  • Start (Before scene.init())
    scene.events.on(\"start\", function () {});\n
  • Ready (After start)
    scene.events.on(\"ready\", function () {});\n
  • Every tick
    • Preupdate
      scene.events.on(\"preupdate\", function (time, delta) {});\n
    • Update
      scene.events.on(\"update\", function (time, delta) {});\n
    • Postupdate
      scene.events.on(\"postupdate\", function (time, delta) {});\n
    • Render
      scene.events.on(\"render\", function () {});\n
  • State changed
    • Pause (from scene.scene.pause())
      scene.events.on(\"pause\", function () {});\n
    • Resume (from scene.scene.resume())
      scene.events.on(\"resume\", function () {});\n
    • Sleep (from scene.scene.sleep())
      scene.events.on(\"sleep\", function () {});\n
    • Wake (from scene.scene.wake())
      scene.events.on(\"wake\", function () {});\n
    • Stop/shutdown (from scene.scene.stop())
      scene.events.on(\"shutdown\", function () {});\n
      • Free-up any resources that may be in use by this scene
  • Destroy (from scene.scene.remove())
    scene.events.on(\"destroy\", function () {});\n
  • Boot
    scene.events.on(\"boot\", function () {});\n
  • Game object added to scene
    • Add
      scene.events.on(\"addedtoscene\", function (gameObject, scene) {});\n
    • Remove
      scene.events.on(\"removedfromscene\", function (gameObject, scene) {});\n
"},{"location":"scenemanager/","title":"Scene manager","text":"

Scene manager plugin:

  • In each scene instance: scene.scene
"},{"location":"scenemanager/#add-new-scene","title":"Add new scene","text":"
var newScene = scene.scene.add(key, sceneConfig, autoStart, data);\n// var newScene = game.scene.add(key, sceneConfig, autoStart, data);\n
  • key : A unique key used to reference the Scene.
  • sceneConfig :
    • A scene class
    • A plain object
      {\ninit(data) {},\npreload() {},\ncreate(data) {},\nupdate(time, delta) {},\n\nextend: {\ndata: {},\n// ...\n},\n}\n
  • autoStart : Set true to start scene immediately after added.
  • data : Optional data object. This will be set as scene.settings.data and passed to scene.init.
"},{"location":"scenemanager/#load-scene-from-external-files","title":"Load scene from external files","text":"
  1. load script
    scene.load.script(key, url);\n
  2. add new scene
    scene.scene.add(key, sceneConfig, autoStart);\n// game.scene.add(key, sceneConfig, autoStart);\n
"},{"location":"scenemanager/#destroy-scene","title":"Destroy scene","text":"
scene.scene.remove(key);\n
  • Fires scene.events destroy
"},{"location":"scenemanager/#start-scene","title":"Start scene","text":"
  • Launch the given Scene and run it in parallel with this one
    scene.scene.launch(key, data);\n
  • Shutdown this Scene and run the given one
    scene.scene.start(key, data);\n
  • Restarts this Scene
    scene.scene.restart(data);\n
"},{"location":"scenemanager/#pauseresume-scene","title":"Pause/Resume scene","text":"
  • Pause : stops the update step but still renders
    scene.scene.pause(key);\n// scene.scene.pause();  // pause myself\n
    • Fires scene.events pause
  • Resume : starts the update loop again
    scene.scene.resume(key);\n// scene.scene.resume();  // resume myself\n
    • Fires scene.events resume
  • Sleep : no update, no render but doesn't shutdown
    scene.scene.sleep(key);\n// scene.scene.sleep();  // sleep myself\n
    • Fires scene.events sleep
  • Wake-up: starts update and render
    scene.scene.wake(key);\n// scene.scene.wake();  // wake-up myself\n
    • Fires scene.events wake
  • Makes this Scene sleep then starts the Scene given
    scene.scene.switch(key, data);\n
"},{"location":"scenemanager/#run-scene","title":"Run scene","text":"

Runs the given Scene, but does not change the state of this Scene.

If the given Scene is paused, it will resume it. If sleeping, it will wake it. If not running at all, it will be started.

scene.scene.run(key, data);\n
"},{"location":"scenemanager/#stop-scene","title":"Stop scene","text":"

Shutdown the Scene, clearing display list, timers, etc.

scene.scene.stop(key);\n// scene.scene.stop();  // stop myself\n
"},{"location":"scenemanager/#set-visible","title":"Set visible","text":"
scene.scene.setVisible(value, key);  // value: true/false\n// scene.scene.setVisible(value);    // set visible to myself\n
"},{"location":"scenemanager/#read-status","title":"Read status","text":"
var isSleep = scene.scene.isSleeping(key);\n// var isSleep = scene.scene.isSleeping();\n
var isPaused = scene.scene.isPaused(key);\n// var isPaused = scene.scene.isPaused();\n
var isActive = scene.scene.isActive(key);\n// var isActive = scene.scene.isActive();\n
var isVisible = scene.scene.isVisible(key);\n// var isVisible = scene.scene.isVisible();\n
Update/isActive Render/isVisible Run Pause Sleep

Pause/Sleep/Stop

  • Pause: Pause update stage.
  • Sleep: Pause update stage, and set scene invisible.
  • Stop: Shoutdown, clearing display list, timers, etc.
var status = scene.scene.getStatus(key);\n// var status = scene.scene.getStatus();\n
  • status :
    • Phaser.Scenes.PENDING, or 0
    • Phaser.Scenes.INIT, or 1
    • Phaser.Scenes.START, or 2
    • Phaser.Scenes.LOADING, or 3
    • Phaser.Scenes.CREATING, or 4
    • Phaser.Scenes.RUNNING, or 5
    • Phaser.Scenes.PAUSED, or 6
    • Phaser.Scenes.SLEEPING, or 7
    • Phaser.Scenes.SHUTDOWN, or 8
    • Phaser.Scenes.DESTROYED, or 9
"},{"location":"scenemanager/#get-scene","title":"Get scene","text":"
var scene = scene.scene.get(key);\n
"},{"location":"scenemanager/#order-of-scenes","title":"Order of scenes","text":"

Swaps the position of two scenes in the Scenes list.

scene.scene.swapPosition(keyA, keyB);\n// scene.scene.stop(keyA);\n
scene.scene.moveAbove(keyA, keyB);\n// scene.scene.moveAbove(keyA);\n

Scene B is directly above Scene A.

scene.scene.moveBelow(keyA, keyB);\n// scene.scene.moveBelow(keyA);\n

Scene B is directly below Scene A.

scene.scene.moveUp(keyA);\n// scene.scene.moveBelow();\n
scene.scene.moveDown(keyA);\n// scene.scene.moveDown();\n
scene.scene.bringToTop(keyA);\n// scene.scene.bringToTop();\n
scene.scene.sendToBack(keyA);\n// scene.scene.sendToBack();\n
"},{"location":"scenemanager/#transition","title":"Transition","text":"
scene.scene.transition({\ntarget: key,\n// data: null,\n// moveAbove: false,\n// moveBelow: false,\n\nduration: 1000,\n\n// remove: false,\n// sleep: false,\n// allowInput: false,\n\n// onStart: null,\n// onStartScope: scene,\n\n// onUpdate: null,\n// onUpdateScope: scene,\n})\n
  • target : The Scene key to transition to.
  • data : An object containing any data you wish to be passed to the target scenes init / create methods.
  • moveAbove. moveBelow : Move the target Scene to be above/below this current scene before the transition starts.
  • duration : Transition duration, in ms.
  • remove : Set true to remove this scene.
  • sleep : Set true to sleep this scene, set false to stop this scene.
  • allowInput : Set true to enable input system of current scene and target scene.
  • onStart, onStartScope : Invoked when transition start
    function(fromScene, toScene, duration) {\n\n}\n
    • fromScene : Current scene instance
    • toScene : Target scene instance
    • duration : Transition duration, in ms.
  • onUpdate ,onUpdateScope : Transition callback in each tick.
    function(progress) {\n\n}\n
    • progress : 0 ~ 1
"},{"location":"scenemanager/#execution-flow","title":"Execution flow","text":"
  1. Invoke scene.scene.transition method.
    • Current scene :
      • Fire 'transitionout' event.
        fromScene.events.on('transitionout', function(targetScene, duration){ });\n
      • Run transition's onUpdate callback every tick.
      • Current scene's update method is still running every tick.
    • Target scene :
      • Start target scene immediately.
      • Fire target scene's 'transitionstart' event. (Register this event in create stage)
        targetScene.events.on('transitionstart', function(fromScene, duration){ });\n
  2. When transition completed.
    • Current scene :
      • Remove or sleep current scene after transition completed.
    • Target scene :
      • Fire target scene's transitioncomplete event.
        targetScene.events.on('transitioncomplete', function(fromScene){ });\n
"},{"location":"scenemanager/#events","title":"Events","text":"
  • boot
    scene.events.on('transitioninit', function(fromScene, duration)){ });\n
  • start
    scene.events.on('transitionstart', function(fromScene, duration){ });\n
  • transition-out
    scene.events.on('transitionout', function(targetScene){ });\n
  • complete
    scene.events.on('transitioncomplete', function(fromScene){ });\n
  • wake : wake-up target scene if it was previously asleep
    scene.events.on('transitionwake', function(fromScene, duration){ });\n
"},{"location":"scenemanager/#system-scene","title":"System scene","text":"

A default empty Scene that lives outside of the Scene list, but can be used by plugins and managers that need access to a live Scene, without being tied to one.

var scene = scene.scene.get('__SYSTEM');\n

or

var scene = scene.scene.systemScene;\n
"},{"location":"scripttagloader/","title":"Script tag loader","text":""},{"location":"scripttagloader/#introduction","title":"Introduction","text":"

Load script tag in preload stage.

  • Author: Rex
  • Custom File of loader
"},{"location":"scripttagloader/#usage","title":"Usage","text":"

Sample code

"},{"location":"scripttagloader/#install-plugin","title":"Install plugin","text":""},{"location":"scripttagloader/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    var sceneConfig = {\n// ....\npack: {\nfiles: [{\ntype: 'plugin',\nkey: 'rexscripttagloaderplugin',\nurl: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexscripttagloaderplugin.min.js',\nstart: true\n}]\n}\n};\nclass MyScene extends Phaser.Scene {\nconstructor() {\nsuper(sceneConfig)\n}\n// ....\n\npreload() {\n// rexscripttagloaderplugin will be installed before preload(), but not added to loader yet\n// Call addToScene(scene) to add this await loader to loader of this scene\nthis.plugins.get('rexscripttagloaderplugin').addToScene(this);\n\nthis.load.rexScriptTag(url);\n}\n}\n
"},{"location":"scripttagloader/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ScriptTagLoaderPlugin from 'phaser3-rex-plugins/plugins/scripttagloader-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexScriptTagLoader',\nplugin: ScriptTagLoaderPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • In preload stage
    scene.load.rexScriptTag(url);\n
"},{"location":"scripttagloader/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ScriptTagLoader from 'phaser3-rex-plugins/plugins/scripttagloader.js';\n
  • Start loading task
    ScriptTagLoader.call(scene.load, url);\n// ScriptTagLoader.call(scene.load, url, availableTest);\n
"},{"location":"scripttagloader/#load-script-tag","title":"Load script tag","text":"

In preload stage:

this.load.rexScriptTag(url);\n// this.load.rexScriptTag(url, availableTest);\n

or

this.load.rexScriptTag({\nurl: url,\navailableTest: undefined\n});\n
  • availableTest : Callback invoked after loading script tag, optional.
    function() {        return true;\n}\n
    • Wait until availableTest return true.
"},{"location":"scripttagloader/#compare-with-script-loader","title":"Compare with script loader","text":"
  • Built-in script loader uses AJAX to load text as script, which might have CORS issue.
  • Script tag loader uses <script> tag to load script.
"},{"location":"scroller/","title":"Scroller","text":""},{"location":"scroller/#introduction","title":"Introduction","text":"

Drag content. Slow down when dragging released, pull back when out of bounds.

  • Author: Rex
  • Behavior of game object
"},{"location":"scroller/#live-demos","title":"Live demos","text":"
  • Scroller
"},{"location":"scroller/#usage","title":"Usage","text":"

Sample code

"},{"location":"scroller/#install-plugin","title":"Install plugin","text":""},{"location":"scroller/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexscrollerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexscrollerplugin.min.js', true);\n
  • Add scroller behavior
    var scroller = scene.plugins.get('rexscrollerplugin').add(gameObject, config);\n
"},{"location":"scroller/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ScrollerPlugin from 'phaser3-rex-plugins/plugins/scroller-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexScroller',\nplugin: ScrollerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add scroller behavior
    var scroller = scene.plugins.get('rexScroller').add(gameObject, config);\n
"},{"location":"scroller/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Scroller from 'phaser3-rex-plugins/plugins/scroller.js';\n
  • Add scroller behavior
    var scroller = new Scroller(gameObject, config);\n
"},{"location":"scroller/#create-instance","title":"Create instance","text":"
var scroller = scene.plugins.get('rexScroller').add(gameObject, {\nbounds: [\nbottomBound,\ntopBound\n],\nvalue: topBound,    // threshold: 10,\n// slidingDeceleration: 5000,\n// backDeceleration: 2000,\n\n// dragReverse: false,\n// dragRate: 1,\n\n// enable: true,\n// orientation: 'vertical',\n// pointerOutRelease: true,\n// rectBoundsInteractive: false,\n\n// valuechangeCallback: null,\n// valuechangeCallbackScope: null,\n\n// overmaxCallback: null,\n// overmaxCallbackScope: null,\n\n// overminCallback: null,\n// overminCallbackScope: null,\n});\n
  • bounds : An array of 2 values [bound0, bound1]
  • value : Initial value between bound0 and bound1
    • Map this value to position of content under event 'valuechange'
  • threshold : Minimal movement to scroll. Set 0 to scroll immediately.
  • slidingDeceleration : Deceleration of slow down when dragging released.
    • Set false to disable it.
  • backDeceleration : Deceleration of pull back when out of bounds.
    • Set false to disable it.
  • dragReverse :
    • false : Dragging up will decrease value, dragging down will increase value. Default behavior.
      • Use this mode when scrolling by position of game object.
    • true : Dragging up will increase value, dragging down will decrease value.
      • Use this mode when scrolling by camera.
  • dragRate : Rate of dragging distance/dragging speed. Default value is 1.
  • enable : Set true to get dragging events.
  • orientation :
    • 'vertical','v', 'y', or 0 : dragging on vertical/y axis.
    • 'horizontal','h', 'x', or 1 : dragging on horizontal/x axis.
  • pointerOutRelease : Set to true to release input control when pointer out of gameObject. Default value is true.
  • rectBoundsInteractive :
    • false : Detect scrolling by game object's touch input. Default behavior.
    • true : Detect scrolling by rectangle bounds of game object.
  • valuechangeCallback , valuechangeCallbackScope : Bind this callback to valuechange event
  • overminCallback , overmaxCallbackScope : Bind this callback to overmax event
  • overminCallback , overminCallbackScope : Bind this callback to overmin event
"},{"location":"scroller/#set-bounds","title":"Set bounds","text":"
this.setBounds(bounds);  // bounds: [bound0, bound1]\n// this.setBounds(bound0, bound1);\n
"},{"location":"scroller/#set-deceleration","title":"Set deceleration","text":"
  • Deceleration of slow down when dragging released
    scroller.setSlidingDeceleration(dec);\n
    • Disable
      scroller.setSlidingDeceleration(false);\n
  • Deceleration of pull back when out of bounds
    scroller.setBackDeceleration(dec);\n
    • Disable
      scroller.setBackDeceleration(false);\n
"},{"location":"scroller/#get-value","title":"Get value","text":"
var value = scroller.value;\n
"},{"location":"scroller/#set-value","title":"Set value","text":"
  • Set value
    scroller.value = newValue;\n// scroller.setValue(newValue);\n
  • Set value, clamp between minValue and maxValue
    scroller.setValue(newValue, true);\n
  • Add value
    scroller.value += inc;\n// scroller.addValue(inc);\n
  • Add value, clamp between minValue and maxValue
    scroller.addValue(inc, true);\n

Fires valuechange event if new value is not equal to current value.

"},{"location":"scroller/#events","title":"Events","text":"
  • Value changed
    scroller.on('valuechange', function(newValue, prevValue){ /* ... */ });\n
    • Set position of content under this event
  • Value out of max/min bound
    scroller.on('overmax', function(newValue, prevValue){ /* ... */ });\n
    scroller.on('overmin', function(newValue, prevValue){ /* ... */ });\n
  • On drag start
    scroller.on('dragstart', function() { /* ... */ });\n
  • On drag end
    scroller.on('dragend', function() { /* ... */ });\n
"},{"location":"scroller/#drag","title":"Drag","text":""},{"location":"scroller/#drag-enable","title":"Drag enable","text":"
  • Get
    var enable = scroller.enable;\n
  • Set
    scroller.setEnable();\n// scroller.setEnable(enable);  // enable: true, or false\n
    or
    scroller.enable = enable; // enable: true, or false\n
  • Toggle
    scroller.toggleEnable();\n
"},{"location":"scroller/#is-dragging","title":"Is dragging","text":"
var isDragging = scroller.isDragging;\n
"},{"location":"scroller/#state-machine","title":"State machine","text":"
graph TB\n\nIDLE[\"Idle\"] --> |Drag| DRAG[\"Dragging<br>event 'valuechange'\"]\nDRAG --> |Release| OnRelease{\"Under bounds?\"}\n\nOnRelease --> |Yes| SLIDE[\"Sliding<br>Sliding-deceleration\"]\nSLIDE --> |Stop| IDLE\nSLIDE --> |Drag| DRAG\n\nOnRelease --> |No| BACK[\"Pull back to bounds<br>Back-deceleration\"]\nBACK --> |Stop| IDLE\nBACK --> |Drag| DRAG
  • Get state
    var state = scroller.state;\n
    • 'IDLE' : No dragging, no sliding
    • 'DRAG' : Dragging
    • 'SLIDE' : Sliding when dragging released
    • 'BACK' : Sliding back to bound when out of bound
"},{"location":"sequence/","title":"Sequence","text":""},{"location":"sequence/#introduction","title":"Introduction","text":"

Run sequence commands in array.

  • Author: Rex
  • Object
"},{"location":"sequence/#live-demos","title":"Live demos","text":"
  • Sequence
"},{"location":"sequence/#usage","title":"Usage","text":"

Sample code

"},{"location":"sequence/#install-plugin","title":"Install plugin","text":""},{"location":"sequence/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexsequenceplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexsequenceplugin.min.js', true);\n
  • Create sequence instance
    var seq = this.plugins.get('rexsequenceplugin').add(config);\n
"},{"location":"sequence/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SequencePlugin from 'phaser3-rex-plugins/plugins/sequence-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexSequence',\nplugin: SequencePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create sequence instance
    var seq = this.plugins.get('rexSequence').add(config);\n
"},{"location":"sequence/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Sequence from 'phaser3-rex-plugins/plugins/sequence.js';\n
  • Create sequence instance
    var seq = new Sequence(config);\n
"},{"location":"sequence/#create-sequence-instance","title":"Create sequence instance","text":"
var seq = this.plugins.get('rexSequence').add({\n// yoyo: false,\n// repeat: 0, \n// loop: false\n});\n
  • yoyo : Reverse sequence when it reaches the end
  • repeat : Repeat count
  • loop : Repeat forever
"},{"location":"sequence/#load-commands","title":"Load commands","text":"
seq.load(commands, actionScope);\n
  • Format of command :
    [fnName, param0, param1, ...]\n
  • Commands in nested array :
    [\ncommand0,\ncommand1\n[\ncommand2,\ncommand3\n]\n]\n
  • ActionScope

Format of command is the same as run-command.

"},{"location":"sequence/#run-commands","title":"Run commands","text":"
seq.start();\n
  • Run command :
    var eventEmitter = actionScope[fnName].call(actionScope, param0, param1 ...);\n
    • Return an event emitter to pause the sequence, otherwise run next command
    • Sequence will continue when that event emitter fires complete event
"},{"location":"sequence/#stop","title":"Stop","text":"
seq.stop();\n
"},{"location":"sequence/#events","title":"Events","text":"
  • On sequence completed :
    seq.on('complete', function(actionScope, seq){ });\n
"},{"location":"sequence/#action-of-commands","title":"Action of commands","text":"

Action of commands, extended from Phaser.Events.EventEmitter.

class ActionKlass extends Phaser.Events.EventEmitter {\nconstructor(scene) {\nsuper();\n\nthis.scene = scene;\nthis.myConsole = scene.add.text(100, 100, '');\n\nthis['wait-click'] = this.waitClick;\nthis['wait-time'] = this.waitTime;\n}\n\n// callbacks\nprint(msg) {\nthis.myConsole.setText(msg);\n// return undefined to run next command\n}\n\nwaitClick() {\nthis.scene.input.once('pointerup', this.complete, this);\nreturn this;  // return eventEmitter to pause the sequence\n}\n\nwaitTime(delay) {\nthis.scene.time.delayedCall(delay * 1000, this.complete, [], this);\nreturn this;  // return eventEmitter to pause the sequence\n}\n\ncomplete() {\nthis.emit('complete');  // resume sequence\n}\n}\nvar actionScope = new ActionKlass(scene);\n

Now this scope supports 3 commands

  • print(msg): ['print', msg]
  • waitClick(): ['wait-click']
  • waitTime(delay): ['wait-time', delay]
"},{"location":"sequence/#state","title":"State","text":"
var state = seq.state;\n
  • 0 : Idle
  • 1 : Run
  • 2 : Last command
  • 3 : Completed
var completed = seq.completed; // seq.state === 3\n
"},{"location":"sequence/#other-properties","title":"Other properties","text":"
  • Yoyo
    • Get
      var yoyo = seq.yoyo;\n
    • Set
      seq.setYoyo();\nseq.setYoyo(fals);\n// seq.yoyo = yoyo;\n
  • Repeat
    • Get
      var repeat = seq.repeat;\n
    • Set
      seq.setRepeat(count);\n
  • Loop
    • Get
      var loop = seq.loop;\n
    • Set
      seq.setLoop();\nseq.setLoop(fals);\n// seq.loop = loop;\n
"},{"location":"shader-barrel/","title":"Barrel","text":"

Note

Phaser3.60 has a built-in barrel effect.

"},{"location":"shader-barrel/#introduction","title":"Introduction","text":"

Barrel post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-barrel/#live-demos","title":"Live demos","text":"
  • Barrel
"},{"location":"shader-barrel/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-barrel/#install-plugin","title":"Install plugin","text":""},{"location":"shader-barrel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexbarrelpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexbarrelpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexbarrelpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexbarrelpipelineplugin').add(camera, config);\n
"},{"location":"shader-barrel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import BarrelPipelinePlugin from 'phaser3-rex-plugins/plugins/barrelpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexBarrelPipeline',\nplugin: BarrelPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexBarrelPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexBarrelPipeline').add(camera, config);\n
"},{"location":"shader-barrel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import BarrelPostFx from 'phaser3-rex-plugins/plugins/barrelpipeline.js';\nvar config = {\n// ...\npipeline: [BarrelPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(BarrelPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(BarrelPostFx);\n
"},{"location":"shader-barrel/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 barrel effect.
    var pipelineInstance = scene.plugins.get('rexBarrelPipeline').add(gameObject, {\n// shrink: false,\n// center: {\n//    x: windowWidth / 2,\n//    y: windowHeight / 2\n//}\n// radius: 0,\n// power: 0.5,\n// intensity: 1,\n\n// name: 'rexBarrelPostFx'\n});\n
    • shrink :
      • false : Fish-eye effect
      • true : Anti fish-eye effect.
    • center.x, center.y : Local position of barrel center.
    • radius : Barrel radius.
    • power : 0~1.
    • intensity : 0(original) ~ 1(barrel). Default value is 1.
  • Apply effect to camera. A camera only can add 1 barrel effect.
    var pipelineInstance = scene.plugins.get('rexBarrelPipeline').add(camera, config);\n
"},{"location":"shader-barrel/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexBarrelPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexBarrelPipeline').remove(camera);\n
"},{"location":"shader-barrel/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexBarrelPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexBarrelPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexBarrelPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexBarrelPipeline').get(camera);\n
"},{"location":"shader-barrel/#shrink-mode","title":"Shrink mode","text":"
  • Get
    var shrinkMode = pipelineInstance.shrinkMode;\n
  • Set
    pipelineInstance.setShrinkMode(true);\n// pipelineInstance.setShrinkMode(false);\n
"},{"location":"shader-barrel/#radius","title":"Radius","text":"
  • Get
    var radius = pipelineInstance.radius;\n
  • Set
    pipelineInstance.radius = radius;\n// pipelineInstance.radius += value;\n
    or
    pipelineInstance.setRadius(radius);\n
"},{"location":"shader-barrel/#power","title":"Power","text":"
  • Get
    var power = pipelineInstance.power;\n
  • Set
    pipelineInstance.power = power;\n
    or
    pipelineInstance.setPower(power);\n
"},{"location":"shader-barrel/#intensity","title":"Intensity","text":"
  • Get
    var intensity = pipelineInstance.intensity;\n
  • Set
    pipelineInstance.intensity = intensity;\n// pipelineInstance.intensity += value;\n
    or
    pipelineInstance.setIntensity(radius);\n
    • intensity : 0(original) ~ 1(barrel)
"},{"location":"shader-barrel/#center-position","title":"Center position","text":"

Default value is center of window.

  • Get
    var x = pipelineInstance.centerX;\nvar y = pipelineInstance.centerY;\n
  • Set
    pipelineInstance.centerX = x;\npipelineInstance.centerY = y;\n
    or
    pipelineInstance.setCenter(x, y);\n// pipelineInstance.setCenter();   // set to center of window\n
"},{"location":"shader-builtin/","title":"Effects","text":""},{"location":"shader-builtin/#introduction","title":"Introduction","text":"

Built-in pre-fx, and post-fx shader effects.

  • Barrel Distortion : A nice pinch / bulge distortion effect.
  • Bloom : Add bloom to any Game Object, with custom offset, blur strength, steps and color.
  • Blur : 3 different levels of gaussian blur (low, medium and high) and custom distance and color.
  • Bokeh / Tilt Shift : A bokeh and tiltshift effect, with intensity, contrast and distance settings.
  • Circle Outline : Add a circular ring around any Game Object, useful for masking / avatar frames, with custom color, width and background color.
  • Color Matrix : Add a ColorMatrix to any Game Object with access to all of its methods, such as sepia, greyscale, lsd and lots more.
  • Glow : Add a smooth inner or outer glow, with custom distance, strength and color.
  • Displacement : Use a displacement texture, such as a noise texture, to drastically (or subtly!) alter the appearance of a Game Object.
  • Gradient : Draw a gradient between two colors across any Game Object, with optional 'chunky' mode for classic retro style games.
  • Pixelate : Make any Game Object appear pixelated, to a varying degree.
  • Shine : Run a 'shine' effect across a Game Object, either additively or as part of a reveal.
  • Shadow : Add a drop shadow behind a Game Object, with custom depth and color.
  • Vignette : Apply a vignette around a Game Object, with custom offset position, radius and color.
  • Wipe / Reveal : Set a Game Object to 'wipe' or 'reveal' with custom line width, direction and axis of the effect.

Texture-based Game Objects also support Pre FX, including: Image, Sprite, TileSprite, Text, RenderTexture, Video.

All Game Objects and camera support Post FX. These are effects applied after the Game Object has been rendered.

  • Author: Richard Davey
  • Pre-fx, and Post-fx shader effects

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-builtin/#live-demos","title":"Live demos","text":"
  • Official demos
"},{"location":"shader-builtin/#usage","title":"Usage","text":""},{"location":"shader-builtin/#barrel","title":"Barrel","text":"
  • Add pre-fx to game object
    // gameObject.preFX.setPadding(padding);\nvar effect = gameObject.preFX.addBarrel(amount);\n
    • padding : The amount of padding to add to this Game Object, in pixels.
      • Used when amount is larger than 1.
    • amount : The amount of distortion applied to the barrel effect.
      • 1 : No distortion
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addBarrel(amount);\n
    var effect = camera.postFX.addBarrel(amount);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.amount = amount;\n
"},{"location":"shader-builtin/#bloom","title":"Bloom","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addBloom(color, offsetX, offsetY, blurStrength, strength, steps);\n
    • color : The color of the Bloom, as a hex value.
    • offsetX, offsetY : The horizontal/vertical offset of the bloom effect. Default value is 1.
    • blurStrength , strength : The strength of the blur/blend process of the bloom effect. Default value is 1.
    • steps : The number of steps to run the Bloom effect for. This value should always be an integer. Default value is 4.
      • The higher the value, the smoother the Bloom, but at the cost of exponentially more gl operations.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addBloom(color, offsetX, offsetY, blurStrength, strength, steps);\n
    var effect = camera.postFX.addBloom(color, offsetX, offsetY, blurStrength, strength, steps);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.color = color;  // hex value\neffect.offsetX = offsetX;\neffect.offsetY = offsetY;\neffect.blurStrength = blurStrength;\neffect.strength = strength;\neffect.steps = steps; // integer\n
"},{"location":"shader-builtin/#blur","title":"Blur","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addBlur(quality, x, y, strength, color, steps);\n
    • quality : The quality of the blur effect. Default value is 0.
      • 0 : Low Quality
      • 1 : Medium Quality
      • 2 : High Quality
    • x, y : The horizontal/vertical offset of the blur effect. Default value is 2
    • strength : The strength of the blur effect. Default value is 1.
    • color : The color of the blur, as a hex value. Default value is 0xffffff.
    • steps : The number of steps to run the blur effect for. This value should always be an integer.
      • The higher the value, the smoother the blur, but at the cost of exponentially more gl operations.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addBlur(quality, x, y, strength, color, steps);\n
    var effect = camera.postFX.addBlur(quality, x, y, strength, color, steps);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.quality = quality;\neffect.x = x;\neffect.y = y;\neffect.strength = strength;\neffect.color = color;\neffect.steps = steps;\n
"},{"location":"shader-builtin/#bokeh","title":"Bokeh","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addBokeh(radius, amount, contrast);\n
    • radius : The radius of the bokeh effect. Default value is 0.5.
    • amount : The amount of the bokeh effect. Default value is 1.
    • contrast : The color contrast of the bokeh effect. Default value is 0.2.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addBlur(quality, x, y, strength, color, steps);\n
    var effect = camera.postFX.addBokeh(radius, amount, contrast);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.radius = radius;\neffect.amount = amount;\neffect.contrast = contrast;\n
"},{"location":"shader-builtin/#tilt-shift","title":"Tilt Shift","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addTiltShift(radius, amount, contrast, blurX, blurY, strength);\n
    • radius : The radius of the bokeh effect. Default value is 0.5.
    • amount : The amount of the bokeh effect. Default value is 1.
    • contrast : The color contrast of the bokeh effect. Default value is 0.2.
    • blurX, blurY : The amount of horizontal/vertical blur.
    • strength : The strength of the blur.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addTiltShift(radius, amount, contrast, blurX, blurY, strength);\n
    var effect = camera.postFX.addTiltShift(radius, amount, contrast, blurX, blurY, strength);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.radius = radius;\neffect.amount = amount;\neffect.contrast = contrast;\neffect.blurX = blurX;\neffect.blurY = blurY;\neffect.strength = strength;\n
"},{"location":"shader-builtin/#circle-outline","title":"Circle Outline","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addCircle(thickness, color, backgroundColor, scale, feather);\n
    • thickness : The width of the circle around the texture, in pixels. Default value is 8.
    • color : The color of the circular ring, given as a number value. Default value is 0xfeedb6.
    • backgroundColor : The color of the background, behind the texture, given as a number value. Default value is 0xff0000.
    • scale : The scale of the circle. Default value is 1.
      • 1 : Full size of the underlying texture.
    • feather : The amount of feathering to apply to the circle from the ring. Default value is 0.005.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addCircle(thickness, color, backgroundColor, scale, feather);\n
    var effect = camera.postFX.addCircle(thickness, color, backgroundColor, scale, feather);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.thickness = thickness;\neffect.color = color;\neffect.backgroundColor = backgroundColor;\neffect.backgroundAlpha = backgroundAlpha;\neffect.scale = scale;\neffect.feather = feather;\n
"},{"location":"shader-builtin/#colormatrix","title":"ColorMatrix","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addColorMatrix();\n
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addColorMatrix();\n
    var effect = camera.postFX.addColorMatrix();\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Methods
    • Brightness : Changes the brightness of this ColorMatrix by the given amount.
      effect.brightness(value, multiply);\n
      • value : The amount of brightness to apply to this ColorMatrix. 0(black)~1. Default value is 0.
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Saturate : Changes the saturation of this ColorMatrix by the given amount.
      effect.saturate(value, multiply);\n
      • value : The amount of saturation to apply to this ColorMatrix. Default value is 0.
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Desaturate : Desaturates this ColorMatrix (removes color from it).
      effect.desaturate(value, multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Hue : Rotates the hues of this ColorMatrix by the value given.
      effect.hue(rotation, multiply);\n
      • rotation : The amount of hue rotation to apply to this ColorMatrix, in degrees. Default value is 0.
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Grayscale : Sets this ColorMatrix to be grayscale.
      effect.grayscale(value, multiply);\n
      • value : The grayscale scale 0(black)~1. Default value is 1.
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • BlackWhite : Sets this ColorMatrix to be black and white.
      effect.blackWhite(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Contrast : Change the contrast of this ColorMatrix by the amount given.
      effect.contrast(value, multiply);\n
      • value : The amount of contrast to apply to this ColorMatrix. Default value is 0.
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Negative : Converts this ColorMatrix to have negative values.
      effect.negative(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • DesaturateLuminance : Apply a desaturated luminance to this ColorMatrix.
      effect.desaturateLuminance(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Sepia : Applies a sepia tone to this ColorMatrix.
      effect.sepia(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Night : Applies a night vision tone to this ColorMatrix.
      effect.night(intensity, multiply);\n
      • intensity : The intensity of this effect. Default value is 0.1.
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • LSD : Applies a trippy color tone to this ColorMatrix.
      effect.lsd(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Brown : Applies a brown tone to this ColorMatrix.
      effect.brown(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • VintagePinhole : Applies a vintage pinhole color effect to this ColorMatrix.
      effect.vintagePinhole(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Kodachrome : Applies a kodachrome color effect to this ColorMatrix.
      effect.kodachrome(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Technicolor : Applies a technicolor color effect to this ColorMatrix.
      effect.technicolor(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • Polaroid : Applies a polaroid color effect to this ColorMatrix.
      effect.polaroid(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
    • ShiftToBGR : Shifts the values of this ColorMatrix into BGR order.
      effect.shiftToBGR(multiply);\n
      • multiply : Multiply the resulting ColorMatrix (true), or set it (false) ?
        • true : Multiply the resulting.
        • false : Set the resulting. Default behavior.
"},{"location":"shader-builtin/#displacement","title":"Displacement","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addDisplacement(texture, x, y);\n
    • texture : The unique string-based key of the texture to use for displacement, which must exist in the Texture Manager. Default value is '__WHITE'.
      • You can only use a whole texture, not a frame from a texture atlas or sprite sheet.
    • x, y : The amount of horizontal/vertical displacement to apply. Default value is 0.005.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addDisplacement(texture, x, y);\n
    var effect = camera.postFX.addDisplacement(texture, x, y);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.x = x;\neffect.y = y;    
  • Methods
    • Set texture
      effect.setTexture(key);\n
"},{"location":"shader-builtin/#glow","title":"Glow","text":"
  • Add pre-fx to game object
    // gameObject.preFX.setPadding(padding);\nvar effect = gameObject.preFX.addGlow(color, outerStrength, innerStrength, knockout);\n
    • padding : The amount of padding to add to this Game Object, in pixels.
      • Used when amount is larger than 1.
    • color : The color of the glow effect as a number value. Default value is 0xffffff.
    • outerStrength, innerStrength : The strength of the glow outward/inward from the edge of the Sprite. Default value is 4/0.
    • knockout :
      • true : Only the glow is drawn
      • false : Draw glow and texture. Default behavior.
    • quality : Only available for PostFX. Sets the quality of this Glow effect. Default is 0.1. Cannot be changed post-creation.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addGlow(color, outerStrength, innerStrength, knockout, quality, distance);\n
    var effect = camera.postFX.addGlow(color, outerStrength, innerStrength, knockout, quality, distance);\n
    • quality : Sets the quality of this Glow effect. Default is 0.1. Cannot be changed post-creation.
    • distance : Sets the distance of this Glow effect. Default is 10. Cannot be changed post-creation.
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.color = color;\neffect.outerStrength = outerStrength;\neffect.innerStrength = innerStrength;\neffect.knockout = knockout;\n
"},{"location":"shader-builtin/#gradient","title":"Gradient","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addGradient(color1, color2, alpha, fromX, fromY, toX, toY, size);\n
    • color1, color2 : The first/second gradient color, given as a number value. Default values are 0xff0000/0x00ff00.
    • alpha : The alpha value of the gradient effect.
    • fromX, fromY : The horizontal/vertical position the gradient will start from. Value between 0 and 1.
    • toX, toY : The horizontal/vertical position the gradient will end at. Value between 0 and 1.
    • size : How many 'chunks' the gradient is divided in to, as spread over the entire height of the texture.
      • 0 : Smooth gradient. Default behavior.
      • Others : Retro chunky effect.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addGradient(color1, color2, alpha, fromX, fromY, toX, toY, size);\n
    var effect = camera.postFX.addGradient(color1, color2, alpha, fromX, fromY, toX, toY, size);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.color1 = color1;\neffect.color2 = color2;\neffect.alpha = alpha;\neffect.fromX = fromX;\neffect.fromY = fromY;\neffect.toX = toX;\neffect.toY = toY;\neffect.size = size;\n
"},{"location":"shader-builtin/#pixelate","title":"Pixelate","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addPixelate(amount);\n
    • amount : The amount of pixelation to apply, in pixels.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addPixelate(amount);\n
    var effect = camera.postFX.addPixelate(amount);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.amount = amount;\n
"},{"location":"shader-builtin/#shadow","title":"Shadow","text":"
  • Add pre-fx to game object
    // gameObject.preFX.setPadding(padding);\nvar effect = gameObject.preFX.addShadow(x, y, decay, power, color, samples, intensity);\n
    • padding : The amount of padding to add to this Game Object, in pixels.
      • Used when amount is larger than 1.
    • x, y : The horizontal/vertical offset of the shadow effect. Default value is 0.
    • decay : The amount of decay for shadow effect. Default value is 0.1.
    • power : The power of the shadow effect. Default value is 1.
    • color : The color of the shadow. Default value is 0x000000.
    • samples : The number of samples that the shadow effect will run for. An integer between 1 and 12.
    • intensity : The intensity of the shadow effect. Default value is 1.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addShadow(x, y, decay, power, color, samples, intensity);\n
    var effect = camera.postFX.addShadow(x, y, decay, power, color, samples, intensity);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.x = x;\neffect.y = y;\neffect.decay = decay;\neffect.power = power;\neffect.color = color;\neffect.samples = samples;\neffect.intensity = intensity;\n
"},{"location":"shader-builtin/#shine","title":"Shine","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addShine(speed, lineWidth, gradient, reveal);\n
    • speed : The speed of the Shine effect. Default value is 0.5.
    • lineWidth : The line width of the Shine effect. Default value is 0.5.
    • gradient : The gradient of the Shine effect. Default value is 3.
    • reveal : Does this Shine effect reveal or get added to its target?
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addShine(speed, lineWidth, gradient, reveal);\n
    var effect = camera.postFX.addShine(speed, lineWidth, gradient, reveal);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.speed = speed;\neffect.lineWidth = lineWidth;\neffect.gradient = gradient;\neffect.reveal = reveal;\n
"},{"location":"shader-builtin/#vignette","title":"Vignette","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addVignette(x, y, radius, strength);\n
    • x, y : The horizontal/vertical offset of the vignette effect. Value is between 0 and 1. Default value is 0.5.
    • radius : The radius of the vignette effect. Value is between 0 and 1. Default value is 0.5.
    • strength : The strength of the vignette effect. Default value is 0.5.
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addVignette(x, y, radius, strength);\n
    var effect = camera.postFX.addVignette(x, y, radius, strength);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.x = x;\neffect.y = y;\neffect.radius = radius;\neffect.strength = strength;\n
"},{"location":"shader-builtin/#wipe","title":"Wipe","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addWipe(wipeWidth, direction, axis);\n
    • wipeWidth : The width of the wipe effect. Value is between 0 and 1. Default value is 0.1.
    • direction : The direction of the wipe effect.
      • 0 : Left to right, or top to bottom
      • 1 : Right to left, or bottom to top
    • axis : The axis of the wipe effect.
      • 0 : Left to right, or right to left
      • 1 : Bottom to top, or top to bottom
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addWipe(wipeWidth, direction, axis);\n
    var effect = camera.postFX.addWipe(wipeWidth, direction, axis);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.progress = t; // 0~1\neffect.wipeWidth = wipeWidth;\neffect.direction = direction;  // 0, 1\neffect.axis = axis;  // 0, 1    \n
"},{"location":"shader-builtin/#reveal","title":"Reveal","text":"
  • Add pre-fx to game object
    var effect = gameObject.preFX.addReveal(wipeWidth, direction, axis);\n
    • wipeWidth : The width of the wipe effect. Value is between 0 and 1. Default value is 0.1.
    • direction : The direction of the wipe effect.
      • 0 : Left to right, or top to bottom
      • 1 : Right to left, or bottom to top
    • axis : The axis of the wipe effect.
      • 0 : Left to right, or right to left
      • 1 : Bottom to top, or top to bottom
  • Add post-fx to game object, or camera
    var effect = gameObject.postFX.addReveal(wipeWidth, direction, axis);\n
    var effect = camera.postFX.addReveal(wipeWidth, direction, axis);\n
  • Disable effect
    effect.setActive(false);\n// effect.active = false;\n
  • Remove effect
    gameObject.preFX.remove(effect);\n
    camera.postFX.remove(effect);\n
  • Properties
    effect.progress = t; // 0~1\neffect.wipeWidth = wipeWidth;\neffect.direction = direction;  // 0, 1\neffect.axis = axis;  // 0, 1\n
"},{"location":"shader-builtin/#remove-all-effects","title":"Remove all effects","text":"

gameObject.preFX.clear();\n
gameObject.postFX.clear();\n
camera.postFX.clear();\n

"},{"location":"shader-builtin/#disable-all-effects","title":"Disable all effects","text":"

gameObject.preFX.disable();\n// gameObject.preFX.disable(true);  // Also remove all effects\n
gameObject.postFX.disable();\n// gameObject.postFX.disable(true);  // Also remove all effects\n
camera.postFX.disable();\n// camera.postFX.disable(true);  // Also remove all effects\n

"},{"location":"shader-colorreplace/","title":"Color replace","text":""},{"location":"shader-colorreplace/#introduction","title":"Introduction","text":"

Replace color post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-colorreplace/#live-demos","title":"Live demos","text":"
  • Color replace
"},{"location":"shader-colorreplace/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-colorreplace/#install-plugin","title":"Install plugin","text":""},{"location":"shader-colorreplace/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcolorreplacepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcolorreplacepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexcolorreplacepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexcolorreplacepipelineplugin').add(camera, config);\n
"},{"location":"shader-colorreplace/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ColorReplacePipelinePlugin from 'phaser3-rex-plugins/plugins/colorreplacepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexColorReplacePipeline',\nplugin: ColorReplacePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexColorReplacePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexColorReplacePipeline').add(camera, config);\n
"},{"location":"shader-colorreplace/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import ColorReplacePostFx from 'phaser3-rex-plugins/plugins/colorreplacepipeline.js';\nvar config = {\n// ...\npipeline: [ColorReplacePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(ColorReplacePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(ColorReplacePostFx);\n
"},{"location":"shader-colorreplace/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 colorreplace effect.
    var pipelineInstance = scene.plugins.get('rexColorReplacePipeline').add(gameObject, {\noriginalColor: 0xFF0000,\nnewColor: 0x000000,\n// epsilon: 0.4,\n\n// name: 'rexColorReplacePostFx'\n});\n
    • originalColor : The color (0xRRGGBB) that will be changed.
    • newColor : The resulting color (0xRRGGBB).
    • epsilon : Tolerance/sensitivity of the floating-point comparison between colors (lower = more exact, higher = more inclusive)
  • Apply effect to camera. A camera only can add 1 colorreplace effect.
    var pipelineInstance = scene.plugins.get('rexColorReplacePipeline').add(camera, config);\n
"},{"location":"shader-colorreplace/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexColorReplacePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexColorReplacePipeline').remove(camera);\n
"},{"location":"shader-colorreplace/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexColorReplacePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexColorReplacePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexColorReplacePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexColorReplacePipeline').get(camera);\n
"},{"location":"shader-colorreplace/#original-color","title":"Original color","text":"
  • Get
    var color = pipelineInstance.originalColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    pipelineInstance.setOriginalColor(value);\n
    pipelineInstance.originalColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"shader-colorreplace/#new-color","title":"New color","text":"
  • Get
    var color = pipelineInstance.newColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    pipelineInstance.setNewColor(value);\n
    pipelineInstance.newColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"shader-colorreplace/#epsilon","title":"Epsilon","text":"
  • Get
    var epsilon = pipelineInstance.epsilon;\n
  • Set
    pipelineInstance.epsilon = epsilon;\n// pipelineInstance.epsilon += value;\n
    or
    pipelineInstance.setEpsilon(value);\n
"},{"location":"shader-crossstitching/","title":"Cross-stitching","text":""},{"location":"shader-crossstitching/#introduction","title":"Introduction","text":"

Cross-stitching post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-crossstitching/#live-demos","title":"Live demos","text":"
  • Cross-stitching
"},{"location":"shader-crossstitching/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-crossstitching/#install-plugin","title":"Install plugin","text":""},{"location":"shader-crossstitching/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcrossstitchingpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcrossstitchingpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexcrossstitchingpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexcrossstitchingpipelineplugin').add(camera, config);\n
"},{"location":"shader-crossstitching/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CrossStitchingPipelinePlugin from 'phaser3-rex-plugins/plugins/crossstitchingpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCrossStitchingPipeline',\nplugin: CrossStitchingPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexCrossStitchingPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexCrossStitchingPipeline').add(camera, config);\n
"},{"location":"shader-crossstitching/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import CrossStitchingPostFx from 'phaser3-rex-plugins/plugins/crossstitchingpipeline.js';\nvar config = {\n// ...\npipeline: [CrossStitchingPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(CrossStitchingPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(CrossStitchingPostFx);\n
"},{"location":"shader-crossstitching/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 cross-stitching effect.
    var pipelineInstance = scene.plugins.get('rexCrossStitchingPipeline').add(gameObject, {\n// stitchingWidth: 6,\n// stitchingHeight: 6,\n// brightness: 0,\n\n// name: 'rexCrossStitchingPostFx'\n});\n
    • stitchingWidth, stitchingHeight : Stitching size.
    • brightness : Brightness of stitching edges
  • Apply effect to camera. A camera only can add 1 cross-stitching effect.
    var pipelineInstance = scene.plugins.get('rexCrossStitchingPipeline').add(camera, config);\n
"},{"location":"shader-crossstitching/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexCrossStitchingPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexCrossStitchingPipeline').remove(camera);\n
"},{"location":"shader-crossstitching/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexCrossStitchingPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexCrossStitchingPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexCrossStitchingPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexCrossStitchingPipeline').get(camera);\n
"},{"location":"shader-crossstitching/#stitching-size","title":"Stitching size","text":"
  • Get
    var stitchingWidth = pipelineInstance.stitchingWidth;\nvar stitchingHeight = pipelineInstance.stitchingHeight;\n
  • Set
    pipelineInstance.stitchingWidth = stitchingWidth;\npipelineInstance.stitchingHeight = stitchingHeight;\n// pipelineInstance.stitchingWidth += value;\n// pipelineInstance.stitchingHeight += value;\n
    or
    pipelineInstance.setStitchingWidth(stitchingWidth);\npipelineInstance.setStitchingHeight(stitchingHeight);\npipelineInstance.setStitchingSize(stitchingWidth, stitchingHeight);\n
"},{"location":"shader-crossstitching/#brightness","title":"Brightness","text":"
  • Get
    var brightness = pipelineInstance.brightness;\n
  • Set
    pipelineInstance.brightness = brightness;\n// pipelineInstance.brightness += value;\n
    or
    pipelineInstance.setBrightness(radius);\n
    • brightness : 0(black) ~ 1(white)
"},{"location":"shader-crt/","title":"CRT","text":""},{"location":"shader-crt/#introduction","title":"Introduction","text":"

CRT post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-crt/#live-demos","title":"Live demos","text":"
  • CRT
"},{"location":"shader-crt/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-crt/#install-plugin","title":"Install plugin","text":""},{"location":"shader-crt/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcrtpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcrtpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexcrtpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexcrtpipelineplugin').add(camera, config);\n
"},{"location":"shader-crt/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CrtPipelinePlugin from 'phaser3-rex-plugins/plugins/crtpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCrtPipeline',\nplugin: CrtPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexCrtPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexCrtPipeline').add(camera, config);\n
"},{"location":"shader-crt/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import CrtPostFx from 'phaser3-rex-plugins/plugins/crtpipeline.js';\nvar config = {\n// ...\npipeline: [CrtPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(CrtPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(CrtPostFx);\n
"},{"location":"shader-crt/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 crt effect.
    var pipelineInstance = scene.plugins.get('rexCrtPipeline').add(gameObject, {\n// warpX: 0.75,\n// warpY: 0.75,\n// scanLineStrength: 0.2,\n// scanLineWidth: 1024,\n\n// name: 'rexCrtPostFx'\n});\n
    • warpX, warpY : Horizontal and Vertical warp.
    • scanLineStrength, scanLineWidth : Scan line parameters.
  • Apply effect to camera. A camera only can add 1 crt effect.
    var pipelineInstance = scene.plugins.get('rexCrtPipeline').add(camera, config);\n
"},{"location":"shader-crt/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexCrtPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexCrtPipeline').remove(camera);\n
"},{"location":"shader-crt/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexCrtPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexCrtPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexCrtPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexCrtPipeline').get(camera);\n
"},{"location":"shader-crt/#warp","title":"Warp","text":"
  • Get
    var warpX = pipelineInstance.warpX;\nvar warpY = pipelineInstance.warpY;\n
  • Set
    pipelineInstance.setWarp(warpX, warpY);\n
    or
    pipelineInstance.warpX = warpX;\npipelineInstance.warpY = warpY;\n
"},{"location":"shader-crt/#scan-lines","title":"Scan lines","text":"
  • Get
    var scanLineStrength = pipelineInstance.scanLineStrength;\nvar scanLineWidth = pipelineInstance.scanLineWidth;\n
  • Set
    pipelineInstance.setScanStrength(scanLineStrength);\npipelineInstance.setScanLineWidth(scanLineWidth);\n
    or
    pipelineInstance.scanLineStrength = scanLineStrength;\npipelineInstance.scanLineWidth = scanLineWidth;\n
"},{"location":"shader-dissolve/","title":"Dissolve","text":""},{"location":"shader-dissolve/#introduction","title":"Introduction","text":"

Dissolve transition post processing filter. (Reference)

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-dissolve/#live-demos","title":"Live demos","text":"
  • Dissolve
"},{"location":"shader-dissolve/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-dissolve/#install-plugin","title":"Install plugin","text":""},{"location":"shader-dissolve/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexdissolvepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdissolvepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexdissolvepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexdissolvepipelineplugin').add(camera, config);\n
"},{"location":"shader-dissolve/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import DissolvePipelinePlugin from 'phaser3-rex-plugins/plugins/dissolvepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexDissolvePipeline',\nplugin: DissolvePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexDissolvePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexDissolvePipeline').add(camera, config);\n
"},{"location":"shader-dissolve/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import DissolvePostFx from 'phaser3-rex-plugins/plugins/dissolvepipeline.js';\nvar config = {\n// ...\npipeline: [DissolvePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(DissolvePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(DissolvePostFx);\n
"},{"location":"shader-dissolve/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 gray-scale effect.
    var pipelineInstance = scene.plugins.get('rexDissolvePipeline').add(gameObject, {\n// toTexture: textureKey,\n// toFrame: frameName,\n// resizeMode: 1,\n\n// noiseX: undefined,\n// noiseY: undefined,\n// noiseZ: undefined,\n// fromEdgeStart: 0.01,\n// fromEdgeWidth: 0.05,\n// toEdgeStart: 0.01,\n// toEdgeWidth: 0.05,\n\n// progress: 0,\n\n// name: 'rexDissolvePostFx'\n});\n
    • toTexture, toFrame : Texture key and frame name of transition target texture.
    • resizeMode : Resize mode of transition target texture.
      • 0, or 'stretch' : The target texture is stretched to the size of the source texture.
      • 1, or 'contain' : The target texture is resized to fit the source texture.
      • 2, or 'cover' : The target texture is resized to cover the source texture.
    • noiseX, noiseY, noiseZ : Parameter of Perline noise.
      • undefined : A random value.
    • fromEdgeStart, fromEdgeWidth : Dissolve edge start, edge width of from-texture (texture of game object, or render result of camera).
    • toEdgeStart, toEdgeWidth : Reveal edge start, edge width of to-texture.
  • Apply effect to camera. A camera only can add 1 gray-scale effect.
    var pipelineInstance = scene.plugins.get('rexDissolvePipeline').add(camera, config);\n
"},{"location":"shader-dissolve/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexDissolvePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexDissolvePipeline').remove(camera);\n
"},{"location":"shader-dissolve/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexDissolvePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexDissolvePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexDissolvePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexDissolvePipeline').get(camera);\n
"},{"location":"shader-dissolve/#transition-target-texture","title":"Transition target texture","text":"
  • Get
    var textureKey = pipelineInstance.toFrame.texture.key;\nvar frameName = pipelineInstance.toFrame.name;\n
  • Set
    pipelineInstance.setTransitionTargetTexture(textureKey, frameName);\n// pipelineInstance.setTransitionTargetTexture(textureKey, frameName, resizeMode);\n
"},{"location":"shader-dissolve/#progress","title":"Progress","text":"
  • Get
    var progress = pipelineInstance.progress;\n
  • Set
    pipelineInstance.setProgress(value);  // value: 0~1\n
    or
    pipelineInstance.progress = value;  // value: 0~1\n
"},{"location":"shader-dissolve/#resize-mode","title":"Resize mode","text":"
  • Get
    var mode = pipelineInstance.resizeMode;\n
  • Set
    pipelineInstance.setResizeMode(mode);\n
    • mode :
      • 0, or 'stretch' : The target texture is stretched to the size of the source texture.
      • 1, or 'contain' : The target texture is resized to fit the source texture.
      • 2, or 'cover' : The target texture is resized to cover the source texture.
"},{"location":"shader-dissolve/#noise","title":"Noise","text":"
  • Get
    var noiseX = pipelineInstance.noiseX;\nvar noiseY = pipelineInstance.noiseY;\nvar noiseZ = pipelineInstance.noiseZ;\n
  • Set
    pipelineInstance.noiseX = noiseX;\npipelineInstance.noiseY = noiseY;\npipelineInstance.noiseZ = noiseZ;\n
    or
    pipelineInstance.setNoise(noiseX, noiseY, noiseZ);\n// pipelineInstance.setNoise(); // Passing 3 random float numbers\n
"},{"location":"shader-dissolve/#edge","title":"Edge","text":"
  • Get
    • From texture (texture of game object, or render result of camera)
      var edgeStart = pipelineInstance.fromEdgeStart;\nvar edgeWidth = pipelineInstance.fromEdgeWidth;\n
    • To texture (transition target texture)
      var edgeStart = pipelineInstance.toEdgeStart;\nvar edgeWidth = pipelineInstance.toEdgeWidth;\n
  • Set
    • From texture (texture of game object, or render result of camera)
      pipelineInstance.fromEdgeStart = edgeStart;\npipelineInstance.fromEdgeWidth = edgeWidth;\n
      or
      pipelineInstance.setFromEdge(edgeStart, edgeWidth);\n
      • edgeStart : 0~1, default value is 0.01
      • edgeWidth : 0~1, default value is 0.05
    • To texture (transition target texture)
      pipelineInstance.toEdgeStart = edgeStart;\npipelineInstance.toEdgeWidth = edgeWidth;\n
      or
      pipelineInstance.setToEdge(edgeStart, edgeWidth);\n
      • edgeStart : 0~1, default value is 0.01
      • edgeWidth : 0~1, default value is 0.05
"},{"location":"shader-dropshadow/","title":"Drop shadow","text":"

Note

Built-in preFX/postFX also provide shadow effect, might try these first.

"},{"location":"shader-dropshadow/#introduction","title":"Introduction","text":"

Drop-shadow post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-dropshadow/#live-demos","title":"Live demos","text":"
  • Drop-shadow
"},{"location":"shader-dropshadow/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-dropshadow/#install-plugin","title":"Install plugin","text":""},{"location":"shader-dropshadow/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexdropshadowpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexdropshadowpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexdropshadowpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexdropshadowpipelineplugin').add(camera, config);\n
"},{"location":"shader-dropshadow/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import DropShadowPipelinePlugin from 'phaser3-rex-plugins/plugins/dropshadowpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexDropShadowPipeline',\nplugin: DropShadowPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexDropShadowPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexDropShadowPipeline').add(camera, config);\n
"},{"location":"shader-dropshadow/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import DropShadowPostFx from 'phaser3-rex-plugins/plugins/dropshadowpipeline.js';\nvar config = {\n// ...\npipeline: [DropShadowPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(DropShadowPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(DropShadowPostFx);\n
"},{"location":"shader-dropshadow/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 dropshadow effect.
    var pipelineInstance = scene.plugins.get('rexDropShadowPipeline').add(gameObject, {\n// ** Offset **\n// rotation: \n// angle: 45,      // degrees\n// distance: 5,\n\n// ** Shadow color **\n// shadowColor: 0xffffff,\n// alpha: 0.5,\n\n// shadowOnly: false,\n\n// ** Parameters of KawaseBlur **\n// blur: 4,\n// quality: 3,\n// pixelWidth: 1,\n// pixelHeight: 1,\n\n// name: 'rexDropShadowPostFx'\n});\n
    • Offset
      • rotation, angle : The angle of the shadow in radians/degrees.
      • distance : Distance of shadow.
    • Color
      • shadowColor : Color of the shadow.
      • alpha : Alpha of the shadow.
    • shadowOnly : Whether render shadow only.
    • Parameters of KawaseBlur
      • blur : The blur of the filter. Should be greater than 0. If value is an Array, setting kernels.
      • quality : The quality of the filter. Should be an integer greater than 1.
      • pixelWidth, pixelHeight : Sets the pixel size of the filter. Large size is blurrier. For advanced usage.
  • Apply effect to camera. A camera only can add 1 dropshadow effect.
    var pipelineInstance = scene.plugins.get('rexDropShadowPipeline').add(camera, config);\n
"},{"location":"shader-dropshadow/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexDropShadowPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexDropShadowPipeline').remove(camera);\n
"},{"location":"shader-dropshadow/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexDropShadowPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexDropShadowPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexDropShadowPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexDropShadowPipeline').get(camera);\n
"},{"location":"shader-dropshadow/#rotation","title":"Rotation","text":"
  • Get
    var rotation = pipelineInstance.rotation;  // radians\n// var angle = pipelineInstance.angle;     // degrees\n
  • Set
    pipelineInstance.rotation = rotation;   // radians\n// pipelineInstance.angle = angle;      // degrees\n
    or
    pipelineInstance.setRotation(radians);\npipelineInstance.setAngle(degrees);\n
"},{"location":"shader-dropshadow/#distance","title":"Distance","text":"
  • Get
    var distance = pipelineInstance.distance;\n
  • Set
    pipelineInstance.distance = distance;\n// pipelineInstance.distance += value;\n
    or
    pipelineInstance.setDistance(distance);\n
"},{"location":"shader-dropshadow/#shadow-color","title":"Shadow color","text":"
  • Get
    var color = pipelineInstance.shadowColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    pipelineInstance.setShadowColor(value);\n
    pipelineInstance.shadowColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"shader-dropshadow/#alpha","title":"Alpha","text":"
  • Get
    var alpha = pipelineInstance.alpha;\n
  • Set
    pipelineInstance.alpha = alpha;\n
    or
    pipelineInstance.setAlpha(alpha);\n
"},{"location":"shader-dropshadow/#shadow-only","title":"Shadow-only","text":"
  • Get
    var enable = pipelineInstance.shadowOnly;\n
  • Set
    pipelineInstance.shadowOnly = enable;\n
    or
    pipelineInstance.setShadowOnly(enable);\n
"},{"location":"shader-dropshadow/#blur","title":"Blur","text":"
  • Get
    var blur = pipelineInstance.blur;\n
  • Set
    pipelineInstance.blur = blur;\n// pipelineInstance.blur += value;\n
    or
    pipelineInstance.setBlur(value);\n
"},{"location":"shader-dropshadow/#quality","title":"Quality","text":"
  • Get
    var quality = pipelineInstance.quality;\n
  • Set
    pipelineInstance.quality = quality;\n// pipelineInstance.quality += value;\n
    or
    pipelineInstance.setQuality(value);\n
"},{"location":"shader-dropshadow/#pixel-size","title":"Pixel size","text":"
  • Get
    var pixelWidth = pipelineInstance.pixelWidth;\nvar pixelHeight = pipelineInstance.pixelHeight;\n
  • Set
    pipelineInstance.pixelWidth = pixelWidth;\npipelineInstance.pixelHeight = pixelHeight;\n
    or
    pipelineInstance.setPixelWidth(pixelWidth);\npipelineInstance.setPixelHeight(pixelHeight);\npipelineInstance.setPixelSize(pixelWidth, pixelHeight);\n
"},{"location":"shader-fisheye/","title":"Fisheye","text":""},{"location":"shader-fisheye/#introduction","title":"Introduction","text":"

Fish-eye post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-fisheye/#live-demos","title":"Live demos","text":"
  • FishEye
"},{"location":"shader-fisheye/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-fisheye/#install-plugin","title":"Install plugin","text":""},{"location":"shader-fisheye/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfisheyepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfisheyepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexfisheyepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexfisheyepipelineplugin').add(camera, config);\n
"},{"location":"shader-fisheye/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FishEyePipelinePlugin from 'phaser3-rex-plugins/plugins/fisheyepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFishEyePipeline',\nplugin: FishEyePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexFishEyePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexFishEyePipeline').add(camera, config);\n
"},{"location":"shader-fisheye/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import FishEyePostFx from 'phaser3-rex-plugins/plugins/fisheyepipeline.js';\nvar config = {\n// ...\npipeline: [FishEyePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(FishEyePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(FishEyePostFx);\n
"},{"location":"shader-fisheye/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 fisheye effect.
    var pipelineInstance = scene.plugins.get('rexFishEyePipeline').add(gameObject, {\n// center: {\n//    x: windowWidth / 2,\n//    y: windowHeight / 2\n//}\n// radius: 0,\n// intensity: 1,\n// mode:0,  // 0|1|'asin'|'sin'\n\n// name: 'rexFishEyePostFx'\n});\n
    • center.x, center.y : Local position of fisheye center.
    • radius : FishEye radius.
    • intensity : 0(original) ~ 1(fisheye). Default value is 1.
    • mode :
      • 0, or 'asin' : asin mode. Defaule value is 0.
      • 1, or 'sin' : sin mode.
  • Apply effect to camera. A camera only can add 1 fisheye effect.
    var pipelineInstance = scene.plugins.get('rexFishEyePipeline').add(camera, config);\n
"},{"location":"shader-fisheye/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexFishEyePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexFishEyePipeline').remove(camera);\n
"},{"location":"shader-fisheye/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexFishEyePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexFishEyePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexFishEyePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexFishEyePipeline').get(camera);\n
"},{"location":"shader-fisheye/#radius","title":"Radius","text":"
  • Get
    var radius = pipelineInstance.radius;\n
  • Set
    pipelineInstance.radius = radius;\n// pipelineInstance.radius += value;\n
    or
    pipelineInstance.setRadius(radius);\n
"},{"location":"shader-fisheye/#intensity","title":"Intensity","text":"
  • Get
    var intensity = pipelineInstance.intensity;\n
  • Set
    pipelineInstance.intensity = intensity;\n// pipelineInstance.intensity += value;\n
    or
    pipelineInstance.setIntensity(intensity);\n
    • intensity : 0(original) ~ 1(fisheye)
"},{"location":"shader-fisheye/#center-position","title":"Center position","text":"

Default value is center of window.

  • Get
    var x = pipelineInstance.centerX;\nvar y = pipelineInstance.centerY;\n
  • Set
    pipelineInstance.centerX = x;\npipelineInstance.centerY = y;\n
    or
    pipelineInstance.setCenter(x, y);\n// pipelineInstance.setCenter();   // set to center of window\n
"},{"location":"shader-fisheye/#mode","title":"Mode","text":"
  • Get
    var mode = pipelineInstance.fishEyeMode;\n
  • Set
    pipelineInstance.setFishEyeMode(mode);\n
    • 0, or 'asin' : asin mode.
    • 1, or 'sin' : sin mode.
"},{"location":"shader-glowfilter/","title":"Glow","text":"

Note

Phaser3.60 has a built-in Glow effect.

"},{"location":"shader-glowfilter/#introduction","title":"Introduction","text":"

Glow post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-glowfilter/#live-demos","title":"Live demos","text":"
  • Glow filter
"},{"location":"shader-glowfilter/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-glowfilter/#install-plugin","title":"Install plugin","text":""},{"location":"shader-glowfilter/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexglowfilterpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexglowfilterpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexglowfilterpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexglowfilterpipelineplugin').add(camera, config);\n
"},{"location":"shader-glowfilter/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GlowFilterPipelinePlugin from 'phaser3-rex-plugins/plugins/glowfilterpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGlowFilterPipeline',\nplugin: GlowFilterPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(camera, config);\n
"},{"location":"shader-glowfilter/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import GlowFilterPostFx from 'phaser3-rex-plugins/plugins/glowfilterpipeline.js';\nvar config = {\n// ...\npipeline: [GlowFilterPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(GlowFilterPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(GlowFilterPostFx);\n
"},{"location":"shader-glowfilter/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 glow effect.
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(gameObject, {\n// intensity: 0\n});\n
    • intensity : 0(original color) ~ 1(white color)
      • Suggestion value : 0 ~ 0.02
  • Apply effect to camera. A camera only can add 1 glow effect.
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(camera, config);\n
"},{"location":"shader-glowfilter/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexGlowFilterPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexGlowFilterPipeline').remove(camera);\n
"},{"location":"shader-glowfilter/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexGlowFilterPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexGlowFilterPipeline').get(camera);\n
"},{"location":"shader-glowfilter/#intensity","title":"Intensity","text":"
  • Get
    var intensity = pipelineInstance.intensity;\n
  • Set
    pipelineInstance.intensity = intensity;\n// pipelineInstance.intensity += value;\n
    or
    pipelineInstance.setIntensity(radius);\n
    • intensity : 0(original color) ~ 1(white color)
      • Suggestion value : 0 ~ 0.02
"},{"location":"shader-glowfilter2/","title":"Glow","text":"

Note

Phaser3.60 has a built-in Glow effect.

"},{"location":"shader-glowfilter2/#introduction","title":"Introduction","text":"

Glow post processing filter, port from pixi. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-glowfilter2/#live-demos","title":"Live demos","text":"
  • Glow filter
"},{"location":"shader-glowfilter2/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-glowfilter2/#install-plugin","title":"Install plugin","text":""},{"location":"shader-glowfilter2/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexglowfilter2pipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexglowfilter2pipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexglowfilter2pipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexglowfilter2pipelineplugin').add(camera, config);\n
"},{"location":"shader-glowfilter2/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GlowFilterPipelinePlugin from 'phaser3-rex-plugins/plugins/glowfilter2pipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGlowFilterPipeline',\nplugin: GlowFilterPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(camera, config);\n
"},{"location":"shader-glowfilter2/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import GlowFilterPostFx from 'phaser3-rex-plugins/plugins/glowfilter2pipeline.js';\nvar config = {\n// ...\npipeline: [GlowFilterPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(GlowFilterPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(GlowFilterPostFx);\n
"},{"location":"shader-glowfilter2/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 glowfilter effect.
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(gameObject, {    // outerStrength: 4,\n// innerStrength: 0,\n// glowColor: 0xffffff,\n// knockout: false,\n\n// distance: 10,\n// quality: 0.1,\n\n// name: 'rexGlowFilterPostFx'\n});\n
    • outerStrength : The strength of the glow outward from the edge of the texture.
    • innerStrength : The strength of the glow inward from the edge of the texture.
    • glowColor : The color of the glow.
    • knockout :
      • true : Only show effect.
      • false : Show content and effect.
    • distance : The distance of the glow. It can't be changed after filter creation.
    • quality : 0~1. The higher the number the less performant. It can't be changed after filter creation.
  • Apply effect to camera. A camera only can add 1 glowfilter effect.
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').add(camera, config);\n
"},{"location":"shader-glowfilter2/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexGlowFilterPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexGlowFilterPipeline').remove(camera);\n
"},{"location":"shader-glowfilter2/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexGlowFilterPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexGlowFilterPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexGlowFilterPipeline').get(camera);\n
"},{"location":"shader-glowfilter2/#outer-strength","title":"Outer strength","text":"
  • Get
    var outerStrength = pipelineInstance.outerStrength;\n
  • Set
    pipelineInstance.outerStrength = outerStrength;\n// pipelineInstance.outerStrength += value;\n
    or
    pipelineInstance.setOuterStrength(value);\n
"},{"location":"shader-glowfilter2/#inner-strength","title":"Inner strength","text":"
  • Get
    var innerStrength = pipelineInstance.innerStrength;\n
  • Set
    pipelineInstance.innerStrength = innerStrength;\n// pipelineInstance.innerStrength += value;\n
    or
    pipelineInstance.setInnerStrength(value);\n
"},{"location":"shader-glowfilter2/#glow-color","title":"Glow color","text":"
  • Get
    var color = pipelineInstance.glowColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    pipelineInstance.setGlowColor(value);\n
    pipelineInstance.glowColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"shader-glowfilter2/#distance","title":"Distance","text":"

The distance of the glow. Make it 2 times more for resolution=2. It can't be changed after filter creation.

  • Get
    var distance = pipelineInstance.distance;\n
  • Set
    pipelineInstance.setDistance(distance);\n
    or
    pipelineInstance.distance = distance;\n
    • distance : The distance of the glow.
"},{"location":"shader-glowfilter2/#quality","title":"Quality","text":"

A number between 0 and 1 that describes the quality of the glow. The higher the number the less performant.

  • Get
    var quality = pipelineInstance.quality;\n
  • Set
    pipelineInstance.setQuality(quality);\n
    or
    pipelineInstance.quality = quality;\n
    • quality : 0 ~ 1, default is 0.1.
      • 0.1 : 10 sample points.
      • 0.08 : 8 sample points.
      • 1 : 100 sample points.
"},{"location":"shader-grayscale/","title":"Gray scale","text":"

Note

Phaser3.60 has a built-in Color Matrix effects.

"},{"location":"shader-grayscale/#introduction","title":"Introduction","text":"

Gray scale post processing filter.

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-grayscale/#live-demos","title":"Live demos","text":"
  • Gray scale
"},{"location":"shader-grayscale/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-grayscale/#install-plugin","title":"Install plugin","text":""},{"location":"shader-grayscale/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexgrayscalepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexgrayscalepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexgrayscalepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexgrayscalepipelineplugin').add(camera, config);\n
"},{"location":"shader-grayscale/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import GrayScalePipelinePlugin from 'phaser3-rex-plugins/plugins/grayscalepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexGrayScalePipeline',\nplugin: GrayScalePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexGrayScalePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexGrayScalePipeline').add(camera, config);\n
"},{"location":"shader-grayscale/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import GrayScalePostFx from 'phaser3-rex-plugins/plugins/grayscalepipeline.js';\nvar config = {\n// ...\npipeline: [GrayScalePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(GrayScalePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(GrayScalePostFx);\n
"},{"location":"shader-grayscale/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 gray-scale effect.
    var pipelineInstance = scene.plugins.get('rexGrayScalePipeline').add(gameObject, {\n// intensity: 1,\n\n// name: 'rexGrayScalePostFx'\n});\n
    • intensity : 0(original color) ~ 1(gray scale). Default value is 1.
  • Apply effect to camera. A camera only can add 1 gray-scale effect.
    var pipelineInstance = scene.plugins.get('rexGrayScalePipeline').add(camera, config);\n
"},{"location":"shader-grayscale/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexGrayScalePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexGrayScalePipeline').remove(camera);\n
"},{"location":"shader-grayscale/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexGrayScalePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexGrayScalePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexGrayScalePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexGrayScalePipeline').get(camera);\n
"},{"location":"shader-grayscale/#intensity","title":"Intensity","text":"
  • Get
    var intensity = pipelineInstance.intensity;\n
  • Set
    pipelineInstance.intensity = intensity;\n// pipelineInstance.intensity += value;\n
    or
    pipelineInstance.setIntensity(radius);\n
    • intensity : 0(original color) ~ 1(gray scale)
"},{"location":"shader-horrifi/","title":"Horri-fi","text":""},{"location":"shader-horrifi/#introduction","title":"Introduction","text":"

6-in-1 post processing filter

  • Bloom
  • Chromatic Abberation
  • Scanlines
  • VHS Distortion
  • CRT TV Curve
  • Noise
  • Vignette

Reference : Horri-fi shader effect

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-horrifi/#live-demos","title":"Live demos","text":"
  • Horrifi
"},{"location":"shader-horrifi/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-horrifi/#install-plugin","title":"Install plugin","text":""},{"location":"shader-horrifi/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexhorrifipipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexhorrifipipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexhorrifipipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexhorrifipipelineplugin').add(camera, config);\n
"},{"location":"shader-horrifi/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import HorrifiPipelinePlugin from 'phaser3-rex-plugins/plugins/horrifipipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexHorrifiPipeline',\nplugin: HorrifiPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexHorrifiPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexHorrifiPipeline').add(camera, config);\n
"},{"location":"shader-horrifi/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import HorrifiPostFx from 'phaser3-rex-plugins/plugins/horrifipipeline.js';\nvar config = {\n// ...\npipeline: [HorrifiPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(HorrifiPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(HorrifiPostFx);\n
"},{"location":"shader-horrifi/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 horrifi effect.
    var pipelineInstance = scene.plugins.get('rexHorrifiPipeline').add(gameObject, {\nenable: false,\n\n// Bloom\nbloomEnable: false,\nbloomRadius: 0, bloomIntensity: 0, bloomThreshold: 0,\nbloomTexelWidth: 0, bloomTexelHeight: 0,\n\n// Chromatic abberation\nchromaticEnable: false,\nchabIntensity: 0,\n\n// Vignette\nvignetteEnable: false,\nvignetteStrength: 0, vignetteIntensity: 0,\n\n// Noise\nnoiseEnable: false,\nnoiseStrength: 0,\nnoiseSeed: 0,\n\n// VHS\nvhsEnable: false,\nvhsStrength: 0,\n\n// Scanlines\nscanlinesEnable: false,\nscanStrength: 0,\n\n// CRT\ncrtEnable: false,\ncrtWidth: 0, crtHeight: 0,\n\n// name: 'rexHorrifiPostFx'\n});\n
    • enable : Default enable value for all shader effects.
    • Bloom
      • bloomEnable : Set true to enable bloom effect.
      • bloomRadius, bloomIntensity, bloomThreshold
      • bloomTexelWidth, bloomTexelHeight
    • Chromatic abberation
      • chromaticEnable : Set true to enable chromatic abberation effect.
      • chabIntensity
    • Vignette
      • vignetteEnable : Set true to enable vignette effect.
      • vignetteStrength, vignetteIntensity
    • Noise
      • noiseEnable : Set true to enable noise effect.
      • noiseStrength
      • noiseSeed
    • VHS
      • vhsEnable : Set true to enable VHS effect.
      • vhsStrength
    • Scanlines
      • scanlinesEnable : Set true to enable Scanlines effect.
      • scanStrength
    • CRT
      • crtEnable : Set true to enable Scanlines effect.
      • crtWidth, crtHeight
  • Apply effect to camera. A camera only can add 1 horrifi effect.
    var pipelineInstance = scene.plugins.get('rexHorrifiPipeline').add(camera, config);\n
"},{"location":"shader-horrifi/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexHorrifiPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexHorrifiPipeline').remove(camera);\n
"},{"location":"shader-horrifi/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexHorrifiPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexHorrifiPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexHorrifiPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexHorrifiPipeline').get(camera);\n
"},{"location":"shader-horrifi/#bloom","title":"Bloom","text":""},{"location":"shader-horrifi/#enable","title":"Enable","text":"
  • Enable
    pipelineInstance.setBloomEnable();\n// pipelineInstance.setBloomEnable(true);\n
    or
    pipelineInstance.bloomEnable = true;\n
  • Disable
    pipelineInstance.setBloomEnable(false);\n
    or
    pipelineInstance.bloomEnable = false;\n
  • Get
    var bloomEnable = pipelineInstance.bloomEnable;\n
"},{"location":"shader-horrifi/#parameters","title":"Parameters","text":"
  • Set
    pipelineInstance.setBloomRadius(value);\npipelineInstance.setBloomIntensity(value);\npipelineInstance.setBloomThreshold(value);\npipelineInstance.setBloomTexelSize(width, height);\n
    or
    pipelineInstance.bloomRadius = value;\npipelineInstance.bloomIntensity = value;\npipelineInstance.bloomThreshold = value;\npipelineInstance.bloomTexelWidth = width;\npipelineInstance.bloomTexelHeight = height;\n
  • Get
    var bloomRadius = pipelineInstance.bloomRadius;\nvar bloomIntensity = pipelineInstance.bloomIntensity;\nvar bloomThreshold = pipelineInstance.bloomThreshold;\nvar bloomTexelWidth = pipelineInstance.bloomTexelWidth;\nvar bloomTexelHeight = pipelineInstance.bloomTexelHeight;\n
"},{"location":"shader-horrifi/#chromatic-abberation","title":"Chromatic abberation","text":""},{"location":"shader-horrifi/#enable_1","title":"Enable","text":"
  • Enable
    pipelineInstance.setChromaticEnable();\n// pipelineInstance.setChromaticEnable(true);\n
    or
    pipelineInstance.chromaticEnable = true;\n
  • Disable
    pipelineInstance.setChromaticEnable(false);\n
    or
    pipelineInstance.chromaticEnable = false;\n
  • Get
    var chromaticEnable = pipelineInstance.chromaticEnable;\n
"},{"location":"shader-horrifi/#parameters_1","title":"Parameters","text":"
  • Set
    pipelineInstance.setChabIntensity(value);\n
    or
    pipelineInstance.chabIntensity = value;\n
  • Get
    var chabIntensity = pipelineInstance.chabIntensity;\n
"},{"location":"shader-horrifi/#vignette","title":"Vignette","text":""},{"location":"shader-horrifi/#enable_2","title":"Enable","text":"
  • Enable
    pipelineInstance.setVignetteEnable();\n// pipelineInstance.setVignetteEnable(true);\n
    or
    pipelineInstance.vignetteEnable = true;\n
  • Disable
    pipelineInstance.setVignetteEnable(false);\n
    or
    pipelineInstance.vignetteEnable = false;\n
  • Get
    var vignetteEnable = pipelineInstance.vignetteEnable;\n
"},{"location":"shader-horrifi/#parameters_2","title":"Parameters","text":"
  • Set
    pipelineInstance.setVignetteStrength(value);\npipelineInstance.setVignetteIntensity(value);\n
    or
    pipelineInstance.vignetteStrength = value;\npipelineInstance.vignetteIntensity = value;\n
  • Get
    var vignetteStrength = pipelineInstance.vignetteStrength;\nvar vignetteIntensity = pipelineInstance.vignetteIntensity;\n
"},{"location":"shader-horrifi/#noise","title":"Noise","text":""},{"location":"shader-horrifi/#enable_3","title":"Enable","text":"
  • Enable
    pipelineInstance.setNoiseEnable();\n// pipelineInstance.setNoiseEnable(true);\n
    or
    pipelineInstance.noiseEnable = true;\n
  • Disable
    pipelineInstance.setNoiseEnable(false);\n
    or
    pipelineInstance.noiseEnable = false;\n
  • Get
    var noiseEnable = pipelineInstance.noiseEnable;\n
"},{"location":"shader-horrifi/#parameters_3","title":"Parameters","text":"
  • Set
    pipelineInstance.setNoiseStrength(value);\npipelineInstance.setNoiseSeed(value);\n
    or
    pipelineInstance.noiseStrength = value;\npipelineInstance.noiseSeed = value;\n
  • Get
    var noiseStrength = pipelineInstance.noiseStrength;\nvar noiseSeed = pipelineInstance.noiseSeed;\n
"},{"location":"shader-horrifi/#vhs","title":"VHS","text":""},{"location":"shader-horrifi/#enable_4","title":"Enable","text":"
  • Enable
    pipelineInstance.setVHSEnable();\n// pipelineInstance.setVHSEnable(true);\n
    or
    pipelineInstance.vhsEnable = true;\n
  • Disable
    pipelineInstance.setVHSEnable(false);\n
    or
    pipelineInstance.vhsEnable = false;\n
  • Get
    var vhsEnable = pipelineInstance.vhsEnable;\n
"},{"location":"shader-horrifi/#parameters_4","title":"Parameters","text":"
  • Set
    pipelineInstance.setVhsStrength(value);\n
    or
    pipelineInstance.vhsStrength = value;\n
  • Get
    var vhsStrength = pipelineInstance.vhsStrength;\n
"},{"location":"shader-horrifi/#scanlines","title":"Scanlines","text":""},{"location":"shader-horrifi/#enable_5","title":"Enable","text":"
  • Enable
    pipelineInstance.setScanlinesEnable();\n// pipelineInstance.setScanlinesEnable(true);\n
    or
    pipelineInstance.scanlinesEnable = true;\n
  • Disable
    pipelineInstance.setScanlinesEnable(false);\n
    or
    pipelineInstance.scanlinesEnable = false;\n
  • Get
    var scanlinesEnable = pipelineInstance.scanlinesEnable;\n
"},{"location":"shader-horrifi/#parameters_5","title":"Parameters","text":"
  • Set
    pipelineInstance.setScanStrength(value);\n
    or
    pipelineInstance.scanStrength = value;\n
  • Get
    var scanStrength = pipelineInstance.scanStrength;\n
"},{"location":"shader-horrifi/#crt","title":"CRT","text":""},{"location":"shader-horrifi/#enable_6","title":"Enable","text":"
  • Enable
    pipelineInstance.setCRTEnable();\n// pipelineInstance.setCRTEnable(true);\n
    or
    pipelineInstance.crtEnable = true;\n
  • Disable
    pipelineInstance.setCRTEnable(false);\n
    or
    pipelineInstance.crtEnable = false;\n
  • Get
    var crtEnable = pipelineInstance.crtEnable;\n
"},{"location":"shader-horrifi/#parameters_6","title":"Parameters","text":"
  • Set
    pipelineInstance.setCrtSize(width, height);\n
    or
    pipelineInstance.crtWidth = width;\npipelineInstance.crtHeight = height;\n
  • Get
    var crtWidth = pipelineInstance.crtWidth;\nvar crtHeight = pipelineInstance.crtHeight;\n
"},{"location":"shader-horrifi/#enable-all-effects","title":"Enable all effects","text":"
  • Enable all
    pipelineInstance.setEnable();\n// pipelineInstance.setEnable(true);\n
  • Disable all
    pipelineInstance.setEnable(false);\n
"},{"location":"shader-hsladjust/","title":"HSL adjust","text":"

Note

Phaser3.60 has a built-in Color Matrix effects.

"},{"location":"shader-hsladjust/#introduction","title":"Introduction","text":"

Adjust color in HSL domain, post processing filter.

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-hsladjust/#live-demos","title":"Live demos","text":"
  • HSL adjust
"},{"location":"shader-hsladjust/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-hsladjust/#install-plugin","title":"Install plugin","text":""},{"location":"shader-hsladjust/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexhsladjustpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexhsladjustpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexhsladjustpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexhsladjustpipelineplugin').add(camera, config);\n
"},{"location":"shader-hsladjust/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import HSLAdjustPipelinePlugin from 'phaser3-rex-plugins/plugins/hsladjustpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexHSLAdjustPipeline',\nplugin: HSLAdjustPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexHSLAdjustPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexHSLAdjustPipeline').add(camera, config);\n
"},{"location":"shader-hsladjust/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import HSLAdjustPostFx from 'phaser3-rex-plugins/plugins/hsladjustpipeline.js';\nvar config = {\n// ...\npipeline: [HSLAdjustPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(HSLAdjustPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(HSLAdjustPostFx);\n
"},{"location":"shader-hsladjust/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 hsl-adjust effect.
    var pipelineInstance = scene.plugins.get('rexHslAdjustPipeline').add(gameObject, {\n// hueRotate: 0,\n// satAdjust: 1,\n// lumAdjust: 0.5,\n\n// name: 'rexHslAdjustPostFx'\n});\n
    • hueRotate : Hue rotation
      • 0 : Rotate 0 degrees, original color (Default value)
      • 0.5 : Rotate 180 degrees
      • 1 : Rotate 360 degrees
    • satAdjust : Saturation adjustment
      • 0 : Gray
      • 1 : Original color (Default value)
      • 1 :

    • lumAdjust : Lumen adjustment
      • 0 : Dark
      • 0.5 : Original color (Default value)
      • 1 : White
  • Apply effect to camera. A camera only can add 1 hsl-adjust effect.
    var pipelineInstance = scene.plugins.get('rexHslAdjustPipeline').add(camera, config);\n
"},{"location":"shader-hsladjust/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexHslAdjustPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexHslAdjustPipeline').remove(camera);\n
"},{"location":"shader-hsladjust/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexHslAdjustPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexHslAdjustPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexHslAdjustPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexHslAdjustPipeline').get(camera);\n
"},{"location":"shader-hsladjust/#hue-rotation","title":"Hue rotation","text":"
  • Get
    var hueRotate = pipelineInstance.hueRotate;\n
  • Set
    pipelineInstance.hueRotate = hueRotate;\n// pipelineInstance.hueRotate += value;\n
    or
    pipelineInstance.setHueRotate(value);\n
    • 0 : Rotate 0 degrees, original color
    • 0.5 : Rotate 180 degrees
    • 1 : Rotate 360 degrees
"},{"location":"shader-hsladjust/#saturation-adjustment","title":"Saturation adjustment","text":"
  • Get
    var satAdjust = pipelineInstance.satAdjust;\n
  • Set
    pipelineInstance.satAdjust = satAdjust;\n// pipelineInstance.satAdjust += value;\n
    or
    pipelineInstance.setSatAdjust(value);\n
    • 0 : Gray
    • 1 : Original color
    • 1 :

"},{"location":"shader-hsladjust/#lumen-adjustment","title":"Lumen adjustment","text":"
  • Get
    var lumAdjust = pipelineInstance.lumAdjust;\n
  • Set
    pipelineInstance.lumAdjust = lumAdjust;\n// pipelineInstance.lumAdjust += value;\n
    or
    pipelineInstance.setLumAdjust(value);\n
    • 0 : Dark
    • 0.5 : Original color
    • 1 : White
"},{"location":"shader-inverse/","title":"Inverse","text":"

Note

Phaser3.60 has a built-in Color Matrix effects.

"},{"location":"shader-inverse/#introduction","title":"Introduction","text":"

Inverse color post processing filter.

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-inverse/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-inverse/#install-plugin","title":"Install plugin","text":""},{"location":"shader-inverse/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexinversepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexinversepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexinversepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexinversepipelineplugin').add(camera, config);\n
"},{"location":"shader-inverse/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import InversePipelinePlugin from 'phaser3-rex-plugins/plugins/inversepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexInversePipeline',\nplugin: InversePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexInversePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexInversePipeline').add(camera, config);\n
"},{"location":"shader-inverse/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import InversePostFx from 'phaser3-rex-plugins/plugins/inversepipeline.js';\nvar config = {\n// ...\npipeline: [InversePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(InversePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(InversePostFx);\n
"},{"location":"shader-inverse/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 inverse effect.
    var pipelineInstance = scene.plugins.get('rexInversePipeline').add(gameObject, {\n// intensity: 1,\n\n// name: 'rexInversePostFx'\n});\n
    • intensity : 0(original color) ~ 1(inverse scale). Default value is 1.
  • Apply effect to camera. A camera only can add 1 inverse effect.
    var pipelineInstance = scene.plugins.get('rexInversePipeline').add(camera, config);\n
"},{"location":"shader-inverse/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexInversePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexInversePipeline').remove(camera);\n
"},{"location":"shader-inverse/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexInversePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexInversePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexInversePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexInversePipeline').get(camera);\n
"},{"location":"shader-inverse/#intensity","title":"Intensity","text":"
  • Get
    var intensity = pipelineInstance.intensity;\n
  • Set
    pipelineInstance.intensity = intensity;\n// pipelineInstance.intensity += value;\n
    or
    pipelineInstance.setIntensity(radius);\n
    • intensity : 0(original color) ~ 1(inverse color)
"},{"location":"shader-kawaseblur/","title":"Kawase blur","text":"

Note

Phaser3.60 has a built-in blur effect.

"},{"location":"shader-kawaseblur/#introduction","title":"Introduction","text":"

Kawase-blur post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-kawaseblur/#live-demos","title":"Live demos","text":"
  • Kawase-blur
"},{"location":"shader-kawaseblur/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-kawaseblur/#install-plugin","title":"Install plugin","text":""},{"location":"shader-kawaseblur/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexkawaseblurpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexkawaseblurpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexkawaseblurpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexkawaseblurpipelineplugin').add(camera, config);\n
"},{"location":"shader-kawaseblur/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import KawaseBlurPipelinePlugin from 'phaser3-rex-plugins/plugins/kawaseblurpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexKawaseBlurPipeline',\nplugin: KawaseBlurPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexKawaseBlurPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexKawaseBlurPipeline').add(camera, config);\n
"},{"location":"shader-kawaseblur/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import KawaseBlurPostFx from 'phaser3-rex-plugins/plugins/kawaseblurpipeline.js';\nvar config = {\n// ...\npipeline: [KawaseBlurPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(KawaseBlurPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(KawaseBlurPostFx);\n
"},{"location":"shader-kawaseblur/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 kawaseblur effect.
    var pipelineInstance = scene.plugins.get('rexKawaseBlurPipeline').add(gameObject, {\n// blur: 4,\n// quality: 3,\n// pixelWidth: 1,\n// pixelHeight: 1,\n\n// name: 'rexKawaseBlurPostFx'\n});\n
    • blur : The blur of the filter. Should be greater than 0. If value is an Array, setting kernels.
    • quality : The quality of the filter. Should be an integer greater than 1.
    • pixelWidth, pixelHeight : Sets the pixel size of the filter. Large size is blurrier. For advanced usage.
  • Apply effect to camera. A camera only can add 1 kawaseblur effect.
    var pipelineInstance = scene.plugins.get('rexKawaseBlurPipeline').add(camera, config);\n
"},{"location":"shader-kawaseblur/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexKawaseBlurPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexKawaseBlurPipeline').remove(camera);\n
"},{"location":"shader-kawaseblur/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexKawaseBlurPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexKawaseBlurPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexKawaseBlurPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexKawaseBlurPipeline').get(camera);\n
"},{"location":"shader-kawaseblur/#blur","title":"Blur","text":"
  • Get
    var blur = pipelineInstance.blur;\n
  • Set
    pipelineInstance.blur = blur;\n// pipelineInstance.blur += value;\n
    or
    pipelineInstance.setBlur(value);\n
"},{"location":"shader-kawaseblur/#quality","title":"Quality","text":"
  • Get
    var quality = pipelineInstance.quality;\n
  • Set
    pipelineInstance.quality = quality;\n// pipelineInstance.quality += value;\n
    or
    pipelineInstance.setQuality(value);\n
"},{"location":"shader-kawaseblur/#pixel-size","title":"Pixel size","text":"
  • Get
    var pixelWidth = pipelineInstance.pixelWidth;\nvar pixelHeight = pipelineInstance.pixelHeight;\n
  • Set
    pipelineInstance.pixelWidth = pixelWidth;\npipelineInstance.pixelHeight = pixelHeight;\n
    or
    pipelineInstance.setPixelWidth(pixelWidth);\npipelineInstance.setPixelHeight(pixelHeight);\npipelineInstance.setPixelSize(pixelWidth, pixelHeight);\n
"},{"location":"shader-outline/","title":"Outline","text":""},{"location":"shader-outline/#introduction","title":"Introduction","text":"

Outline post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-outline/#live-demos","title":"Live demos","text":"
  • Outline
"},{"location":"shader-outline/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-outline/#install-plugin","title":"Install plugin","text":""},{"location":"shader-outline/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexoutlinepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexoutlinepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexoutlinepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexoutlinepipelineplugin').add(camera, config);\n
"},{"location":"shader-outline/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import OutlinePipelinePlugin from 'phaser3-rex-plugins/plugins/outlinepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexOutlinePipeline',\nplugin: OutlinePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexOutlinePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexOutlinePipeline').add(camera, config);\n
"},{"location":"shader-outline/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import OutlinePostFx from 'phaser3-rex-plugins/plugins/outlinepipeline.js';\nvar config = {\n// ...\npipeline: [OutlinePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(OutlinePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(OutlinePostFx);\n
"},{"location":"shader-outline/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 outline effect.
    var pipelineInstance = scene.plugins.get('rexOutlinePipeline').add(gameObject, {\n// thickness: 3,\n// outlineColor: 0x000000,\n\n// quality: 0.1,\n\n// name: 'rexOutlinePostFx'\n});\n
    • thickness : Thickness of outline.
    • outlineColor : Color of outline.
    • quality : 0~1. The higher the number the less performant. It can't be changed after filter creation.
  • Apply effect to camera. A camera only can add 1 outline effect.
    var pipelineInstance = scene.plugins.get('rexOutlinePipeline').add(camera, config);\n
"},{"location":"shader-outline/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexOutlinePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexOutlinePipeline').remove(camera);\n
"},{"location":"shader-outline/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexOutlinePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexOutlinePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexOutlinePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexOutlinePipeline').get(camera);\n
"},{"location":"shader-outline/#thickness","title":"Thickness","text":"
  • Get
    var thickness = pipelineInstance.thickness;\n
  • Set
    pipelineInstance.thickness = thickness;\n// pipelineInstance.thickness += value;\n
    or
    pipelineInstance.setThickness(value);\n
"},{"location":"shader-outline/#outline-color","title":"Outline color","text":"
  • Get
    var color = pipelineInstance.outlineColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    pipelineInstance.setOutlineColor(value);\n
    pipelineInstance.outlineColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"shader-outline/#quality","title":"Quality","text":"

The quality of the outline from 0 to 1, using a higher quality setting will result in slower performance and more accuracy.

  • Get
    var quality = pipelineInstance.quality;\n
  • Set
    pipelineInstance.setQuality(quality);\n
    or
    pipelineInstance.quality = quality;\n
    • quality : 0 ~ 1, default is 0.1.
      • 0.1 : 10 sample points.
      • 0.08 : 8 sample points.
      • 1 : 100 sample points.
"},{"location":"shader-pixelation/","title":"Pixelation","text":"

Note

Phaser3.60 has a built-in pixelate effect.

"},{"location":"shader-pixelation/#introduction","title":"Introduction","text":"

Pixelation post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-pixelation/#live-demos","title":"Live demos","text":"
  • Pixelation
"},{"location":"shader-pixelation/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-pixelation/#install-plugin","title":"Install plugin","text":""},{"location":"shader-pixelation/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexpixelationpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexpixelationpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexpixelationpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexpixelationpipelineplugin').add(camera, config);\n
"},{"location":"shader-pixelation/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import PixelationPipelinePlugin from 'phaser3-rex-plugins/plugins/pixelationpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexPixelationPipeline',\nplugin: PixelationPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexPixelationPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexPixelationPipeline').add(camera, config);\n
"},{"location":"shader-pixelation/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import PixelationPostFx from 'phaser3-rex-plugins/plugins/pixelationpipeline.js';\nvar config = {\n// ...\npipeline: [PixelationPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(PixelationPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(PixelationPostFx);\n
"},{"location":"shader-pixelation/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 pixelation effect.
    var pipelineInstance = scene.plugins.get('rexPixelationPipeline').add(gameObject, {\n// pixelWidth: 0,\n// pixelHeight: 0,\n\n// name: 'rexPixelationPostFx'\n});\n
    • pixelWidth, pixelHeight : Pixel size.
  • Apply effect to camera. A camera only can add 1 pixelation effect.
    var pipelineInstance = scene.plugins.get('rexPixelationPipeline').add(camera, config);\n
"},{"location":"shader-pixelation/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexPixelationPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexPixelationPipeline').remove(camera);\n
"},{"location":"shader-pixelation/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexPixelationPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexPixelationPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexPixelationPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexPixelationPipeline').get(camera);\n
"},{"location":"shader-pixelation/#pixel-size","title":"Pixel size","text":"
  • Get
    var pixelWidth = pipelineInstance.pixelWidth;\nvar pixelHeight = pipelineInstance.pixelHeight;\n
  • Set
    pipelineInstance.pixelWidth = pixelWidth;\npipelineInstance.pixelHeight = pixelHeight;\n// pipelineInstance.pixelWidth += value;\n// pipelineInstance.pixelHeight += value;\n
    or
    pipelineInstance.setPixelWidth(pixelWidth);\npipelineInstance.setPixelHeight(pixelHeight);\npipelineInstance.setPixelSize(pixelWidth, pixelHeight);\n
"},{"location":"shader-shockwave/","title":"Shockwave","text":""},{"location":"shader-shockwave/#introduction","title":"Introduction","text":"

Shockwave post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-shockwave/#live-demos","title":"Live demos","text":"
  • Shockwave
"},{"location":"shader-shockwave/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-shockwave/#install-plugin","title":"Install plugin","text":""},{"location":"shader-shockwave/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexshockwavepipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexshockwavepipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexshockwavepipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexshockwavepipelineplugin').add(camera, config);\n
"},{"location":"shader-shockwave/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ShockwavePipelinePlugin from 'phaser3-rex-plugins/plugins/shockwavepipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexShockwavePipeline',\nplugin: ShockwavePipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexShockwavePipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexShockwavePipeline').add(camera, config);\n
"},{"location":"shader-shockwave/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import ShockwavePostFx from 'phaser3-rex-plugins/plugins/shockwavepipeline.js';\nvar config = {\n// ...\npipeline: [ShockwavePostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(ShockwavePostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(ShockwavePostFx);\n
"},{"location":"shader-shockwave/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 shockwave effect.
    var pipelineInstance = scene.plugins.get('rexShockwavePipeline').add(gameObject, {\n// center: {\n//    x: windowWidth / 2,\n//    y: windowHeight / 2\n//}\n// waveRadius: 0,\n// waveWidth: 20,\n// powBaseScale: 0.8,\n// powExponent: 0.1,\n\n// name: 'rexShockwavePostFx'\n});\n
    • waveRadius : Radius of shockwave, in pixels.
    • waveWidth : Width of shockwave, in pixels.
    • powBaseScale, powExponent : Parameters of shockwave.
  • Apply effect to camera. A camera only can add 1 shockwave effect.
    var pipelineInstance = scene.plugins.get('rexShockwavePipeline').add(camera, config);\n
"},{"location":"shader-shockwave/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexShockwavePipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexShockwavePipeline').remove(camera);\n
"},{"location":"shader-shockwave/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexShockwavePipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexShockwavePipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexShockwavePipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexShockwavePipeline').get(camera);\n
"},{"location":"shader-shockwave/#wave-radius","title":"Wave radius","text":"
  • Get
    var waveRadius = pipelineInstance.waveRadius;\n
  • Set
    pipelineInstance.waveRadius = waveRadius;\n
    or
    pipelineInstance.setWaveRadius(waveRadius);\n
"},{"location":"shader-shockwave/#wave-width","title":"Wave width","text":"
  • Get
    var waveWidth = pipelineInstance.waveWidth;\n
  • Set
    pipelineInstance.waveWidth = waveWidth;\n
    or
    pipelineInstance.setWaveWidth(waveWidth);\n
"},{"location":"shader-split/","title":"Split","text":""},{"location":"shader-split/#introduction","title":"Introduction","text":"

Split image into 4 parts.

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-split/#live-demos","title":"Live demos","text":"
  • Split
"},{"location":"shader-split/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-split/#install-plugin","title":"Install plugin","text":""},{"location":"shader-split/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexsplitpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexsplitpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexsplitpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexsplitpipelineplugin').add(camera, config);\n
"},{"location":"shader-split/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SplitPipelinePlugin from 'phaser3-rex-plugins/plugins/splitpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexSplitPipeline',\nplugin: SplitPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexSplitPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexSplitPipeline').add(camera, config);\n
"},{"location":"shader-split/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import SplitPostFx from 'phaser3-rex-plugins/plugins/splitpipeline.js';\nvar config = {\n// ...\npipeline: [SplitPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(SplitPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(SplitPostFx);\n
"},{"location":"shader-split/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 split effect.
    var pipelineInstance = scene.plugins.get('rexSplitPipeline').add(gameObject, {\n// x: undefined,  // renderer.width / 2\n// y: undefined,  // renderer.height / 2\n\n// width: undefined,\n// left: 0,\n// right: 0,\n// height: undefined,\n// top: 0,\n// bottom: 0,\n\n// angle: undefined,  // Degrees\n// rotation: 0,       // Radian\n\n// shiftEnable: true,\n\n// name: 'rexSplitPostFx'\n});\n
    • x : Vertical split position. Default value is center of render width.
    • y : Horizontal split position. Default value is center of render height.
    • width, height : Vertical/Horizontal split length.
    • left, right : Specify left/right part length of vertical split. Default value is half Vertical split length.
    • top, bottom : Specify top/bottom part length of horizontal split. Default value is half Horizontal split length.
    • angle, rotation : Rotation of split axis. Default value is 0.
    • shiftEnable :
      • true : Shift splitted parts out. Default value.
      • false : Don't shift splitted parts. Equal to apply mask on this image.
  • Apply effect to camera. A camera only can add 1 split effect.
    var pipelineInstance = scene.plugins.get('rexSplitPipeline').add(camera, config);\n
"},{"location":"shader-split/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexSplitPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexSplitPipeline').remove(camera);\n
"},{"location":"shader-split/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexSplitPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexSplitPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexSplitPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexSplitPipeline').get(camera);\n
"},{"location":"shader-split/#split-position","title":"Split position","text":"
  • Get
    var splitX = pipelineInstance.splitX;\nvar splitY = pipelineInstance.splitY;\n
  • Set
    pipelineInstance.splitX = splitX;\npipelineInstance.splitY = splitY;\n
    or
    pipelineInstance.setSplit(x, y);\n
"},{"location":"shader-split/#split-at-center-of-render","title":"Split at center of render","text":"
pipelineInstance.splitAtCenter();\n// pipelineInstance.splitAtCenter(width, height);\n
"},{"location":"shader-split/#split-length","title":"Split length","text":"
  • Get
    var splittedWidth = pipelineInstance.splittedWidth;\nvar splittedHeight = pipelineInstance.splittedHeight;\n
  • Set
    pipelineInstance.splittedWidth = splittedWidth;\npipelineInstance.splittedHeight = splittedHeight;\n
    or
    pipelineInstance.setSplittedWidth(splittedWidth);\npipelineInstance.setSplittedHeight(splittedHeight);\n

or specify left/right/top/bottom of split length

  • Get
    var left = pipelineInstance.spaceLeft;\nvar right = pipelineInstance.spaceRight;\nvar top = pipelineInstance.spaceTop;\nvar bottom = pipelineInstance.spaceBottom;\n
  • Set
    pipelineInstance.spaceLeft = left;\npipelineInstance.spaceRight = right;\npipelineInstance.spaceTop = top;\npipelineInstance.spaceBottom = bottom;\n
    or
    pipelineInstance.setSpace(left, right, top, bottom);\n
"},{"location":"shader-split/#rotation-axis-of-split-edge","title":"Rotation Axis of Split edge","text":"
  • Get
    var rotation = pipelineInstance.rotation;  // radians\n// var angle = pipelineInstance.angle;     // degrees\n
  • Set
    pipelineInstance.rotation = rotation;\npipelineInstance.rotation += value;\n// pipelineInstance.angle = angle;\n// pipelineInstance.angle += value;\n
    or
    pipelineInstance.setRotation(rotation);\n// pipelineInstance.setAngle(angle);\n
"},{"location":"shader-split/#shift-enable","title":"Shift enable","text":"
  • Get
    var enable = pipelineInstance.shiftEnable;\n
  • Set
    pipelineInstance.shiftEnable = enable;\n
    or
    pipelineInstance.setShiftEnable(enable);\n
"},{"location":"shader-swirl/","title":"Swirl","text":""},{"location":"shader-swirl/#introduction","title":"Introduction","text":"

Swirl post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-swirl/#live-demos","title":"Live demos","text":"
  • Swirl
"},{"location":"shader-swirl/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-swirl/#install-plugin","title":"Install plugin","text":""},{"location":"shader-swirl/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexswirlpipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexswirlpipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexswirlpipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexswirlpipelineplugin').add(camera, config);\n
"},{"location":"shader-swirl/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SwirlPipelinePlugin from 'phaser3-rex-plugins/plugins/swirlpipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexSwirlPipeline',\nplugin: SwirlPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexSwirlPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexSwirlPipeline').add(camera, config);\n
"},{"location":"shader-swirl/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import SwirlPostFx from 'phaser3-rex-plugins/plugins/swirlpipeline.js';\nvar config = {\n// ...\npipeline: [SwirlPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(SwirlPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(SwirlPostFx);\n
"},{"location":"shader-swirl/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 swirl effect.
    var pipelineInstance = scene.plugins.get('rexSwirlPipeline').add(gameObject, {\n// center: {\n//    x: windowWidth / 2,\n//    y: windowHeight / 2\n//}\n// radius: 0,\n// rotation: 0,  // or angle: 0,\n\n// name: 'rexSwirlPostFx'\n});\n
    • center.x, center.y : Local position of swirl center.
    • radius : Swirl radius.
    • rotation (angle) : Swirl angle.
  • Apply effect to camera. A camera only can add 1 swirl effect.
    var pipelineInstance = scene.plugins.get('rexSwirlPipeline').add(camera, config);\n
"},{"location":"shader-swirl/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexSwirlPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexSwirlPipeline').remove(camera);\n
"},{"location":"shader-swirl/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexSwirlPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexSwirlPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexSwirlPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexSwirlPipeline').get(camera);\n
"},{"location":"shader-swirl/#radius","title":"Radius","text":"
  • Get
    var radius = pipelineInstance.radius;\n
  • Set
    pipelineInstance.radius = radius;\n// pipelineInstance.radius += value;\n
    or
    pipelineInstance.setRadius(radius);\n
"},{"location":"shader-swirl/#rotation","title":"Rotation","text":"
  • Get
    var rotation = pipelineInstance.rotation;  // radians\n// var angle = pipelineInstance.angle;     // degrees\n
  • Set
    pipelineInstance.rotation = rotation;\npipelineInstance.rotation += value;\n// pipelineInstance.angle = angle;\n// pipelineInstance.angle += value;\n
    or
    pipelineInstance.setRotation(rotation);\n// pipelineInstance.setAngle(angle);\n
"},{"location":"shader-swirl/#center-position","title":"Center position","text":"

Default value is center of window.

  • Get
    var x = pipelineInstance.centerX;\nvar y = pipelineInstance.centerY;\n
  • Set
    pipelineInstance.centerX = x;\npipelineInstance.centerY = y;\n
    or
    pipelineInstance.setCenter(x, y);\n// pipelineInstance.setCenter();   // set to center of window\n
"},{"location":"shader-toonify/","title":"Toonify","text":""},{"location":"shader-toonify/#introduction","title":"Introduction","text":"

Draw outlines and quantize color in HSV domain, post processing filter. Reference

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-toonify/#live-demos","title":"Live demos","text":"
  • Toonify
"},{"location":"shader-toonify/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-toonify/#install-plugin","title":"Install plugin","text":""},{"location":"shader-toonify/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextoonifypipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextoonifypipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rextoonifypipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rextoonifypipelineplugin').add(camera, config);\n
"},{"location":"shader-toonify/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ToonifyPipelinePlugin from 'phaser3-rex-plugins/plugins/toonifypipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexToonifyPipeline',\nplugin: ToonifyPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexToonifyPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexToonifyPipeline').add(camera, config);\n
"},{"location":"shader-toonify/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import ToonifyPostFx from 'phaser3-rex-plugins/plugins/toonifypipeline.js';\nvar config = {\n// ...\npipeline: [ToonifyPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(ToonifyPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(ToonifyPostFx);\n
"},{"location":"shader-toonify/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 toonify effect.
    var pipelineInstance = scene.plugins.get('rexToonifyPipeline').add(gameObject, {\n// edgeThreshold: 0.2,\n// hueLevels: 0,\n// sLevels: 0,\n// vLevels: 0,\n// edgeColor: 0,\n\n// name: 'rexToonifyPostFx'\n});\n
    • edgeThreshold : Threshold of edge. Set 1.1 (or any number larger then 1) to disable this feature.
    • hueLevels : Amount of hue levels. Set 0 to disable this feature.
    • sLevels : Amount of saturation levels. Set 0 to disable this feature.
    • vLevels : Amount of value levels. Set 0 to disable this feature.
    • edgeColor : Color of edge, could be a number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
  • Apply effect to camera. A camera only can add 1 toonify effect.
    var pipelineInstance = scene.plugins.get('rexToonifyPipeline').add(camera, config);\n
"},{"location":"shader-toonify/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexToonifyPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexToonifyPipeline').remove(camera);\n
"},{"location":"shader-toonify/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexToonifyPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexToonifyPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexToonifyPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexToonifyPipeline').get(camera);\n
"},{"location":"shader-toonify/#edge-threshold","title":"Edge threshold","text":"
  • Get
    var edgeThreshold = pipelineInstance.edgeThreshold;\n
  • Set
    pipelineInstance.edgeThreshold = edgeThreshold;\n
    or
    pipelineInstance.setEdgeThreshold(value);\n
    • Set 1.1 (or any number larger then 1) to disable this feature.
"},{"location":"shader-toonify/#hue-levels","title":"Hue levels","text":"
  • Get
    var hueLevels = pipelineInstance.hueLevels;\n
  • Set
    pipelineInstance.hueLevels = hueLevels;\n
    or
    pipelineInstance.setHueLevels(value);\n
    • Set 0 to disable this feature.
"},{"location":"shader-toonify/#saturation-levels","title":"Saturation levels","text":"
  • Get
    var satLevels = pipelineInstance.satLevels;\n
  • Set
    pipelineInstance.satLevels = satLevels;\n
    or
    pipelineInstance.setSatLevels(value);\n
    • Set 0 to disable this feature.
"},{"location":"shader-toonify/#value-levels","title":"Value levels","text":"
  • Get
    var valLevels = pipelineInstance.valLevels;\n
  • Set
    pipelineInstance.valLevels = valLevels;\n
    or
    pipelineInstance.setValLevels(value);\n
    • Set 0 to disable this feature.
"},{"location":"shader-toonify/#edge-color","title":"Edge color","text":"
  • Get
    var color = pipelineInstance.edgeColor;\n
    • color : Color object.
      • Red: color.red, 0~255.
      • Green: color.green, 0~255.
      • Blue: color.blue, 0~255.
  • Set
    pipelineInstance.setEdgeColor(value);\n
    or
    pipelineInstance.edgeColor = value;\n
    • value : A number 0xRRGGBB, or a JSON object {r:255, g:255, b:255}
"},{"location":"shader-warp-transition/","title":"Warp","text":""},{"location":"shader-warp-transition/#introduction","title":"Introduction","text":"

Warp transition post processing filter.

  • Author: Richard Davey
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-warp-transition/#usage","title":"Usage","text":"

Reference

"},{"location":"shader-warp-transition/#install-plugin","title":"Install plugin","text":""},{"location":"shader-warp-transition/#import-class","title":"Import class","text":"
  • Get minify file from github
  • Add to game config
    import { WarpPostFX } from './dist/WarpPostFX.js';  // Path to your minify file\nvar config = {\n// ...\npipeline: { WarpPostFX }\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(WarpPostFX);\n
    • Apply effect to camera
      camera.setPostPipeline(WarpPostFX);\n
"},{"location":"shader-warp-transition/#remove-effect","title":"Remove effect","text":"
gameObject.removePostPipeline(WarpPostFX); // WarpPostFX class\n
"},{"location":"shader-warp-transition/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = gameObject.getPostPipeline(WarpPostFX); // WarpPostFX class\n
  • Get effect from camera
    var pipelineInstance = camera.getPostPipeline(WarpPostFX); // WarpPostFX class\n
"},{"location":"shader-warp-transition/#set-texture","title":"Set texture","text":"
pipelineInstance.setTexture(textureKey, resizeMode);\n
  • textureKey : The key of the texture to use.
  • resizeMode :
    • 0, or 'stretch' : The target texture is stretched to the size of the source texture.
    • 1, or 'contain' : The target texture is resized to fit the source texture.
    • 2, or 'cover' : The target texture is resized to cover the source texture.
"},{"location":"shader-warp-transition/#progress","title":"Progress","text":"
  • Get
    var progress = pipelineInstance.progress;\n
  • Set
    pipelineInstance.setProgress(value);  // value: 0~1\n
    or
    pipelineInstance.progress = value;  // value: 0~1\n
"},{"location":"shader-warp-transition/#direction","title":"Direction","text":"
  • Get
    var direction = pipelineInstance.direction;  // {x, y}\n
    • Default value is {x:-1, y:1}
  • Set
    pipelineInstance.setDirection(x, y);  // x, y : 1, or -1\n
"},{"location":"shader-warp-transition/#smoothness","title":"Smoothness","text":"
  • Get
    var smoothness = pipelineInstance.smoothness;\n
  • Set
    pipelineInstance.setSmoothness(value);  // value: 0~1\n
    or
    pipelineInstance.smoothness = value;  // value: 0~1\n
"},{"location":"shader-warp-transition/#resize-mode","title":"Resize mode","text":"
  • Get
    var mode = pipelineInstance.resizeMode;\n
  • Set
    pipelineInstance.setResizeMode(mode);\n
    • mode :
      • 0, or 'stretch' : The target texture is stretched to the size of the source texture.
      • 1, or 'contain' : The target texture is resized to fit the source texture.
      • 2, or 'cover' : The target texture is resized to cover the source texture.
"},{"location":"shader-warp/","title":"Warp","text":""},{"location":"shader-warp/#introduction","title":"Introduction","text":"

Warp post processing filter.

  • Author: Rex
  • A post-fx shader effect

WebGL only

Only work in WebGL render mode.

"},{"location":"shader-warp/#live-demos","title":"Live demos","text":"
  • Warp
"},{"location":"shader-warp/#usage","title":"Usage","text":"

Sample code

"},{"location":"shader-warp/#install-plugin","title":"Install plugin","text":""},{"location":"shader-warp/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexwarppipelineplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexwarppipelineplugin.min.js', true);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexwarppipelineplugin').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexwarppipelineplugin').add(camera, config);\n
"},{"location":"shader-warp/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import WarpPipelinePlugin from 'phaser3-rex-plugins/plugins/warppipeline-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexWarpPipeline',\nplugin: WarpPipelinePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      var pipelineInstance = scene.plugins.get('rexWarpPipeline').add(gameObject, config);\n
    • Apply effect to camera
      var pipelineInstance = scene.plugins.get('rexWarpPipeline').add(camera, config);\n
"},{"location":"shader-warp/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Add to game config
    import WarpPostFx from 'phaser3-rex-plugins/plugins/warppipeline.js';\nvar config = {\n// ...\npipeline: [WarpPostFx]\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Apply effect
    • Apply effect to game object
      gameObject.setPostPipeline(WarpPostFx);\n
    • Apply effect to camera
      camera.setPostPipeline(WarpPostFx);\n
"},{"location":"shader-warp/#apply-effect","title":"Apply effect","text":"
  • Apply effect to game object. A game object only can add 1 warp effect.

    var pipelineInstance = scene.plugins.get('rexWarpPipeline').add(gameObject, {\n// frequencyX: 10,\n// frequencyY: 10,\n\n// amplitudeX: 10,\n// amplitudeY: 10,\n\n// speedX: 0,\n// speedY: 0,\n// speedEnable: \n\n// name: 'rexWarpPostFx'\n});\n

    • frequencyX, frequencyY : Horizontal/vertical frequency, in pixel.
    • amplitudeX, amplitudeY : Horizontal/vertical amplitude, in pixel.
    • speedX, speedY : Horizontal/vertical speed.
    • speedEnable
      • true : Enable speed. Default value if speedX or speedY is not 0.
      • false : Disable speed. Default value if speedX and speedY are both 0.
  • Apply effect to camera. A camera only can add 1 warp effect.

    var pipelineInstance = scene.plugins.get('rexWarpPipeline').add(camera, config);\n

"},{"location":"shader-warp/#remove-effect","title":"Remove effect","text":"
  • Remove effect from game object
    scene.plugins.get('rexWarpPipeline').remove(gameObject);\n
  • Remove effect from camera
    scene.plugins.get('rexWarpPipeline').remove(camera);\n
"},{"location":"shader-warp/#get-effect","title":"Get effect","text":"
  • Get effect from game object
    var pipelineInstance = scene.plugins.get('rexWarpPipeline').get(gameObject)[0];\n// var pipelineInstances = scene.plugins.get('rexWarpPipeline').get(gameObject);\n
  • Get effect from camera
    var pipelineInstance = scene.plugins.get('rexWarpPipeline').get(camera)[0];\n// var pipelineInstances = scene.plugins.get('rexWarpPipeline').get(camera);\n
"},{"location":"shader-warp/#frequency","title":"Frequency","text":"

Horizontal/vertical frequency, in pixel.

  • Get
    var frequencyX = pipelineInstance.frequencyX;\nvar frequencyY = pipelineInstance.frequencyY;\n
  • Set
    pipelineInstance.frequencyX = frequencyX;\npipelineInstance.frequencyY = frequencyY;\n// pipelineInstance.frequencyX += value;\n// pipelineInstance.frequencyY += value;\n
    or
    pipelineInstance.setFrequencyX(frequencyX);\npipelineInstance.setFrequencyY(frequencyY);\npipelineInstance.setFrequency(frequencyX, frequencyY);\n
"},{"location":"shader-warp/#amplitude","title":"Amplitude","text":"

Horizontal/vertical amplitude, in pixel.

  • Get
    var amplitudeX = pipelineInstance.amplitudeX;\nvar amplitudeY = pipelineInstance.amplitudeY;\n
  • Set
    pipelineInstance.amplitudeX = amplitudeX;\npipelineInstance.amplitudeY = amplitudeY;\n// pipelineInstance.amplitudeX += value;\n// pipelineInstance.amplitudeY += value;\n
    or
    pipelineInstance.setAmplitudeX(amplitudeX);\npipelineInstance.setAmplitudeY(amplitudeY);\npipelineInstance.setAmplitude(amplitudeX, amplitudeY);\n
"},{"location":"shader-warp/#speed","title":"Speed","text":"

Horizontal/vertical speed.

  • Eanble/resume
    pipelineInstance.setSpeedEnable();\n
  • Pause
    pipelineInstance.setSpeedEnable(false);\n
  • Get
    var speedX = pipelineInstance.speedX;\nvar speedY = pipelineInstance.speedY;\n
  • Set
    pipelineInstance.speedX = speedX;\npipelineInstance.speedY = speedY;\n// pipelineInstance.speedX += value;\n// pipelineInstance.speedY += value;\n
    or
    pipelineInstance.setSpeedX(speedX);\npipelineInstance.setSpeedY(speedY);\npipelineInstance.setSpeed(speedX, speedY);\n
"},{"location":"shader/","title":"Shader","text":""},{"location":"shader/#introduction","title":"Introduction","text":"

A quad with its own shader, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shader/#usage","title":"Usage","text":""},{"location":"shader/#load-glsl","title":"Load GLSL","text":"
scene.load.glsl(key, url);\n

Reference: load glsl

"},{"location":"shader/#add-shader-object","title":"Add shader object","text":"
var shader = scene.add.shader(key, x, y, width, height, textures);\n
  • key : The key of the shader to use from the shader cache, or a BaseShader instance.
  • x, y : Position.
  • width, height : Size.
  • textures : Optional array of texture keys to bind to the iChannel0, iChannel1, iChannel2, iChannel3 uniforms.

Note

Lots of shaders expect textures to be power-of-two sized.

Add shader object from JSON

var shader = scene.make.shader({\nx: 0,\ny: 0,\nkey: '',\n\n// angle: 0,\n// alpha: 1\n// flipX: true,\n// flipY: true,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
  • key : The key of the shader to use from the shader cache, or a BaseShader instance.
    • A string
    • An array of string to pick one element at random
  • x, y, scale.x, scale.y :
    • A number
    • A callback to get return value
      function() { return 0; }\n
    • Random integer between min and max
      { randInt: [min, max] }\n
    • Random float between min and max
      { randFloat: [min, max] }\n
"},{"location":"shader/#custom-class","title":"Custom class","text":"
  • Define class
    class MyShader extends Phaser.GameObjects.Shader {\nconstructor(scene, key, x, y, width, height, textures) {\nsuper(scene, key, x, y, width, height, textures);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var shader = new MyShader(scene, key, x, y, width, height, textures);\n
"},{"location":"shader/#sampler2d-uniform","title":"Sampler2D uniform","text":"
  • Default uniform mappings :
    • resolution (2f) - Set to the size of this shader.
      • uniform vec2 resolution; in GLSL.
    • time (1f) - The elapsed game time, in seconds.
      • uniform float time; in GLSL.
    • mouse (2f) - If a pointer has been bound (with setPointer), this uniform contains its position each frame.
      • uniform vec2 mouse; in GLSL.
    • date (4fv) - A vec4 containing the year, month, day and time in seconds.
      • uniform vec4 date; in GLSL.
    • sampleRate (1f) - Sound sample rate. 44100 by default.
      • uniform float sampleRate; in GLSL.
    • iChannel0...3 (sampler2D) - Input channels 0 to 3. null by default. uniform sampler2D iChannel0; in GLSL.
  • Get uniform object
    var uniform = shader.getUniform(key);\n
    • Texture key
      var textureKey = uniform.textureKey;\n
    • Get texture key of iChannel0, iChannel1, iChannel2, iChannel3 sampler2D uniform.
      var textureKey = shader.getUniform('iChannel0').textureKey;\nvar textureKey = shader.getUniform('iChannel1').textureKey;\nvar textureKey = shader.getUniform('iChannel2').textureKey;\nvar textureKey = shader.getUniform('iChannel3').textureKey;\n
  • Sets a property of a uniform already present on this shader.
    shader.setUniform(key, value);\n
    • key : The key of the uniform to modify. Use dots for deep properties, i.e. resolution.value.x.
  • Sets a sampler2D uniform from texture manager.
    shader.setChannel0(textureKey);\nshader.setChannel1(textureKey);\nshader.setChannel2(textureKey);\nshader.setChannel3(textureKey);\n// shader.setChannel0(textureKey, textureData);\n// shader.setChannel1(textureKey, textureData);\n// shader.setChannel2(textureKey, textureData);\n// shader.setChannel3(textureKey, textureData);\n
    or
    shader.setSampler2D(uniformKey, textureKey, textureIndex);\n// shader.setSampler2D(uniformKey, textureKey, textureIndex, textureData);\n
    • uniformKey : 'iChannel0', 'iChannel1', 'iChannel2', or 'iChannel3'.
    • textureIndex : 0(for iChannel0), 1(for iChannel1), 2(for iChannel2), 3(for iChannel3).
    • textureData : Additional texture data.
    • textureKey: Key from the Texture Manager cache. It cannot be a single frame from a texture, only the full image. Lots of shaders expect textures to be power-of-two sized.
  • Sets a sampler2D uniform from a webgl texture.
    shader.setSampler2DBuffer(uniformKey, texture, width, height, textureIndex);\n// shader.setSampler2DBuffer(uniformKey, texture, width, height, textureIndex, textureData);\n
    • uniformKey : 'iChannel0', 'iChannel1', 'iChannel2', or 'iChannel3'.
    • width, height : The width, height of the texture.
    • textureIndex : 0(for iChannel0), 1(for iChannel1), 2(for iChannel2), 3(for iChannel3).
    • textureData : Additional texture data.
"},{"location":"shader/#other-uniforms","title":"Other uniforms","text":"
  • mouse, a pointer parameter.
    • Get
      var pointer = shader.pointer;\n
    • Set
      shader.setPointer(pointer);\n
      • pointer : {x, y}
  • time, the elapsed game time, in seconds.
    • Get
      var time = shader.getUniform('time').value;\n// var time = shader.uniforms.time.value\n
    • Set
      shader.setUniform('time.value', time);\n
"},{"location":"shader/#output","title":"Output","text":"
  • Render to Display list, by default.
  • Redirect render result to internal webgl texture.
    shader.setRenderToTexture();\nvar texture = shader.glTexture;\n
  • Redirect render result to internal webgl texture, and sample2D from buffer.
    shader.setRenderToTexture(undefined, true);\nvar texture = shader.glTexture;\n
  • Redirect render result to texture manager, for texture-based game object.
    shader.setRenderToTexture(textureKey);\n// var texture = shader.glTexture;\n
  • Redirect render result to texture manager, and Sample2D from buffer.
    shader.setRenderToTexture(textureKey, true);\n// var texture = shader.glTexture;\n
"},{"location":"shader/#texture-routing","title":"Texture routing","text":"
graph TB\n\nTextureManagerIn[\"Texture manager\"] --> |\"shader.setSampler2D()\"| Sampler2D[\"Samplers:<br>iChannel0<br>iChannel1<br>iChannel2<br>iChannel3\"]\nSampler2D--> Shader[\"shader<br>Shader game object\"]\nShader --> DisplayList[\"Display list\"]\nShader --> |\"shader.setRenderToTexture()\"| InternalTexture[\"shader.glTexture\"]\nInternalTexture -.-> |\"Texture key\"| TextureManagerOut[\"Texture manager\"]\nTextureManagerOut -.-> GameObject[\"Image game object\"]\nGameObject -.-> DisplayList\n\nWebGLTexture[\"WebGl texture<br>gameObject.glTexture\"] --> |\"shader.setSampler2DBuffer()\"| Sampler2D\nInternalTexture --> WebGLTexture\n\nsubgraph Output\nDisplayList\nGameObject\nTextureManagerOut\nend\n\nsubgraph Input\nTextureManagerIn\nWebGLTexture\nend
"},{"location":"shader/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shader/#create-mask","title":"Create mask","text":"
var mask = shader.createBitmapMask();\n

See mask

"},{"location":"shader/#baseshader","title":"BaseShader","text":"
var baseShader = new Phaser.Display.BaseShader(key, fragmentSrc, vertexSrc, uniforms);\n
  • key : The key of this shader
  • fragmentSrc : The fragment source for the shader.
  • vertexSrc : The vertex source for the shader.
    • undefined, or '' : Use default vertex source.
  • uniforms : Optional object defining the uniforms the shader uses.
    {\nuniformName : {type: uniformType, value: initValue},\n...\n}\n
    • uniformName : Uniform name in fragment source.
    • uniformType, initValue : Type and initial value of uniform.
      • '1f' : initValue is a single float value.
        • Example : time: { type: '1f', value: 0 }
      • '2f' : initValue is float numbers {x, y}.
        • Example : resolution: { type: '2f', value: { x: this.width, y: this.height } }
      • '3f' : initValue is float numbers {x, y, z}.
        • Example : color: { type: '3f', value: {x: 0, y: 0, z: 0}}
      • '4f' : initValue is float numbers {x, y, z, w}.
"},{"location":"shake-position/","title":"Shake position","text":""},{"location":"shake-position/#introduction","title":"Introduction","text":"

Shake position of game object.

  • Author: Rex
  • Behavior of game object
"},{"location":"shake-position/#live-demos","title":"Live demos","text":"
  • Shake position
  • Shake position on mutliple game objects
"},{"location":"shake-position/#usage","title":"Usage","text":"

Sample code

"},{"location":"shake-position/#install-plugin","title":"Install plugin","text":""},{"location":"shake-position/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexshakepositionplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexshakepositionplugin.min.js', true);\n
  • Add shake-position behavior
    var shakePosition = scene.plugins.get('rexshakepositionplugin').add(gameObject, config);\n
"},{"location":"shake-position/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ShakePositionPlugin from 'phaser3-rex-plugins/plugins/shakeposition-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexShakePosition',\nplugin: ShakePositionPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add shake-position behavior
    var shakePosition = scene.plugins.get('rexShakePosition').add(gameObject, config);\n
"},{"location":"shake-position/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ShakePosition from 'phaser3-rex-plugins/plugins/shakeposition.js';\n
  • Add shake-position behavior
    var shakePosition = new ShakePosition(gameObject, config);\n
"},{"location":"shake-position/#create-instance","title":"Create instance","text":"
var shake = scene.plugins.get('rexShake').add(gameObject, {\n// mode: 1, // 0|'effect'|1|'behavior'\n// duration: 500,\n// magnitude: 10,\n// magnitudeMode: 1, // 0|'constant'|1|'decay'\n// axis: 0,      //0|'both'|'h&v'|1|'horizontal'|'h'|2|'vertical'|'v'\n});\n
  • mode :
    • 'effect', or 0 : Shake position in 'poststep' game event, and restore in 'prestep' game event.
    • 'behavior', or 1 : Shake position in 'preupdate' scene event.
  • duration : Duration of shaking, in millisecond.
  • magnitude : The strength of the shake, in pixels.
  • magnitudeMode :
    • 'constant', or 0 : Constant strength of the shake.
    • 'decay', or 1 : Decay the strength of the shake.
  • axis :
    • 'both','h&v', 'x&y', or 0 : Changing position on all directions.
    • 'horizontal','h', 'x', or 1 : Changing position on horizontal/x axis.
    • 'vertical','v', 'y', or 2 : Changing position on vertical/y axis.
"},{"location":"shake-position/#start-shaking","title":"Start shaking","text":"
shake.shake();\n// shake.shake(duration, magnitude);\n

or

shake.shake({\nduration: 500,\nmagnitude: 10\n});\n
"},{"location":"shake-position/#stop-shakeing","title":"Stop shakeing","text":"
shake.stop();\n
"},{"location":"shake-position/#enable","title":"Enable","text":"
  • Enable/resume (default)
    shake.setEnable();\n
    or
    shake.enable = true;\n
  • Disable/pause
    shake.setEnable(false);\n
    or
    shake.enable = false;\n
"},{"location":"shake-position/#set-updating-mode","title":"Set updating mode","text":"
shake.setMode(mode);\n
  • mode :
    • 'effect', or 0 : Shake position in post-update stage, and restore in pre-update stage.
    • 'behavior', or 1 : Shake position in pre-update stage.
"},{"location":"shake-position/#set-duration","title":"Set duration","text":"
shake.setDuration(duration);\n// shake.duration = duration;\n
"},{"location":"shake-position/#set-magnitude","title":"Set magnitude","text":"
shake.setMagnitude(magnitude);\nshake.magnitude = magnitude;\n
  • magnitude : The strength of the shake, in pixels.
"},{"location":"shake-position/#set-magnitude-mode","title":"Set magnitude mode","text":"
shake.setMagnitudeMode(magnitudeMode);\n// shake.magnitudeMode = magnitudeMode;\n
  • magnitudeMode :
    • 'constant', or 0 : Constant strength of the shake.
    • 'decay', or 1 : Decay the strength of the shake.
"},{"location":"shake-position/#set-axis-mode","title":"Set axis mode","text":"
shake.setAxisMode(axis);\n
  • axis :
    • 'both','h&v', 'x&y', or 0 : Dragging on all directions.
    • 'horizontal','h', 'x', or 1 : Dragging on horizontal/x axis.
    • 'vertical','v', 'y', or 2 : Dragging on vertical/y axis.
"},{"location":"shake-position/#events","title":"Events","text":"
  • On reached target
    shake.on('complete', function(gameObject, shake){});\n
"},{"location":"shake-position/#status","title":"Status","text":"
  • Is shakeing
    var isRunning = shake.isRunning;\n
"},{"location":"shape-arc/","title":"Arc","text":""},{"location":"shape-arc/#introduction","title":"Introduction","text":"

Arc shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-arc/#usage","title":"Usage","text":""},{"location":"shape-arc/#create-shape","title":"Create shape","text":"
var arc = scene.add.arc(x, y, radius, startAngle, endAngle, anticlockwise, fillColor);\n// var arc = scene.add.arc(x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha);\n
"},{"location":"shape-arc/#custom-class","title":"Custom class","text":"
  • Define class
    class MyArc extends Phaser.GameObjects.Arc {\nconstructor(scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor) {\nsuper(scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var arc = new MyArc(scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor);\n
"},{"location":"shape-arc/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = arc.fillColor;\nvar alpha = arc.fillAlpha;\n
    • Set
      arc.setFillStyle(color, alpha);\n
    • Clear
      arc.setFillStyle();\n
  • Stroke color
    • Get
      var color = arc.strokeColor;\n
    • Set
      arc.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      arc.setStrokeStyle();\n

No tint methods

Uses arc.setFillStyle(color, alpha) to change color.

"},{"location":"shape-arc/#alpha","title":"Alpha","text":"
  • Get
    var alpha = arc.alpha;\n
  • Set
    arc.setAlpha(alpha);\n// arc.alpha = alpha;\n
"},{"location":"shape-arc/#angle","title":"Angle","text":"
  • Start angle, in degrees.
    • Get
      var startAngle = arc.startAngle;\n
    • Set
      arc.setStartAngle(startAngle);\n// arc.setStartAngle(startAngle, anticlockwise);\n
      or
      arc.startAngle = startAngle;\n
  • End angle, in degrees.
    • Get
      var endAngle = arc.endAngle;\n
    • Set
      arc.seEndAngle(endAngle);\n
      or
      arc.endAngle = endAngle;\n
  • Anticlockwise (true, or false)
    • Get
      var anticlockwise = arc.anticlockwise;\n
    • Set
      arc.anticlockwise = anticlockwise;\n
"},{"location":"shape-arc/#radius","title":"Radius","text":"
  • Radius
    • Get
      var radius = arc.radius;\n
    • Set
      arc.setRadius(radius);\n
      or
      arc.radius = radius;\n
  • Iterations: Increase this value for smoother arcs, at the cost of more polygons being rendered. Default is 0.01
    • Get
      var iterations = arc.iterations;\n
    • Set
      arc.iterations = iterations;\n
"},{"location":"shape-arc/#display-size","title":"Display size","text":"
  • Get
    var width = arc.displayWidth;\nvar height = arc.displayHeight;\n
  • Set
    arc.setDisplaySize(width, height);\n
    or
    arc.displayWidth = width;\narc.displayHeight = height;\n
"},{"location":"shape-arc/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-arc/#create-mask","title":"Create mask","text":"
var mask = arc.createGeometryMask();\n

See mask

"},{"location":"shape-arc/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-checkbox/","title":"Checkbox","text":""},{"location":"shape-checkbox/#introduction","title":"Introduction","text":"

Checkbox input with drawing checker path animation.

  • Author: Rex
  • Game object
"},{"location":"shape-checkbox/#live-demos","title":"Live demos","text":"
  • Checkbox
"},{"location":"shape-checkbox/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-checkbox/#install-plugin","title":"Install plugin","text":""},{"location":"shape-checkbox/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcheckboxplugin', 'https://raw.githubusercontent.com/rexrainbow/    phaser3-rex-notes/master/dist/rexcheckboxplugin.min.js', true);\n
  • Add checkbox input
    var checkbox = scene.add.rexCheckbox(x, y, width, height, color, config);\n
  • Add checkbox shape (without click input)
    var checkbox = scene.add.rexCheckboxShape(x, y, width, height, color, config);\n
"},{"location":"shape-checkbox/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CheckboxPlugin from 'phaser3-rex-plugins/plugins/checkbox-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCheckboxPlugin',\nplugin: CheckboxPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add checkbox input
    var checkbox = scene.add.rexCheckbox(x, y, width, height, color, config);\n
  • Add checkbox shape (without click input)
    var checkbox = scene.add.rexCheckboxShape(x, y, width, height, color, config);\n
"},{"location":"shape-checkbox/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Checkbox from 'phaser3-rex-plugins/plugins/checkbox.js';\n
  • Add checkbox input
    var checkbox = new Checkbox(scene, x, y, width, height, color, config);\nscene.add.existing(checkbox);\n
  • Add checkbox shape (without click input)
    // import CheckboxShape from 'phaser3-rex-plugins/plugins/checkboxshape.js';\nvar checkbox = new CheckboxShape(scene, x, y, width, height, color, config);\nscene.add.existing(checkbox);\n
"},{"location":"shape-checkbox/#create-checkbox-input","title":"Create checkbox input","text":"
var checkbox = scene.add.rexCheckbox(x, y, width, height, color, config);\n

or

var checkbox = scene.add.rexCheckbox({\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\n\ncolor: 0x005cb2,\nboxFillAlpha: 1,\nuncheckedColor: null,\nuncheckedBoxFillAlpha: 1,\n\nboxLineWidth: 4,\nboxStrokeColor: 0x005cb2,\nboxStrokeAlpha: 1,\nuncheckedBoxStrokeColor: 0x005cb2,\nuncheckedBoxStrokeAlpha: 1,\n\ncheckerColor: 0xffffff,\ncheckerAlpha: 1,\n\n// boxSize: 1,\n// checkerSize: 1,\n\ncircleBox: false,\n\nanimationDuration: 150,\n\nchecked: false, // or value: false,\n\nclick: undefined,\n// click: {\n//     mode: 1,            // 0|'press'|1|'release'\n//     clickInterval: 100  // ms\n//     threshold: undefined\n// },\nreadOnly: false,\n});\n
  • width, height : Size of checkbox.
  • Box fill style
    • color, boxFillAlpha : Box color and alpha of checked
    • uncheckedColor, uncheckedBoxFillAlpha : Box color and alpha of unchecked
  • Box stroke style
    • boxLineWidth, boxStrokeColor, boxStrokeAlpha : Box stroke color and alpha of checked.
    • uncheckedBoxStrokeColor, uncheckedBoxStrokeAlpha : Box stroke color and alpha of unchecked.
  • Checker style
    • checkerColor, checkerAlpha : Checker color and alpha
  • circleBox : Shape of box
    • false : Rectangle shape box. Default behavior.
    • true : Circle shape box
  • boxSize, checkerSize : Size ratio of box, and checker. Default value is 1.
  • animationDuration : Duration of drawing path of checker.
  • checked : Initial value of checked.
  • click : Configuration of click input
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
    • click.threshold : Cancel clicking detecting when dragging distance is larger then this threshold.
      • undefined : Ignore this feature. Default behavior.
  • readOnly : Set ture to disable input.
"},{"location":"shape-checkbox/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCheckbox extends RexPlugins.GameObjects.Checkbox {\nconstructor(scene, x, y, width, height, color, config) {\nsuper(scene, x, y, width, height, color, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var checkbox = new MyCheckbox(scene, x, y, width, height, color, config);\n
"},{"location":"shape-checkbox/#check","title":"Check","text":"
  • Get
    var checked = checkbox.checked;\n// var checked = checkbox.value;\n
  • Set
    • Check
      checkbox.setChecked();\n// checkbox.setChecked(true);\n// checkbox.setValue(true);\n
      or
      checkbox.checked = true;\n// checkbox.value = true;\n
    • Uncheck
      checkbox.setChecked(false);\n// checkbox.setValue(false);\n
      or
      checkbox.checked = false;\n// checkbox.value = false;\n
    • Toggle
      checkbox.toggleChecked();\n// checkbox.setValue(!checkbox.checked);\n
      or
      checkbox.checked = !checkbox.checked;\n// checkbox.value = !checkbox.value;\n
"},{"location":"shape-checkbox/#read-only","title":"Read only","text":"
  • Get
    var readOnly = checkbox.readOnly;\n
  • Set
    checkbox.setReadOnly();\n// checkbox.setReadOnly(true);\n
    or
    checkbox.readOnly = true;\n
"},{"location":"shape-checkbox/#box-fill-style","title":"Box fill style","text":"
  • Get
    var color = checkbox.boxFillColor;\nvar alpha = checkbox.boxFillAlpha;\n
    var color = checkbox.uncheckedBoxFillColor;\nvar alpha = checkbox.uncheckedBoxFillAlpha;\n
  • Set
    checkbox.setBoxFillStyle(color, alpha);\n// checkbox.boxFillColor = color;\n// checkbox.boxFillAlpha = alpha;\n
    checkbox.setUncheckedBoxFillStyle(color, alpha);\n// checkbox.uncheckedBoxFillColor = color;\n// checkbox.uncheckedBoxFillAlpha = alpha;\n
"},{"location":"shape-checkbox/#box-stroke-style","title":"Box stroke style","text":"
  • Get
    var lineWidth = checkbox.boxLineWidth;\nvar color = checkbox.boxStrokeColor;\nvar alpah = checkbox.boxStrokeAlpha;\n
    var lineWidth = checkbox.uncheckedBoxLineWidth;\nvar color = checkbox.uncheckedBoxStrokeColor;\nvar alpah = checkbox.uncheckedBoxStrokeAlpha;\n
  • Set
    checkbox.setBoxStrokeStyle(lineWidth, color, alpha);\n// checkbox.boxLineWidth = lineWidth;\n// checkbox.boxStrokeColor = color;\n// checkbox.boxStrokeAlpha = alpha;\n
    checkbox.setUncheckedBoxStrokeStyle(lineWidth, color, alpha);\n// checkbox.uncheckedBoxLineWidth = lineWidth;\n// checkbox.uncheckedBoxStrokeColor = color;\n// checkbox.uncheckedBoxStrokeAlpha = alpha;\n
"},{"location":"shape-checkbox/#checker-style","title":"Checker style","text":"
  • Get
    var color = checkbox.checkerColor;\nvar alpha = checkbox.checkAlpha;\n
  • Set
    checkbox.setCheckerStyle(color, alpha);\n// checkbox.checkerColor = color;\n// checkbox.checkAlpha = alpha;\n
"},{"location":"shape-checkbox/#checker-animation","title":"Checker animation","text":"
  • Duration
    • Get
      var duration = checkbox.checkerAnimDuration;\n
    • Set
      checkbox.setCheckerAnimDuration(duration);\ncheckbox.checkerAnimDuration = duration;\n
"},{"location":"shape-checkbox/#size","title":"Size","text":"
  • Get
    var width = checkbox.width;\nvar height = checkbox.height;\n
  • Set
    checkbox.setSize(width, height);\n
    or
    checkbox.width = width;\ncheckbox.height = height;\n
"},{"location":"shape-checkbox/#display-size","title":"Display size","text":"
  • Get
    var width = checkbox.displayWidth;\nvar height = checkbox.displayHeight;\n
  • Set
    checkbox.setDisplaySize(width, height);\n
    or
    checkbox.displayWidth = width;\ncheckbox.displayHeight = height;\n
"},{"location":"shape-checkbox/#size-ratio","title":"Size ratio","text":"
  • Get
    var boxSize = checkbox.boxSize;\nvar checkerSize =checkbox.checkerSize;\n
    • boxSize, checkerSize : Size ratio of box, and checker
  • Set
    checkbox.setBoxSize(sizeRatio);\ncheckbox.setCheckerSize(sizeRatio);\n
"},{"location":"shape-checkbox/#events","title":"Events","text":"
  • On value change
    checkbox.on('valuechange', function(value) {\n// value: checked\n})\n
"},{"location":"shape-checkbox/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-checkbox/#create-mask","title":"Create mask","text":"
var mask = checkbox.createGeometryMask();\n

See mask

"},{"location":"shape-checkbox/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-circle/","title":"Circle","text":""},{"location":"shape-circle/#introduction","title":"Introduction","text":"

Circle shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-circle/#usage","title":"Usage","text":""},{"location":"shape-circle/#create-shape-object","title":"Create shape object","text":"
var circle = scene.add.circle(x, y, radius, fillColor);\n// var circle = scene.add.circle(x, y, radius, fillColor, fillAlpha);\n
"},{"location":"shape-circle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCircle extends Phaser.GameObjects.Arc {\nconstructor(scene, x, y, radius, fillColor, fillAlpha) {\nsuper(scene, x, y, radius, 0, 360, false, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var circle = new MyCircle(scene, x, y, radius, fillColor, fillAlpha);\n
"},{"location":"shape-circle/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = circle.fillColor;\nvar alpha = circle.fillAlpha;\n
    • Set
      circle.setFillStyle(color, alpha);\n
    • Clear
      circle.setFillStyle();\n
  • Stroke color
    • Get
      var color = circle.strokeColor;\n
    • Set
      circle.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      circle.setStrokeStyle();\n

No tint methods

Uses circle.setFillStyle(color, alpha) to change color.

"},{"location":"shape-circle/#alpha","title":"Alpha","text":"
  • Get
    var alpha = circle.alpha;\n
  • Set
    circle.setAlpha(alpha);\n// circle.alpha = alpha;\n
"},{"location":"shape-circle/#radius","title":"Radius","text":"
  • Radius
    • Get
      var radius = circle.radius;\n
    • Set
      circle.setRadius(radius);\n
      or
      circle.radius = radius;\n
  • Iterations: Increase this value for smoother arcs, at the cost of more polygons being rendered. Default is 0.01
    • Get
      var iterations = circle.iterations;\n
    • Set
      circle.iterations = iterations;\n
"},{"location":"shape-circle/#display-size","title":"Display size","text":"
  • Get
    var width = circle.displayWidth;\nvar height = circle.displayHeight;\n
  • Set
    circle.setDisplaySize(width, height);\n
    or
    circle.displayWidth = width;\ncircle.displayHeight = height;\n
"},{"location":"shape-circle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-circle/#create-mask","title":"Create mask","text":"
var mask = circle.createGeometryMask();\n

See mask

"},{"location":"shape-circle/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-circularprogress/","title":"Circular progres","text":""},{"location":"shape-circularprogress/#introduction","title":"Introduction","text":"

Circular progress bar shape.

  • Author: Rex
  • Game object
"},{"location":"shape-circularprogress/#live-demos","title":"Live demos","text":"
  • Circular-progress
  • Pie bar
"},{"location":"shape-circularprogress/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-circularprogress/#install-plugin","title":"Install plugin","text":""},{"location":"shape-circularprogress/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcircularprogressplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcircularprogressplugin.min.js', true);\n
  • Add circular-progress object
    var circularProgress = scene.add.rexCircularProgress(x, y, radius, color, value, config);\n
"},{"location":"shape-circularprogress/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CircularProgressPlugin from 'phaser3-rex-plugins/plugins/circularprogress-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCircularProgressPlugin',\nplugin: CircularProgressPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add circular-progress object
    var circularProgress = scene.add.rexCircularProgress(x, y, radius, color, value, config);\n
"},{"location":"shape-circularprogress/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CircularProgress from 'phaser3-rex-plugins/plugins/circularprogress.js';\n
  • Add circular-progress object
    var circularProgress = new CircularProgress(scene, x, y, radius, color, value, config);\nscene.add.existing(image);\n
"},{"location":"shape-circularprogress/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCircularProgressPlugin',\nplugin: CircularProgressPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"shape-circularprogress/#create-instance","title":"Create instance","text":"
var circularProgress = scene.add.rexCircularProgress(x, y, radius, barColor, value, {    trackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nanticlockwise: false,\n// iterations: 128,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},\n});\n

or

var circularProgress = scene.add.rexCircularProgress({\nx: 0,\ny: 0,\nradius: 1,\n\nbarColor: undefined,\ntrackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nanticlockwise: false,\n// iterations: 128,\n\nvalue: 0,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},  });\n
  • x, y : Position of this object.
  • radius : Radius of this circle. Size will be (radius*2, radius*2).
  • barColor : Color of circular bar, in number or css string value.
  • trackColor : Color of circular track, in number or css string value.
  • centerColor : Color of center circle, in number or css string value.
  • thickness : 0 ~ 1, thickness of circular bar. Default value is 0.2 (0.2*radius)
  • startAngle : Start angle of circular bar, in radians. Default value is 270 degrees.
  • anticlockwise : Set true to put anticlockwise circular bar. Default value is false.
  • iterations : Iterations of curve, set larger value to get more smooth rendering result. Default value is 128.
  • value : 0 ~ 1, progress value. Default is 0.
  • easeValue : Parameters of easing value.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • valuechangeCallback : callback function when value changed.
    function(newValue, oldValue, circularProgress) {\n}\n

Add circular-progress from JSON

var circularProgress = scene.make.rexCircularProgress({\nx: 0,\ny: 0,\nradius: 1,\n\nbarColor: undefined,\ntrackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nanticlockwise: false,\n\nvalue: 0,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},  add: true\n});\n
"},{"location":"shape-circularprogress/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCircularProgress extends CircularProgress {\nconstructor(scene, x, y, radius, color, value, config) {\nsuper(scene, x, y, radius, color, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var circularProgress = new MyCircularProgress(scene, x, y, radius, color, value, config);\n
"},{"location":"shape-circularprogress/#progress-value","title":"Progress value","text":"
  • Get value
    var value = circularProgress.getValue(min, max); // value : min ~ max\n
    or
    var value = circularProgress.getValue(); // value: 0 ~ 1\n
    or
    var value = circularProgress.value; // value: 0 ~ 1\n
  • Set value
    circularProgress.setValue(value, min, max); // value: min ~ max\n
    or
    circularProgress.setValue(value); // value: 0 ~ 1\n
    or
    circularProgress.value = value; // value: 0 ~ 1\n
  • Increase value
    circularProgress.addValue(inc, min, max); // inc: min ~ max\n
    or
    circularProgress.addValue(inc); // inc: 0 ~ 1\n
    or
    circularProgress.value += inc; // inc: 0 ~ 1\n
"},{"location":"shape-circularprogress/#ease-progress-value","title":"Ease progress value","text":"
  • Ease value to
    circularProgress.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    circularProgress.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    circularProgress.stopEaseValue();\n
  • Set ease duration
    circularProgress.setEaseValueDuration(duration);\n
  • Set ease function
    circularProgress.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"shape-circularprogress/#radius","title":"Radius","text":"
  • Get
    var radius = circularProgress.radius;\n
  • Set
    circularProgress.setRadius(radius);\n// circularProgress.radius = radius;\n
    • Also resize this game object to (radius*2, radius*2)
"},{"location":"shape-circularprogress/#circular-track","title":"Circular track","text":"
  • Color
    • Get
      var trackColor = circularProgress.trackColor;\n
    • Set
      circularProgress.setTrackColor(trackColor);\n// circularProgress.trackColor = trackColor;\n
  • Thickness : radius*thickness
    circularProgress.setThickness(thickness);\n
    • thickness : 0~1.
"},{"location":"shape-circularprogress/#circular-bar","title":"Circular bar","text":"
  • Color
    • Get
      var barColor = circularProgress.barColor;\n
    • Set
      circularProgress.setBarColor(barColor);\n// circularProgress.barColor = barColor;\n
  • Thickness : radius*thickness
    circularProgress.setThickness(thickness);\n
    • thickness : 0~1.
  • Start angle
    • Get
      var startAngle = circularProgress.startAngle;\n
    • Set
      circularProgress.setStartAngle(startAngle);\ncircularProgress.startAngle = startAngle;\n
      • startAngle : Start angle of circular bar, in radians.
  • Anticlockwise
    • Get
      var anticlockwise = circularProgress.anticlockwise;\n
    • Set
      circularProgress.setAnticlockwise(anticlockwise);\n// circularProgress.anticlockwise = anticlockwise;\n
"},{"location":"shape-circularprogress/#center-circle","title":"Center circle","text":"
  • Color
    • Get
      var centerColor = circularProgress.centerColor;\n
    • Set
      circularProgress.setCenterColor(centerColor);\n// circularProgress.centerColor = centerColor;\n
"},{"location":"shape-circularprogress/#events","title":"Events","text":"
  • On value changed
    circularProgress.on('valuechange', function(newValue, oldValue, circularProgress){\n//\n}, scope);\n
"},{"location":"shape-circularprogress/#alpha","title":"Alpha","text":"
  • Get
    var alpha = circularProgress.alpha;\n
  • Set
    circularProgress.setAlpha(alpha);\n// circularProgress.alpha = alpha;\n
"},{"location":"shape-circularprogress/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-circularprogress/#create-mask","title":"Create mask","text":"
var mask = circularProgress.createGeometryMask();\n

See mask

"},{"location":"shape-circularprogress/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-circularprogress/#compare-with-circular-progress-canvas","title":"Compare with Circular-progress canvas","text":"
  • Circular-progress canvas creates a canvas then draw on that canvas, circular progress shape draw on GRAPHICS pipeline like Shape or Graphics game object.
  • Circular-progress canvas can draw text directly, circular progress shape can't draw any text.
"},{"location":"shape-cover/","title":"Cover","text":""},{"location":"shape-cover/#introduction","title":"Introduction","text":"

Rectangle shape covered full window, and block all touch events.

  • Author: Rex
  • Game object
"},{"location":"shape-cover/#live-demos","title":"Live demos","text":"
  • Cover
"},{"location":"shape-cover/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-cover/#install-plugin","title":"Install plugin","text":""},{"location":"shape-cover/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcoverplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcoverplugin.min.js', true);\n
  • Add cover object
    var cover = scene.add.rexCover(config);\n
"},{"location":"shape-cover/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CoverPlugin from 'phaser3-rex-plugins/plugins/cover-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCoverPlugin',\nplugin: CoverPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add cover object
    var cover = scene.add.rexCover(config);\n
"},{"location":"shape-cover/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Cover from 'phaser3-rex-plugins/plugins/cover.js';\n
  • Add cover object
    var cover = new Cover(scene, config);\nscene.add.existing(cover);\n
"},{"location":"shape-cover/#create-cover-object","title":"Create cover object","text":"
var cover = scene.add.rexCover({\n// color: 0x0,\n// alpha: 0.8\n});\n
  • color : Color of cover.
  • alpha : Alpha value of cover.
"},{"location":"shape-cover/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCover extends RexPlugins.GameObjects.Cover {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var cover = new MyCover(scene, config);\n
"},{"location":"shape-cover/#color","title":"Color","text":"
  • Tint
    • Get
      var tint = cover.tint;\n
    • Set
      cover.tint = tint;\n
  • Alpha
    • Get
      var alpha = cover.alpha;\n
    • Set
      cover.alpha = alpha;\n
  • Fill color
    • Get
      var color = cover.fillColor;\nvar alpha = cover.fillAlpha;\n
    • Set
      cover.setFillStyle(color, alpha);\n
    • Clear
      cover.setFillStyle();\n
"},{"location":"shape-cover/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-cover/#create-mask","title":"Create mask","text":"
var mask = cover.createGeometryMask();\n

See mask

"},{"location":"shape-cover/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-curve/","title":"Curve","text":""},{"location":"shape-curve/#introduction","title":"Introduction","text":"

Curve shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-curve/#usage","title":"Usage","text":""},{"location":"shape-curve/#create-shape-object","title":"Create shape object","text":"
var curve = scene.add.curve(x, y, path, fillColor);\n// var curve = scene.add.curve(x, y, path, fillColor, fillAlpha);\n
  • path : Path object.
"},{"location":"shape-curve/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCurve extends Phaser.GameObjects.Curve {\nconstructor(scene, x, y, path, fillColor, fillAlpha) {\nsuper(scene, x, y, path, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var curve = new MyCurve(scene, x, y, path, fillColor, fillAlpha);\n
"},{"location":"shape-curve/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = curve.fillColor;\nvar alpha = curve.fillAlpha;\n
    • Set
      curve.setFillStyle(color, alpha);\n
    • Clear
      curve.setFillStyle();\n
  • Stroke color
    • Get
      var color = curve.strokeColor;\n
    • Set
      curve.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      curve.setStrokeStyle();\n

No tint methods

Uses curve.setFillStyle(color, alpha) to change color.

"},{"location":"shape-curve/#alpha","title":"Alpha","text":"
  • Get
    var alpha = curve.alpha;\n
  • Set
    curve.setAlpha(alpha);\n// curve.alpha = alpha;\n
"},{"location":"shape-curve/#smoothness","title":"Smoothness","text":"

The number of points used when rendering it. Increase this value for smoother curves, at the cost of more polygons being rendered.

curve.setSmoothness(smoothness);\n
or
curve.smoothness = smoothness;\n

"},{"location":"shape-curve/#display-size","title":"Display size","text":"
  • Get
    var width = curve.displayWidth;\nvar height = curve.displayHeight;\n
  • Set
    curve.setDisplaySize(width, height);\n
    or
    curve.displayWidth = width;\ncurve.displayHeight = height;\n
"},{"location":"shape-curve/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-curve/#create-mask","title":"Create mask","text":"
var mask = curve.createGeometryMask();\n

See mask

"},{"location":"shape-curve/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-custom-progress/","title":"Custom progress","text":""},{"location":"shape-custom-progress/#introduction","title":"Introduction","text":"

Custom progress bar based on custom-shapes.

  • Author: Rex
  • Game object
"},{"location":"shape-custom-progress/#live-demos","title":"Live demos","text":"
  • React-circle-progress-bar
  • Round rectangle
  • Orb
  • Trapezoid Mask
  • Round rectangles mask
  • Slash effect with rexUI
  • Path segment animation
"},{"location":"shape-custom-progress/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-custom-progress/#install-plugin","title":"Install plugin","text":""},{"location":"shape-custom-progress/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcustomprogressplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcustomprogressplugin.min.js', true);\n
  • Add custom shapes object
    var customProgress = scene.add.rexCustomProgress(x, y, width, height, config);\n
"},{"location":"shape-custom-progress/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CustomProgressPlugin from 'phaser3-rex-plugins/plugins/customprogress-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCustomProgressPlugin',\nplugin: CustomProgressPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add custom shapes object
    var customProgress = scene.add.rexCustomProgress(x, y, width, height, config);\n
"},{"location":"shape-custom-progress/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CustomProgress from 'phaser3-rex-plugins/plugins/bbcodetext.js';\n
  • Add custom shapes object
    var customProgress = new CustomProgress(scene, x, y, width, height, config);\nscene.add.existing(customProgress);\n
"},{"location":"shape-custom-progress/#add-custom-shapes-object","title":"Add custom shapes object","text":"
var customProgress = scene.add.rexCustomProgress(x, y, width, height, {\n// type: 'rexCustomProgress',\n\ncreate: [\n{ name: name0, type: shapeType},\n{ name: name1, type: shapeType},\n...\n],\n\n// create: {\n//     shapeType: [name0, name1, ...],\n//     shapeType: number,\n//     shapeType: name,\n// },\n\n// create: function() {\n// \n// },\n\nupdate: function() {\n\n},\n\nvalue: 0,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},\n});\n

or

var customProgress = scene.add.rexCustomProgress({\n// x: 0,\n// y: 0,\n// width: 64,\n// height: 64,\n// type: 'rexCustomProgress',\n\ncreate: [\n{ name: name0, type: shapeType},\n{ name: name1, type: shapeType},\n...\n],\n\n// create: {\n//     shapeType: [name0, name1, ...],\n//     shapeType: number,\n//     shapeType: name,\n// },\n\n// create: function() {\n// \n// },\n\nupdate: function() {\n\n},\n\nvalue: 0,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\n\nvaluechangeCallback: function(newValue, oldValue, circularProgress) {\n},\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • create : Callback to create shapes
    • An array of object with name and type
      { name: name0, type: shapeType }\n
      • shapeType :
        • 'arc' : Create Arc shape.
        • 'circle' : Create Circle shape.
        • 'ellipse' : Create Ellipse shape.
        • 'line' : Create Line shape.
        • 'lines' : Create Lines shape.
        • 'rectangle' : Create Rectangle shape.
        • 'roundRectangle' : Create Round rectangle shape.
        • 'triangle' : Create Triangle shape.
    • A plain object with shapeType: name, or shapeType: number
      • shapeType : arc, circle, ellipse, line, rectangle, triangle
      • nameArray : An array of unique string name for each shape.
      • name : An unique string name of this shape.
      • number : Amount of shapes to create.
    • A callback
      function() {\n// this : This custom shapes game object\nvar shape = this.createShape(shapeType, name);\nthis.addShape(shape);\n}\n
      • this.createShape(shapeType, name) : Crate a shape instance, with an unique name.
      • this.addShape(shape) : Add this shape instance to this custom custom shapes.
  • update : Callback when refresh
    function() {\n// this : This custom shapes game object     \nvar shapes = this.getShapes();\nvar shape = this.getShape(name);\n// ...\n// var isSizeChanged = this.isSizeChanged;\n\n// var fillColor = this.fillColor;\n// var fillAlpha = this.fillAlpha;\n// var lineWidth = this.lineWidth;\n// var strokeColor = this.strokeColor;\n// var strokeAlpha = this.strokeAlpha;\n// ...\n// var value = this.value;\n}\n
    • Shape instances : Change properties of shape instances.
      • this.getShapes() : Return all shapes in an array.
      • this.getShape(name) : Return a shape by the unique string name.
    • Is size changed : this.isSizeChanged
    • Fill style : this.fillColor, this.fillAlpha
    • Stroke style : this.strokeColor, this.strokeAlpha, this.lineWidth
    • Current progress value : this.value
  • value : 0 ~ 1, progress value. Default is 0.
  • easeValue : Parameters of easing value.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • valuechangeCallback : callback function when value changed.
    function(newValue, oldValue, customProgress) {\n}\n
"},{"location":"shape-custom-progress/#set-update-shape-callback","title":"Set update shape callback","text":"

See Shape class

"},{"location":"shape-custom-progress/#size","title":"Size","text":"

See Size

"},{"location":"shape-custom-progress/#styles","title":"Styles","text":"

See Styles

"},{"location":"shape-custom-progress/#recreate-shapes","title":"Recreate shapes","text":"

See Shape class

"},{"location":"shape-custom-progress/#progress-value","title":"Progress value","text":"
  • Get value
    var value = customProgress.getValue(min, max); // value : min ~ max\n
    or
    var value = customProgress.getValue(); // value: 0 ~ 1\n
    or
    var value = customProgress.value; // value: 0 ~ 1\n
  • Set value
    customProgress.setValue(value, min, max); // value: min ~ max\n
    or
    customProgress.setValue(value); // value: 0 ~ 1\n
    or
    customProgress.value = value; // value: 0 ~ 1\n
  • Increase value
    customProgress.addValue(inc, min, max); // inc: min ~ max\n
    or
    customProgress.addValue(inc); // inc: 0 ~ 1\n
    or
    customProgress.value += inc; // inc: 0 ~ 1\n
"},{"location":"shape-custom-progress/#ease-progress-value","title":"Ease progress value","text":"
  • Set ease duration
    customProgress.setEaseValueDuration(duration);\n
  • Set ease function
    customProgress.setEaseValueFunction(ease);\n
    • ease : Ease function.
  • Ease value to
    customProgress.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    customProgress.easeValueTo(value);  // value: 0 ~ 1\n
  • Ease value repeat
    customProgress.easeValueRepeat(from, to);  // from, to: 0 ~ 1\n// customProgress.easeValueRepeat(from, to, repeat, repeatDelay);\n
  • Stop ease
    customProgress.stopEaseValue();\n
"},{"location":"shape-custom-progress/#refresh","title":"Refresh","text":"

Redraw shapes when

  • Value changed : customProgress.setValue(newValue), customProgress.easeValueTo(newValue)
  • Resize : customProgress.resize(width, height)
  • Set dirty : customProgress.setDirty()
  • Set update shape callback : customProgress.setUpdateShapesCallback(callback)
"},{"location":"shape-custom-progress/#shape-class","title":"Shape class","text":"

See Shape class

"},{"location":"shape-custom-progress/#events","title":"Events","text":"
  • On value changed
    customProgress.on('valuechange', function(newValue, oldValue, customProgress){\n//\n}, scope);\n
"},{"location":"shape-custom-progress/#alpha","title":"Alpha","text":"
  • Get
    var alpha = customProgress.alpha;\n
  • Set
    customProgress.setAlpha(alpha);\n// customProgress.alpha = alpha;\n
"},{"location":"shape-custom-progress/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-custom-progress/#create-mask","title":"Create mask","text":"
var mask = customProgress.createGeometryMask();\n

See mask

"},{"location":"shape-custom-progress/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-custom-shapes/","title":"Custom shapes","text":""},{"location":"shape-custom-shapes/#introduction","title":"Introduction","text":"

Custom shapes on shape.

  • Author: Rex
  • Game object
"},{"location":"shape-custom-shapes/#live-demos","title":"Live demos","text":"
  • Speech bubble
  • Jigsaw
  • Checkbox
  • World to localXY
"},{"location":"shape-custom-shapes/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-custom-shapes/#install-plugin","title":"Install plugin","text":""},{"location":"shape-custom-shapes/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexcustomshapesplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexcustomshapesplugin.min.js', true);\n
  • Add custom shapes object
    var customShapes = scene.add.rexCustomShapes(x, y, width, height, config);\n
"},{"location":"shape-custom-shapes/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import CustomShapesPlugin from 'phaser3-rex-plugins/plugins/customshapes-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexCustomShapesPlugin',\nplugin: CustomShapesPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add custom shapes object
    var customShapes = scene.add.rexCustomShapes(x, y, width, height, config);\n
"},{"location":"shape-custom-shapes/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import CustomShapes from 'phaser3-rex-plugins/plugins/bbcodetext.js';\n
  • Add custom shapes object
    var customShapes = new CustomShapes(scene, x, y, width, height, config);\nscene.add.existing(customShapes);\n
"},{"location":"shape-custom-shapes/#add-custom-shapes-object","title":"Add custom shapes object","text":"
var customShapes = scene.add.rexCustomShapes(x, y, width, height, {\n// type: 'rexCustomShapes',\n\ncreate: [\n{ name: name0, type: shapeType},\n{ name: name1, type: shapeType},\n...\n],\n\n// create: {\n//     shapeType: [name0, name1, ...],\n//     shapeType: number,\n//     shapeType: name,\n// },\n\n// create: function() {\n// \n// },\n\nupdate: function() {\n\n},\n});\n

or

var customShapes = scene.add.rexCustomShapes({\n// x: 0,\n// y: 0,\n// width: 64,\n// height: 64,\n// type: 'rexCustomShapes',\n\ncreate: [\n{ name: name0, type: shapeType},\n{ name: name1, type: shapeType},\n...\n],\n\n// create: {\n//     shapeType: [name0, name1, ...],\n//     shapeType: number,\n//     shapeType: name,\n// },\n\n// create: function() {\n// \n// },\n\nupdate: function() {\n\n},\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • create : Callback to create shapes
    • An array of object with name and type
      { name: name0, type: shapeType }\n
      • shapeType :
        • 'arc' : Create Arc shape.
        • 'circle' : Create Circle shape.
        • 'ellipse' : Create Ellipse shape.
        • 'line' : Create Line shape.
        • 'lines' : Create Lines shape.
        • 'rectangle' : Create Rectangle shape.
        • 'roundRectangle' : Create Round rectangle shape.
        • 'triangle' : Create Triangle shape.
    • A plain object with shapeType: name, or shapeType: number
      • shapeType : arc, circle, ellipse, line, rectangle, triangle
      • nameArray : An array of unique string name for each shape.
      • name : An unique string name of this shape.
      • number : Amount of shapes to create.
    • A callback
      function() {\n// this : This custom shapes game object\nvar shape = this.createShape(shapeType, name);\nthis.addShape(shape);\n}\n
      • this.createShape(shapeType, name) : Crate a shape instance, with an unique name.
      • this.addShape(shape) : Add this shape instance to this custom custom shapes.
  • update : Callback when refresh
    function() {\n// this : This custom shapes game object     \nvar shapes = this.getShapes();\nvar shape = this.getShape(name);\n// ...\n// var isSizeChanged = this.isSizeChanged;\n\n// var fillColor = this.fillColor;\n// var fillAlpha = this.fillAlpha;\n// var lineWidth = this.lineWidth;\n// var strokeColor = this.strokeColor;\n// var strokeAlpha = this.strokeAlpha;\n}\n
    • Shape instances : Change properties of shape instances.
      • this.getShapes() : Return all shapes in an array.
      • this.getShape(name) : Return a shape by the unique string name.
    • Is size changed : this.isSizeChanged
    • Fill style : this.fillColor, this.fillAlpha
    • Stroke style : this.strokeColor, this.strokeAlpha, this.lineWidth
"},{"location":"shape-custom-shapes/#set-update-shape-callback","title":"Set update shape callback","text":"
customShapes.setUpdateShapesCallback(callback);\n
  • callback :
    function() {\n// this : This custom shapes game object     \nvar shapes = this.getShapes();\nvar shape = this.getShape(name);\n// ...\n// var isSizeChanged = this.isSizeChanged;\n}\n
    • Shape instances : Change properties of shape instances.
      • this.getShapes() : Return all shapes in an array.
      • this.getShape(name) : Return a shape by the unique string name.
    • Is size changed: this.isSizeChanged
"},{"location":"shape-custom-shapes/#size","title":"Size","text":"

customShapes.setSize(width, height);\n
or
customShapes.resize(width, height);\n
or
customShapes.width = width;\ncustomShapes.height = height;\n

Will set dirty and redraw shapes

"},{"location":"shape-custom-shapes/#styles","title":"Styles","text":"
  • Fill style
    customShapes.setFillStyle(color, alpha);\n
    or
    customShapes.fillColor = color;\ncustomShapes.fillAlpha = alpha;\n
  • Stroke style
    customShapes.setStrokeStyle(lineWidth, color, alpha);\n
    or
    customShapes.lineWidth = lineWidth;\ncustomShapes.strokeColor = color;\ncustomShapes.strokeAlpha = alpha;\n

Will set dirty and redraw shapes. Apply styles to shapes in update callback.

"},{"location":"shape-custom-shapes/#world-position-to-local-position","title":"World position to local position","text":"
var localXY = customShapes.worldToLocalXY(worldX, worldY); // localXY: {x, y}\n

or

var out = customShapes.worldToLocalXY(worldX, worldY, camera, out);\n
"},{"location":"shape-custom-shapes/#recreate-shapes","title":"Recreate shapes","text":"
  • Clear all shapes
    customShapes.clear();\n
  • Add new shape
    customShapes.createShape(shapeType, name);\n
    • shapeType :
      • 'arc' : Create Arc shape.
      • 'circle' : Create Circle shape.
      • 'ellipse' : Create Ellipse shape.
      • 'line' : Create Line shape.
      • 'lines' : Create Lines shape.
      • 'rectangle' : Create Rectangle shape.
      • 'roundRectangle' : Create Round rectangle shape.
      • 'triangle' : Create Triangle shape.
    • name : A string name of this shape.
"},{"location":"shape-custom-shapes/#refresh","title":"Refresh","text":"

Redraw shapes when

  • Resize : customShapes.resize(width, height)
    • customShapes.isSizeChanged will also be true.
  • Set fill color : customShapes.setFillStyle(color, alpha)
  • Set stroke color : customShapes.setStrokeStyle(lineWidth, color, alpha)
  • Set dirty : customShapes.setDirty()
  • Set update shape callback : customShapes.setUpdateShapesCallback(callback)
"},{"location":"shape-custom-shapes/#update-shape-data","title":"Update shape data","text":"

Shape data will be updated during rendering, or call shape.updateData() to update shape data before rendering.

"},{"location":"shape-custom-shapes/#shape-class","title":"Shape class","text":""},{"location":"shape-custom-shapes/#common-properties","title":"Common properties","text":"
  • Style
    • Get
      var fillColor = shape.fillColor;\nvar fillAlpha = shape.fillAlpha;\nvar lineWidth = shape.lineWidth;\nvar strokeColor = shape.strokeColor;\nvar strokeAlpha = shape.strokeAlpha;\n
    • Set
      shape.fillStyle(color, alpha);\nshape.lineStyle(lineWidth, color, alpha);\n
    • Clear
      shape.fillStyle().lineStyle();\n
  • Visible
    • Get
      var visible = shape.visible;\n
    • Set javascript shape.setVisible(visible);
  • Private data
    • Get
      var data = shape.getData(key);\n// var data = shape.getData(key, defaultValue);\n
    • Set
      shape.setData(key, value);\n
      or
      shape.setData({key:value, ...});\n
    • Inc
      shape.incData(key, incValue);\n// shape.incData(key, incValue, defaultValue);\n
    • Mul
      shape.mulData(key, mulValue);\n// shape.mulData(key, mulValue, defaultValue);\n
    • Clear
      shape.clearData();\n
  • Name
    • Get
      var name = shape.name;\n
"},{"location":"shape-custom-shapes/#line","title":"Line","text":"
  • End points
    • Get
      var x0 = line.x0;\nvar y0 = line.y0;\nvar x1 = line.x1;\nvar y1 = line.y1;\n
    • Set
      line.setP0(x, y);\nline.setP1(x, y);\n
      or
      line.x0 = x0;\nline.y0 = y0;\nline.x1 = x1;\nline.y1 = y1;\n
"},{"location":"shape-custom-shapes/#lines","title":"Lines","text":""},{"location":"shape-custom-shapes/#create-path","title":"Create path","text":"
  • Start, clear points data
    lines.start();\n
  • Start at position, clear points data
    lines.startAt(x, y);\n
  • Line to
    • To position
      lines.lineTo(x, y);\n
    • To relative position
      lines.lineTo(x, y, true);\n
    • To vertical position
      lines.verticalLineTo(x);\n
    • To relative vertical position
      lines.verticalLineTo(x, true);\n
    • To horizontal position
      lines.horizontalLineTo(y);\n
    • To relative horizontal position
      lines.horizontalLineTo(y, true);\n
  • Add arc composed of lines
    lines.arc(centerX, centerY, radius, startAngle, endAngle, anticlockwise);\n
    • startAngle, endAngle : Start and end angle in degrees.
  • Add elliptical arc composed of lines
    lines.ellipticalArc(centerX, centerY, radiusX, radiusY, startAngle, endAngle, anticlockwise);\n
    • startAngle, endAngle : Start and end angle in degrees.
  • Add quadratic bezier of lines
    lines.quadraticBezierTo(cx, cy, x, y);\n
    • cx, cy : Control point
    • x, y : End point
  • Add smooth quadratic bezier of lines
    lines.smoothQuadraticBezierTo(x, y);\n
    • x, y : End point
  • Add cubic bezier of lines
    lines.cubicBezierCurveTo(cx0, cy0, cx1, cy1, x, y);\n
    • cx0, cy0 : Control point0
    • cx1, cy1 : Control point1
    • x, y : End point
  • Add smooth cubic bezier of lines
    lines.smoothCubicBezierCurveTo(cx1, cy1, x, y);\n
    • cx1, cy1 : Control point1
    • x, y : End point
  • End commands
    • Close path, to fill color
      lines.close();\n
    • End path, to draw lines only
      lines.end();\n
  • Copy path from another lines
    lines.copyPathFrom(srcLine);\n
    or
    lines.copyPathFrom(srcLine, startT, endT);\n
  • Append path from another lines
    lines.appendPathFrom(srcLine);\n
    or
    lines.appendPathFrom(srcLine, startT, endT);\n
"},{"location":"shape-custom-shapes/#transform","title":"Transform","text":"
  • Offset all points
    lines.offset(x, y);\n
  • Rotation all points
    lines.rotateAround(centerX, centerY, angle);\n
    • angle : Rotate angle in degrees.
"},{"location":"shape-custom-shapes/#display-path-segment","title":"Display path segment","text":"
  1. Create path, under customShapes.isSizeChanged condition.
  2. Display segment of path
    lines.setDisplayPathSegment(startT, endT);\n
    or
    lines.setDisplayPathSegment(endT);  // startT = 0\n
    • startT, endT : 0~1. Start, end position on path, in percentage of path.
      • 0 : Start position of path
      • 1 : End position of path
"},{"location":"shape-custom-shapes/#misc","title":"Misc","text":"
  • Get polygon
    var polygon = lines.toPolygon();\n
    • Can be used in setInteractive method
      shape.setInteractive({\nhitArea: shape.getShapes()[0].toPolygon(),\nhitAreaCallback: Phaser.Geom.Polygon.Contains,\n})\n
  • Position of first or last point
    var p0x = lines.firstPointX;\nvar p0y = lines.firstPointY;\nvar pNx = lines.lastPointX;\nvar pNy = lines.lastPointY;\n
"},{"location":"shape-custom-shapes/#rectangle","title":"Rectangle","text":"
  • Top-left
    • Get
      var left = rectangle.x;\nvar top = rectangle.y;\n
    • Set
      rectangle.setTopLeftPosition(x, y);\n
      or
      rectangle.x = left;\nrectangle.y = top;\n
  • Center
    • Get
      var centerX = rectangle.centerX;\nvar centerY = rectangle.centerY;\n
    • Set
      rectangle.setCenterPosition(x, y);\n
      or
      rectangle.centerX = centerX;\nrectangle.centerY = centerY;\n
      • Will change rectangle.x, rectangle.y
  • Size
    • Get
      var width = rectangle.width;\nvar height = rectangle.height;\n
    • Set
      rectangle.setSize(width, height);\n
      or
      rectangle.width = width;\nrectangle.height = height;\n
"},{"location":"shape-custom-shapes/#round-rectangle","title":"Round rectangle","text":"
  • Top-left
    • Get
      var left = roundRectangle.x;\nvar top = roundRectangle.y;\n
    • Set
      roundRectangle.setTopLeftPosition(x, y);\n
      or
      roundRectangle.x = left;\nroundRectangle.y = top;\n
  • Center
    • Get
      var centerX = roundRectangle.centerX;\nvar centerY = roundRectangle.centerY;\n
    • Set
      roundRectangle.setCenterPosition(x, y);\n
      or
      roundRectangle.centerX = centerX;\nroundRectangle.centerY = centerY;\n
      • Will change roundRectangle.x, roundRectangle.y
  • Size
    • Get
      var width = roundRectangle.width;\nvar height = roundRectangle.height;\n
    • Set
      roundRectangle.setSize(width, height);\n
      or
      roundRectangle.width = width;\nroundRectangle.height = height;\n
  • Radius
    • Get
      var radius = roundRectangle.radius;\n
      or
      var radiusTL = roundRectangle.radiusTL;\nvar radiusTR = roundRectangle.radiusTR;\nvar radiusBL = roundRectangle.radiusBL;\nvar radiusBR = roundRectangle.radiusBR;\n
    • Set
      roundRectangle.setRadius(radius);\n// roundRectangle.radius = radius;\n
      or
      roundRectangle.setRadius({\ntl: radiusTL, tr: radiusTR,\nbl: radiusBL, br: radiusBR,\n});\n// roundRectangle.radiusTL = radiusTL;\n// roundRectangle.radiusTR = radiusTR;\n// roundRectangle.radiusBL = radiusBL;\n// roundRectangle.radiusBR = radiusBR;\n
      • radius :
        • 0 : No round corner
        • > 0 : Convex round corner
        • < 0 : Concave round corner
"},{"location":"shape-custom-shapes/#triangle","title":"Triangle","text":"
  • Vertices
    • Get
      var x0 = triangle.x0;\nvar y0 = triangle.x0;\nvar x1 = triangle.x1;\nvar y1 = triangle.x1;\nvar x2 = triangle.x2;\nvar y2 = triangle.x2;\n
    • Set
      triangle.setP0(x, y);\ntriangle.setP1(x, y);\ntriangle.setP2(x, y);\n
      or
      triangle.x0 = x0;\ntriangle.x0 = y0;\ntriangle.x1 = x1;\ntriangle.x1 = y1;\ntriangle.x2 = x2;\ntriangle.x2 = y2;\n
"},{"location":"shape-custom-shapes/#arc","title":"Arc","text":"
  • Center position
    • Get
      var x = arc.x;\nvar y = arc.y;\n
    • Set
      arc.setCenterPosition(x, y);\n
      or
      arc.x = x;\narc.y = y;\n
  • Radius
    • Get
      var radiusX = arc.radiusX;\nvar radiusY = arc.radiusY;\n
    • Set
      arc.setRadius(radiusX, radiusY);\n// arc.setRadius(radius);\n
      or
      arc.radiusX = radiusX;\narc.radiusY = radiusY;\n
  • Angles
    • Get
      var startAngle = arc.startAngle;\nvar endAngle = arc.endAngle;\nvar anticlockwise = arc.anticlockwise; // boolean        \n
    • Set
      arc.setAngle(startAngle, endAngle);  // anticlockwise = false\n// arc.setAngle(startAngle, endAngle, anticlockwise);\n
      or
      arc.startAngle = startAngle;\narc.endAngle = endAngle;\narc.anticlockwise = anticlockwise; // boolean\n
      • startAngle, endAngle : Start/end angle in degrees.
  • Pie
    • Get
      var pie = arc.pie; // boolean\n
    • Set
      arc.setPie();\n
      or
      arc.pie = true;\n
"},{"location":"shape-custom-shapes/#circle","title":"Circle","text":"
  • Center position
    • Get
      var x = circle.x;\nvar y = circle.y;\n
    • Set
      circle.setCenterPosition(x, y);\n
      or
      circle.x = x;\ncircle.y = y;\n
  • Radius
    • Get
      var radiusX = circle.radiusX;\nvar radiusY = circle.radiusY;\n
    • Set
      circle.setRadius(radiusX, radiusY);\n// arc.setRadius(radius);\n
      or
      circle.radiusX = radiusX;\ncircle.radiusY = radiusY;\n
"},{"location":"shape-custom-shapes/#ellipse","title":"Ellipse","text":"

The same as Circle.

"},{"location":"shape-custom-shapes/#alpha","title":"Alpha","text":"
  • Get
    var alpha = shape.alpha;\n
  • Set
    shape.setAlpha(alpha);\n// shape.alpha = alpha;\n
"},{"location":"shape-custom-shapes/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-custom-shapes/#create-mask","title":"Create mask","text":"
var mask = shape.createGeometryMask();\n

See mask

"},{"location":"shape-custom-shapes/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-custom-shapes/#compare-with-similar-plugins","title":"Compare with similar plugins","text":"
  • Custom Shapes : Draw shapes.
  • Custom Porgress : Similar with custom-shapes, plus a value property
  • Custom Spinner : Similar with custom-progress, plus a value tween task.
"},{"location":"shape-ellipse/","title":"Ellipse","text":""},{"location":"shape-ellipse/#introduction","title":"Introduction","text":"

Ellipse shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-ellipse/#usage","title":"Usage","text":""},{"location":"shape-ellipse/#create-shape-object","title":"Create shape object","text":"
var ellipse = scene.add.ellipse(x, y, width, height, fillColor);\n// var ellipse = scene.add.ellipse(x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-ellipse/#custom-class","title":"Custom class","text":"
  • Define class
    class MyEllipse extends Phaser.GameObjects.Ellipse {\nconstructor(scene, x, y, width, height, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var ellipse = new MyEllipse(scene, x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-ellipse/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = ellipse.fillColor;\nvar alpha = ellipse.fillAlpha;\n
    • Set
      ellipse.setFillStyle(color, alpha);\n
    • Clear
      ellipse.setFillStyle();\n
  • Stroke color
    • Get
      var color = ellipse.strokeColor;\n
    • Set
      ellipse.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      ellipse.setStrokeStyle();\n

No tint methods

Uses ellipse.setFillStyle(color, alpha) to change color.

"},{"location":"shape-ellipse/#alpha","title":"Alpha","text":"
  • Get
    var alpha = ellipse.alpha;\n
  • Set
    ellipse.setAlpha(alpha);\n// ellipse.alpha = alpha;\n
"},{"location":"shape-ellipse/#size","title":"Size","text":"
  • Get
    var width = ellipse.width;\nvar height = ellipse.height;\n
  • Set
    ellipse.setSize(width, height);\n
"},{"location":"shape-ellipse/#display-size","title":"Display size","text":"
  • Get
    var width = ellipse.displayWidth;\nvar height = ellipse.displayHeight;\n
  • Set
    ellipse.setDisplaySize(width, height);\n
    or
    ellipse.displayWidth = width;\nellipse.displayHeight = height;\n
"},{"location":"shape-ellipse/#smoothness","title":"Smoothness","text":"

The number of points used when rendering it. Increase this value for smoother curves, at the cost of more polygons being rendered.

ellipse.setSmoothness(smoothness);\n
or
ellipse.smoothness = smoothness;\n

"},{"location":"shape-ellipse/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-ellipse/#create-mask","title":"Create mask","text":"
var mask = ellipse.createGeometryMask();\n

See mask

"},{"location":"shape-ellipse/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-fullwindowrectangle/","title":"Full window rectangle","text":""},{"location":"shape-fullwindowrectangle/#introduction","title":"Introduction","text":"

Rectangle shape covered full window.

  • Author: Rex
  • Game object
"},{"location":"shape-fullwindowrectangle/#live-demos","title":"Live demos","text":"
  • Cover
"},{"location":"shape-fullwindowrectangle/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-fullwindowrectangle/#install-plugin","title":"Install plugin","text":""},{"location":"shape-fullwindowrectangle/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexfullwindowrectangleplugin', 'https://raw.githubusercontent.com/rexrainbow/    phaser3-rex-notes/master/dist/rexfullwindowrectangleplugin.min.js', true);\n
  • Add shape object
    var rect = scene.add.rexFullWindowRectangle(fillColor, fillAlpha);\n
"},{"location":"shape-fullwindowrectangle/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FullWindowRectanglePlugin from 'phaser3-rex-plugins/plugins/fullwindowrectangle-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexFullWindowRectanglePlugin',\nplugin: FullWindowRectanglePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add shape object
    var rect = scene.add.rexFullWindowRectangle(fillColor, fillAlpha);\n
"},{"location":"shape-fullwindowrectangle/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import FullWindowRectangle from 'phaser3-rex-plugins/plugins/fullwindowrectangle.js';\n
  • Add shape object
    var rect = new FullWindowRectangle(scene, fillColor, fillAlpha);\nscene.add.existing(rect);\n
"},{"location":"shape-fullwindowrectangle/#create-shape-object","title":"Create shape object","text":"
var rect = scene.add.rexFullWindowRectangle(fillColor, fillAlpha);\n
"},{"location":"shape-fullwindowrectangle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyFullWindowRectangle extends RexPlugins.GameObjects.FullWindowRectangle {\nconstructor(scene, fillColor, fillAlpha) {\nsuper(scene, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var rect = new MyFullWindowRectangle(scene, fillColor, fillAlpha);\n
"},{"location":"shape-fullwindowrectangle/#color","title":"Color","text":"
  • Tint
    • Get
      var tint = rect.tint;\n
    • Set
      rect.tint = tint;\n
  • Alpha
    • Get
      var alpha = rect.alpha;\n
    • Set
      rect.alpha = alpha;\n
  • Fill color
    • Get
      var color = rect.fillColor;\nvar alpha = rect.fillAlpha;\n
    • Set
      rect.setFillStyle(color, alpha);\n
    • Clear
      rect.setFillStyle();\n
"},{"location":"shape-fullwindowrectangle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-fullwindowrectangle/#create-mask","title":"Create mask","text":"
var mask = rect.createGeometryMask();\n

See mask

"},{"location":"shape-fullwindowrectangle/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-grid/","title":"Grid","text":""},{"location":"shape-grid/#introduction","title":"Introduction","text":"

Grid shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-grid/#usage","title":"Usage","text":""},{"location":"shape-grid/#create-shape-object","title":"Create shape object","text":"
var grid = scene.add.grid(x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha);\n
"},{"location":"shape-grid/#custom-class","title":"Custom class","text":"
  • Define class
    class MyGrid extends Phaser.GameObjects.Grid {\nconstructor(scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha) {\nsuper(scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var grid = new MyGrid(scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha);\n
"},{"location":"shape-grid/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = grid.fillColor;\nvar alpha = grid.fillAlpha;\n
    • Set
      grid.setFillStyle(color, alpha);\n
    • Clear
      grid.setFillStyle();\n
  • Stroke color
    • Get
      var color = grid.strokeColor;\n
    • Set
      grid.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      grid.setStrokeStyle();\n
  • Alternating color
    • Get
      var color = grid.altFillColor;\n
    • Set
      grid.setAltFillStyle(color, alpha);\n
    • Clear
      grid.setAltFillStyle();\n
  • Outline color
    • Get
      var color = grid.outlineFillColor;\n
    • Set
      grid.setOutlineStyle(color, alpha;\n
    • Clear
      grid.setOutlineStyle();\n

No tint methods

Uses grid.setFillStyle(color, alpha) to change color.

"},{"location":"shape-grid/#alpha","title":"Alpha","text":"
  • Get
    var alpha = grid.alpha;\n
  • Set
    grid.setAlpha(alpha);\n// grid.alpha = alpha;\n
"},{"location":"shape-grid/#display-size","title":"Display size","text":"
  • Get
    var width = grid.displayWidth;\nvar height = grid.displayHeight;\n
  • Set
    grid.setDisplaySize(width, height);\n
    or
    grid.displayWidth = width;\ngrid.displayHeight = height;\n
"},{"location":"shape-grid/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-grid/#create-mask","title":"Create mask","text":"
var mask = grid.createGeometryMask();\n

See mask

"},{"location":"shape-grid/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-isobox/","title":"Iso box","text":""},{"location":"shape-isobox/#introduction","title":"Introduction","text":"

Iso-box shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-isobox/#usage","title":"Usage","text":""},{"location":"shape-isobox/#create-shape-object","title":"Create shape object","text":"
var isoBox = scene.add.isobox(x, y, width, height, fillTop, fillLeft, fillRight);\n
"},{"location":"shape-isobox/#custom-class","title":"Custom class","text":"
  • Define class
    class MyIsoBox extends Phaser.GameObjects.IsoBox {\nconstructor(scene, x, y, width, height, fillTop, fillLeft, fillRight) {\nsuper(scene, x, y, width, height, fillTop, fillLeft, fillRight);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var isoBox = new MyIsoBox(scene, x, y, width, height, fillTop, fillLeft, fillRight);\n
"},{"location":"shape-isobox/#set-color","title":"Set color","text":"
  • Fill color
    isoBox.setFillStyle(fillTop, fillLeft, fillRight);\n
  • Show face
    isoBox.setFaces(showTop, showLeft, showRight);\n
    • showTop, showLeft, showRight: Set true to show that face

No tint methods

Uses isoBox.setFillStyle(fillTop, fillLeft, fillRight) to change color.

"},{"location":"shape-isobox/#alpha","title":"Alpha","text":"
  • Get
    var alpha = isoBox.alpha;\n
  • Set
    isoBox.setAlpha(alpha);\n// isoBox.alpha = alpha;\n
"},{"location":"shape-isobox/#projection","title":"Projection","text":"
  • Get
    var projection = isoBox.projection;\n
  • Set
    isoBox.setProjection(value)\n
    or
    isoBox.projection = value;\n
"},{"location":"shape-isobox/#display-size","title":"Display size","text":"
  • Get
    var width = isoBox.displayWidth;\nvar height = isoBox.displayHeight;\n
  • Set
    isoBox.setDisplaySize(width, height);\n
    or
    isoBox.displayWidth = width;\nisoBox.displayHeight = height;\n
"},{"location":"shape-isobox/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-isobox/#create-mask","title":"Create mask","text":"
var mask = isoBox.createGeometryMask();\n

See mask

"},{"location":"shape-isobox/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-isotriangle/","title":"Iso triangle","text":""},{"location":"shape-isotriangle/#introduction","title":"Introduction","text":"

Iso-triangle shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-isotriangle/#usage","title":"Usage","text":""},{"location":"shape-isotriangle/#create-shape-object","title":"Create shape object","text":"
var isoTriangle = scene.add.isotriangle(x, y, width, height, reversed, fillTop, fillLeft, fillRight);\n
"},{"location":"shape-isotriangle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyIsoTriangle extends Phaser.GameObjects.IsoTriangle {\nconstructor(scene, x, y, width, height, reversed, fillTop, fillLeft, fillRight) {\nsuper(scene, x, y, width, height, reversed, fillTop, fillLeft, fillRight);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var isoTriangle = new MyIsoTriangle(scene, x, y, width, height, reversed, fillTop, fillLeft, fillRight);\n
"},{"location":"shape-isotriangle/#set-color","title":"Set color","text":"
  • Fill color
    isoTriangle.setFillStyle(fillTop, fillLeft, fillRight);\n
  • Show face
    isoTriangle.setFaces(showTop, showLeft, showRight);\n
    • showTop, showLeft, showRight: Set true to show that face

No tint methods

Uses isoTriangle.setFillStyle(fillTop, fillLeft, fillRight) to change color.

"},{"location":"shape-isotriangle/#alpha","title":"Alpha","text":"
  • Get
    var alpha = isoTriangle.alpha;\n
  • Set
    isoTriangle.setAlpha(alpha);\n// isoTriangle.alpha = alpha;\n
"},{"location":"shape-isotriangle/#projection","title":"Projection","text":"
  • Get
    var projection = isoTriangle.projection;\n
  • Set
    isoTriangle.setProjection(value)\n
    or
    isoTriangle.projection = value;\n
"},{"location":"shape-isotriangle/#reverse","title":"Reverse","text":"
  • Get
    var isReversed = isoTriangle.isReversed;\n
  • Set
    isoTriangle.setReversed(reversed);\n
    or
    isoTriangle.reversed = reversed;\n
  • Set true to render upside down.
"},{"location":"shape-isotriangle/#display-size","title":"Display size","text":"
  • Get
    var width = isoTriangle.displayWidth;\nvar height = isoTriangle.displayHeight;\n
  • Set
    isoTriangle.setDisplaySize(width, height);\n
    or
    isoTriangle.displayWidth = width;\nisoTriangle.displayHeight = height;\n
"},{"location":"shape-isotriangle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-isotriangle/#create-mask","title":"Create mask","text":"
var mask = isoTriangle.createGeometryMask();\n

See mask

"},{"location":"shape-isotriangle/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-line/","title":"Line","text":""},{"location":"shape-line/#introduction","title":"Introduction","text":"

Line shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-line/#usage","title":"Usage","text":""},{"location":"shape-line/#create-shape-object","title":"Create shape object","text":"
var line = scene.add.line(x, y, x1, y1, x2, y2, strokeColor);\n// var line = scene.add.line(x, y, x1, y1, x2, y2, strokeColor, strokeAlpha);\n
"},{"location":"shape-line/#custom-class","title":"Custom class","text":"
  • Define class
    class MyCurve extends Phaser.GameObjects.Line {\nconstructor(scene, x, y, x1, y1, x2, y2, strokeColor) {\nsuper(scene, x, y, x1, y1, x2, y2, strokeColor);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var line = new MyLine(scene, x, y, x1, y1, x2, y2, strokeColor);\n
"},{"location":"shape-line/#set-color","title":"Set color","text":"
  • Fill color
    • Get
      var color = line.fillColor;\nvar alpha = line.fillAlpha;\n
    • Set
      line.setFillStyle(color, alpha);\n
    • Clear
      line.setFillStyle();\n
  • Stroke color
    • Get
      var color = line.strokeColor;\n
    • Set
      line.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      line.setStrokeStyle();\n

No tint methods

Uses line.setFillStyle(color, alpha) to change color.

"},{"location":"shape-line/#alpha","title":"Alpha","text":"
  • Get
    var alpha = line.alpha;\n
  • Set
    line.setAlpha(alpha);\n// line.alpha = alpha;\n
"},{"location":"shape-line/#set-end-points","title":"Set end points","text":"
line.setTo(x1, y1, x2, y2);\n
"},{"location":"shape-line/#line-width","title":"Line width","text":"
line.setLineWidth(startWidth, endWidth);\n
  • endWidth : The end width of the line. Only used in WebGL.
"},{"location":"shape-line/#display-size","title":"Display size","text":"
  • Get
    var width = line.displayWidth;\nvar height = line.displayHeight;\n
  • Set
    line.setDisplaySize(width, height);\n
    or
    line.displayWidth = width;\nline.displayHeight = height;\n
"},{"location":"shape-line/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-line/#create-mask","title":"Create mask","text":"
var mask = line.createGeometryMask();\n

See mask

"},{"location":"shape-line/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-lineprogress/","title":"Line progress","text":""},{"location":"shape-lineprogress/#introduction","title":"Introduction","text":"

Horizontal line progress bar shape.

  • Author: Rex
  • Game object
"},{"location":"shape-lineprogress/#live-demos","title":"Live demos","text":"
  • Line-progress
"},{"location":"shape-lineprogress/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-lineprogress/#install-plugin","title":"Install plugin","text":""},{"location":"shape-lineprogress/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexlineprogressplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexlineprogressplugin.min.js', true);\n
  • Add line-progress object
    var lineProgress = scene.add.rexLineProgress(x, y, width, height, barColor, value, config);\n
"},{"location":"shape-lineprogress/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import LineProgressPlugin from 'phaser3-rex-plugins/plugins/lineprogress-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLineProgressPlugin',\nplugin: LineProgressPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add line-progress object
    var lineProgress = scene.add.rexLineProgress(x, y, width, height, barColor, value, config);\n
"},{"location":"shape-lineprogress/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import LineProgress from 'phaser3-rex-plugins/plugins/lineprogress.js';\n
  • Add line-progress object
    var lineProgress = new LineProgress(scene, x, y, width, height, barColor, value, config);\nscene.add.existing(lineProgress);\n
"},{"location":"shape-lineprogress/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexLineProgressPlugin',\nplugin: LineProgressPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"shape-lineprogress/#create-instance","title":"Create instance","text":"
var lineProgress = scene.add.rexLineProgress(x, y, width, height, barColor, value, {    trackColor: undefined,\ntrackStrokeColor: undefined,\ntrackStrokeThickness: 2,\n\nskewX:0,\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, lineProgress) {\n},\n});\n

or

var lineProgress = scene.add.rexLineProgress({\nx: 0,\ny: 0,\nwidth: 2,\nheight: 2,\n\nbarColor: undefined,\ntrackColor: undefined,\ntrackStrokeColor: undefined,\ntrackStrokeThickness: 2,\n\nskewX:0,\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvalue: 0,\nvaluechangeCallback: function(newValue, oldValue, lineProgress) {\n},\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • barColor : Fill color of line bar, in number or css string value.
  • trackColor : Fill color of line track, in number or css string value.
  • trackStrokeColor : Stroke color of track, in number or css string value.
  • trackStrokeThickness : Stroke line width of track.
  • skewX : Horizontal skew of track and bar.
  • rtl :
    • false : Bar starts from left side. Default behavior.
    • true : Bar starts from right side.
  • value : 0 ~ 1, progress value. Default is 0.
  • easeValue : Parameters of easing value.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • valuechangeCallback : callback function when value changed.
    function(newValue, oldValue, lineProgress) {\n}\n

Add line-progress from JSON

var lineProgress = scene.make.rexLineProgress({\nx: 0,\ny: 0,\nwidth: 2,\nheight: 2,\n\nbarColor: undefined,\ntrackColor: undefined,\ntrackStrokeColor: undefined,\ntrackStrokeThickness: 2,\n\nskewX:0,\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvalue: 0,\nvaluechangeCallback: function(newValue, oldValue, lineProgress) {\n},\n\nadd: true\n});\n
"},{"location":"shape-lineprogress/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLineProgress extends LineProgress {\nconstructor(scene, x, y, width, height, barColor, value, config) {\nsuper(scene, x, y, width, height, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var lineProgress = new MyLineProgress(scene, x, y, width, height, barColor, value, config);\n
"},{"location":"shape-lineprogress/#progress-value","title":"Progress value","text":"
  • Get value
    var value = lineProgress.getValue(min, max); // value : min ~ max\n
    or
    var value = lineProgress.getValue(); // value: 0 ~ 1\n
    or
    var value = lineProgress.value; // value: 0 ~ 1\n
  • Set value
    lineProgress.setValue(value, min, max); // value: min ~ max\n
    or
    lineProgress.setValue(value); // value: 0 ~ 1\n
    or
    lineProgress.value = value; // value: 0 ~ 1\n
  • Increase value
    lineProgress.addValue(inc, min, max); // inc: min ~ max\n
    or
    lineProgress.addValue(inc); // inc: 0 ~ 1\n
    or
    lineProgress.value += inc; // inc: 0 ~ 1\n
"},{"location":"shape-lineprogress/#ease-progress-value","title":"Ease progress value","text":"
  • Ease value to
    lineProgress.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    lineProgress.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    lineProgress.stopEaseValue();\n
  • Set ease duration
    lineProgress.setEaseValueDuration(duration);\n
  • Set ease function
    lineProgress.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"shape-lineprogress/#line-track","title":"Line track","text":"
  • Color
    • Get
      var trackColor = lineProgress.trackColor;\n
    • Set
      lineProgress.setTrackColor(trackColor);\n// lineProgress.trackColor = trackColor;\n
  • Stroke
    • Get
      var trackStrokeColor = lineProgress.trackStrokeColor;\nvar trackStrokeThickness = lineProgress.trackStrokeThickness;\n
    • Set
      lineProgress.setTrackColor(color);\nlineProgress.setTrackStroke(lineWidth, color);\n
"},{"location":"shape-lineprogress/#line-bar","title":"Line bar","text":"
  • Color
    • Get
      var barColor = lineProgress.barColor;\n
    • Set
      lineProgress.setBarColor(barColor);\n// lineProgress.barColor = barColor;\n
"},{"location":"shape-lineprogress/#horizontal-skew","title":"Horizontal skew","text":"
  • Get
    var skewX = lineProgress.skewX;\n
  • Set
    lineProgress.setSkewX(skewX);\n// lineProgress.skewX = skewX;\n
"},{"location":"shape-lineprogress/#right-to-left","title":"Right-to-left","text":"
  • Get
    var rtl = lineProgress.rtl;\n
  • Set
    lineProgress.setRTL(rtl);\n// lineProgress.rtl = rtl;\n
"},{"location":"shape-lineprogress/#events","title":"Events","text":"
  • On value changed
    lineProgress.on('valuechange', function(newValue, oldValue, lineProgress){\n//\n}, scope);\n
"},{"location":"shape-lineprogress/#alpha","title":"Alpha","text":"
  • Get
    var alpha = lineProgress.alpha;\n
  • Set
    lineProgress.setAlpha(alpha);\n// lineProgress.alpha = alpha;\n
"},{"location":"shape-lineprogress/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-lineprogress/#create-mask","title":"Create mask","text":"
var mask = lineProgress.createGeometryMask();\n

See mask

"},{"location":"shape-lineprogress/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-polygon/","title":"Polygon","text":""},{"location":"shape-polygon/#introduction","title":"Introduction","text":"

Polygon shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-polygon/#usage","title":"Usage","text":""},{"location":"shape-polygon/#create-shape-object","title":"Create shape object","text":"
var polygon = scene.add.polygon(x, y, points, fillColor);\n// var polygon = scene.add.polygon(x, y, points, fillColor, fillAlpha);\n
  • points :
    • An array of number : [x0, y0, x1, y1, ...]
    • An array of points : [{x:x0, y:y0}, {x:x1, y:y1}, ...]
    • A string : 'x0 y0 x1 y1 ...'

Note

Shift given points to align position (0, 0)

"},{"location":"shape-polygon/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPolygon extends Phaser.GameObjects.Polygon {\nconstructor(scene, x, y, points, fillColor) {\nsuper(scene, x, y, points, fillColor);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var polygon = new MyPolygon(scene, x, y, points, fillColor);\n
"},{"location":"shape-polygon/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = polygon.fillColor;\nvar alpha = polygon.fillAlpha;\n
    • Set
      polygon.setFillStyle(color, alpha);\n
    • Clear
      polygon.setFillStyle();\n
  • Stroke color
    • Get
      var color = polygon.strokeColor;\n
    • Set
      polygon.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      polygon.setStrokeStyle();\n

No tint methods

Uses polygon.setFillStyle(color, alpha) to change color.

"},{"location":"shape-polygon/#alpha","title":"Alpha","text":"
  • Get
    var alpha = polygon.alpha;\n
  • Set
    polygon.setAlpha(alpha);\n// polygon.alpha = alpha;\n
"},{"location":"shape-polygon/#smooth","title":"Smooth","text":"

Smooths the polygon over the number of iterations specified.

polygon.smooth(iterations);\n
"},{"location":"shape-polygon/#set-points","title":"Set points","text":"
polygon.setTo(points);\n
  • point :
    • A string containing paired values separated by a single space : '40 0 40 20 100 20 100 80 40 80 40 100 0 50'
    • An array of Point objects : [new Phaser.Point(x1, y1), ...]
    • An array of objects with public x/y properties : [obj1, obj2, ...]
    • An array of paired numbers that represent point coordinates : [x1,y1, x2,y2, ...]
    • An array of arrays with two elements representing x/y coordinates : [[x1, y1], [x2, y2], ...]
"},{"location":"shape-polygon/#display-size","title":"Display size","text":"
  • Get
    var width = polygon.displayWidth;\nvar height = polygon.displayHeight;\n
  • Set
    polygon.setDisplaySize(width, height);\n
    or
    polygon.displayWidth = width;\npolygon.displayHeight = height;\n
"},{"location":"shape-polygon/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-polygon/#create-mask","title":"Create mask","text":"
var mask = polygon.createGeometryMask();\n

See mask

"},{"location":"shape-polygon/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-quad/","title":"Quad","text":""},{"location":"shape-quad/#introduction","title":"Introduction","text":"

Quad shape, offsets can be given on four vertices, and additional points can be added on the four sides.

  • Author: Rex
  • Game object
"},{"location":"shape-quad/#live-demos","title":"Live demos","text":"
  • Ease vertices
  • Ease side-points
"},{"location":"shape-quad/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-quad/#install-plugin","title":"Install plugin","text":""},{"location":"shape-quad/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquadshapeplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquadshapeplugin.min.js', true);\n
  • Add shape object
    var quad = scene.add.rexQuadShape(x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-quad/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuadShapePlugin from 'phaser3-rex-plugins/plugins/quadshape-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuadShapePlugin',\nplugin: QuadShapePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add shape object
    var quad = scene.add.rexQuadShape(x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-quad/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import QuadShape from 'phaser3-rex-plugins/plugins/quadshape.js';\n
  • Add shape object
    var quad = new QuadShape(scene, x, y, width, height, fillColor, fillAlpha);\nscene.add.existing(quad);\n
"},{"location":"shape-quad/#create-shape-object","title":"Create shape object","text":"
var quad = scene.add.rexQuadShape(x, y, width, height, fillColor, fillAlpha);\n

or

var quad = scene.add.rexQuadShape({\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\n\ncolor: undefined,\nalpha: undefined,\n\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: 2,\n\ntlx: 0,\ntly: 0,\ntrx: 0,\ntry: 0,\nblx: 0,\nbly: 0,\nbrx: 0,\nbry: 0,\n\nleftSidePoints: [\n// {t, x, y, key},\n// {t, x, y, key},\n// ...\n],\nrightSidePoints: [\n// {t, x, y, key},\n// {t, x, y, key},\n// ...\n],\ntopSidePoints: [\n// {t, x, y, key},\n// {t, x, y, key},\n// ...\n],\nbottomSidePoints: [\n// {t, x, y, key},\n// {t, x, y, key},\n// ...\n],\n});\n
  • width, height : Size of quadangle.
    • undefined : Set ot undefined to draw a circle.
  • tlx, tly : Offset of top-left vertex.
  • trx, try : Offset of top-right vertex.
  • blx, bly : Offset of bottom-left vertex.
  • brx, bry : Offset of bottom-right vertex.
  • leftSidePoints, rightSidePoints, topSidePoints, bottomSidePoints : A list of points, additional points on left-side/right-side/top-side/bottom-side.
    {\nt, x, y, key\n}\n
    • t : Position in percent of edge.
    • x, y : Offset of this point on edge.
    • key :
      • undefined : Ignore this feature. Default value.
      • A string: Inject key+'\uff38', key+'Y', key+'T' properties into this quad shape game object.
"},{"location":"shape-quad/#custom-class","title":"Custom class","text":"
  • Define class
    class MyQuadShape extends RexPlugins.GameObjects.QuadShape {\nconstructor(scene, x, y, width, height, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var quad = new MyQuadShape(scene, x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-quad/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = quad.fillColor;\nvar alpha = quad.fillAlpha;\n
    • Set
      quad.setFillStyle(color, alpha);\n
    • Clear
      quad.setFillStyle();\n
  • Stroke color
    • Get
      var color = quad.strokeColor;\n
    • Set
      quad.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      quad.setStrokeStyle();\n

No tint methods

Uses quad.setFillStyle(color, alpha) to change color.

"},{"location":"shape-quad/#alpha","title":"Alpha","text":"
  • Get
    var alpha = quad.alpha;\n
  • Set
    quad.setAlpha(alpha);\n// quad.alpha = alpha;\n
"},{"location":"shape-quad/#size","title":"Size","text":"
  • Get
    var width = quad.width;\nvar height = quad.height;\n
  • Set
    quad.setSize(width, height);\n
    or
    quad.width = width;\nquad.height = height;\n
"},{"location":"shape-quad/#display-size","title":"Display size","text":"
  • Get
    var width = quad.displayWidth;\nvar height = quad.displayHeight;\n
  • Set
    quad.setDisplaySize(width, height);\n
    or
    quad.displayWidth = width;\nquad.displayHeight = height;\n
"},{"location":"shape-quad/#position-of-vertices","title":"Position of vertices","text":"
  • Top-left vertex
    • Get
      var x = quad.tlx;\nvar y = quad.tly;\n
    • Set
      quad.setTLPosition(x, y);\n
      or
      quad.tlx = x;\nquad.tly = y;\n
  • Top-right vertex
    • Get
      var x = quad.trx;\nvar y = quad.try;\n
    • Set
      quad.setTRPosition(x, y);\n
      or
      quad.trx = x;\nquad.try = y;\n
  • Bottom-left vertex
    • Get
      var x = quad.blx;\nvar y = quad.bly;\n
    • Set
      quad.setBLPosition(x, y);\n
      or
      quad.blx = x;\nquad.bly = y;\n
  • Bottom-right vertex
    • Get
      var x = quad.brx;\nvar y = quad.bry;\n
    • Set
      quad.setBRPosition(x, y);\n
      or
      quad.brx = x;\nquad.bry = y;\n
"},{"location":"shape-quad/#position-of-side-points","title":"Position of side points","text":"
  • Top side
    quad.insertTopSidePoint(t, x, y);\n// quad.insertTopSidePoint(t, x, y, key);\n// quad.insertTopSidePoint({t, x, y, key});\n
    • t : Position in percent of edge.
    • x, y : Offset of this point on edge.
    • key : - undefined : Ignore this feature. Default value. - A string: Inject key+'\uff38', key+'Y', key+'T' properties into this quad shape game object.
  • Right side
    quad.insertRightSidePoint(t, x, y);\n// quad.insertRightSidePoint(t, x, y, key);\n// quad.insertRightSidePoint({t, x, y, key});\n
    • t : Position in percent of edge.
    • x, y : Offset of this point on edge.
    • key : - undefined : Ignore this feature. Default value. - A string: Inject key+'\uff38', key+'Y', key+'T' properties into this quad shape game object.
  • Bottom side
    quad.insertBottomSidePoint(t, x, y);\n// quad.insertBottomSidePoint(t, x, y, key);\n// quad.insertBottomSidePoint({t, x, y, key});\n
    • t : Position in percent of edge.
    • x, y : Offset of this point on edge.
    • key : - undefined : Ignore this feature. Default value. - A string: Inject key+'\uff38', key+'Y', key+'T' properties into this quad shape game object.
  • Left side
    quad.insertLeftSidePoint(t, x, y);\n// quad.insertLeftSidePoint(t, x, y, key);\n// quad.insertLeftSidePoint({t, x, y, key});\n
    • t : Position in percent of edge.
    • x, y : Offset of this point on edge.
    • key : - undefined : Ignore this feature. Default value. - A string: Inject key+'\uff38', key+'Y', key+'T' properties into this quad shape game object.
"},{"location":"shape-quad/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-quad/#create-mask","title":"Create mask","text":"
var mask = quad.createGeometryMask();\n

See mask

"},{"location":"shape-quad/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-rectangle/","title":"Rectangle","text":""},{"location":"shape-rectangle/#introduction","title":"Introduction","text":"

Rectangle shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-rectangle/#usage","title":"Usage","text":""},{"location":"shape-rectangle/#create-shape-object","title":"Create shape object","text":"
var rect = scene.add.rectangle(x, y, width, height, fillColor);\n// var rect = scene.add.rectangle(x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-rectangle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyRectangle extends Phaser.GameObjects.Rectangle {\nconstructor(scene, x, y, width, height, fillColor) {\nsuper(scene, x, y, width, height, fillColor);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var rect = new MyRectangle(scene, x, y, width, height, fillColor);\n
"},{"location":"shape-rectangle/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = rect.fillColor;\nvar alpha = rect.fillAlpha;\n
    • Set
      rect.setFillStyle(color, alpha);        
    • Clear
      rect.setFillStyle();\n
  • Stroke color
    • Get
      var color = rect.strokeColor;\n
    • Set
      rect.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      rect.setStrokeStyle();\n

No tint methods

Uses rect.setFillStyle(color, alpha) to change color.

"},{"location":"shape-rectangle/#alpha","title":"Alpha","text":"
  • Get
    var alpha = rect.alpha;\n
  • Set
    rect.setAlpha(alpha);\n// rect.alpha = alpha;\n
"},{"location":"shape-rectangle/#size","title":"Size","text":"
  • Get
    var width = rect.width;\nvar height = rect.height;\n
  • Set
    rect.setSize(width, height);\n
    or
    rect.width = width;\nrect.height = height;\n
"},{"location":"shape-rectangle/#display-size","title":"Display size","text":"
  • Get
    var width = rect.displayWidth;\nvar height = rect.displayHeight;\n
  • Set
    rect.setDisplaySize(width, height);\n
    or
    rect.displayWidth = width;\nrect.displayHeight = height;\n
"},{"location":"shape-rectangle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-rectangle/#create-mask","title":"Create mask","text":"
var mask = rect.createGeometryMask();\n

See mask

"},{"location":"shape-rectangle/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-roundrectangle/","title":"Round Rectangle","text":""},{"location":"shape-roundrectangle/#introduction","title":"Introduction","text":"

Round rectangle shape.

  • Author: Rex
  • Game object
"},{"location":"shape-roundrectangle/#live-demos","title":"Live demos","text":"
  • Round rectangle
"},{"location":"shape-roundrectangle/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-roundrectangle/#install-plugin","title":"Install plugin","text":""},{"location":"shape-roundrectangle/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexroundrectangleplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexroundrectangleplugin.min.js', true);\n
  • Add shape object
    var rect = scene.add.rexRoundRectangle(x, y, width, height, radius, fillColor, fillAlpha);\n
"},{"location":"shape-roundrectangle/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import RoundRectanglePlugin from 'phaser3-rex-plugins/plugins/roundrectangle-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexRoundRectanglePlugin',\nplugin: RoundRectanglePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add shape object
    var rect = scene.add.rexRoundRectangle(x, y, width, height, radius, fillColor, fillAlpha);\n
"},{"location":"shape-roundrectangle/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import RoundRectangle from 'phaser3-rex-plugins/plugins/roundrectangle.js';\n
  • Add shape object
    var rect = new RoundRectangle(scene, x, y, width, height, radius, fillColor, fillAlpha);\nscene.add.existing(rect);\n
"},{"location":"shape-roundrectangle/#create-shape-object","title":"Create shape object","text":"
var rect = scene.add.rexRoundRectangle(x, y, width, height, radius, fillColor, fillAlpha);\n

or

var rect = scene.add.rexRoundRectangle({\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\nradius: 0,\n\ncolor: undefined,\nalpha: undefined,\n\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: 2\n});\n
  • width, height : Size of rectangle.
    • undefined : Set ot undefined to draw a circle.
  • radius : Radius of four corners.
    • 0, or undefined : Disable round corner.
    • Number: 4 corners with the same radius.
    • JSON
      • 4 corners with the same radius X/Y
        {\nx: radiusX,\ny: radiusY\n}\n
      • Eeach radius of corner
        {\ntl: radius,\ntr: radius,\nbl: radius,\nbr: radius\n}\n
        or
        {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n}\n
      • Radius and iteration
        {\nradius: radius,\niteration: 0\n}\n
        or
        {\nradius: {x: radiusX, y: radiusY},\niteration: 0\n}\n
        or
        {\nradius: {\ntl: {x : radiusX, y: radiusY},\ntr: {x : radiusX, y: radiusY},\nbl: {x : radiusX, y: radiusY},\nbr: {x : radiusX, y: radiusY},\n},\niteration: 0\n}\n
        • radius :
          • 0 : No round corner
          • > 0 : Convex round corner
          • < 0 : Concave round corner
        • iteration : Number of interpolation points in each round corner. Default value is 4.
          • 0 : Draw a straight line instead of arc.
"},{"location":"shape-roundrectangle/#deform","title":"Deform","text":"
  • Rectangle, set radius of 4 corners to 0.
    var rect = scene.add.rexRoundRectangle(x, y,  width, height, 0, fillColor, fillAlpha);\n
  • Circle, set width and height to undefined.
    var rect = scene.add.rexRoundRectangle(x, y, undefined, undefined, radius, fillColor, fillAlpha);\n
  • Ellipse, set width and height to undefined, and radiusX/radiusY.
    var rect = scene.add.rexRoundRectangle(x, y, undefined, undefined, {x: radiusX, y: radiusY}, fillColor, fillAlpha);\n
  • Rhombus, set width and height to undefined, and assign iteration to 0
    var rect = scene.add.rexRoundRectangle(x, y, undefined, undefined, {\nradius: radius,\niteration: 0\n}, fillColor, fillAlpha);\n
  • Octagon, assign iteration to 0
    var rect = scene.add.rexRoundRectangle(x, y, width, height, {\nradius: radius,\niteration: 0\n}, fillColor, fillAlpha);\n
"},{"location":"shape-roundrectangle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyRoundRectangle extends RexPlugins.GameObjects.RoundRectangle {\nconstructor(scene, x, y, width, height, radius, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, radius, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var rect = new MyRoundRectangle(scene, x, y, width, height, radius, fillColor, fillAlpha);\n
"},{"location":"shape-roundrectangle/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = rect.fillColor;\nvar alpha = rect.fillAlpha;\n
    • Set
      rect.setFillStyle(color, alpha);\n
    • Clear
      rect.setFillStyle();\n
  • Stroke color
    • Get
      var color = rect.strokeColor;\n
    • Set
      rect.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      rect.setStrokeStyle();\n

No tint methods

Uses rect.setFillStyle(color, alpha) to change color.

"},{"location":"shape-roundrectangle/#alpha","title":"Alpha","text":"
  • Get
    var alpha = rect.alpha;\n
  • Set
    rect.setAlpha(alpha);\n// rect.alpha = alpha;\n
"},{"location":"shape-roundrectangle/#size","title":"Size","text":"
  • Get
    var width = rect.width;\nvar height = rect.height;\n
  • Set
    rect.setSize(width, height);\n
    or
    rect.width = width;\nrect.height = height;\n
"},{"location":"shape-roundrectangle/#display-size","title":"Display size","text":"
  • Get
    var width = rect.displayWidth;\nvar height = rect.displayHeight;\n
  • Set
    rect.setDisplaySize(width, height);\n
    or
    rect.displayWidth = width;\nrect.displayHeight = height;\n
"},{"location":"shape-roundrectangle/#radius","title":"Radius","text":"
  • Get
    var radius = rect.radius;\nvar radiusTL = rect.radiusTL;\nvar radiusTR = rect.radiusTR;\nvar radiusBL = rect.radiusBL;\nvar radiusBR = rect.radiusBR;\n
    or
    var cornerRadius = rect.cornerRadius;\n
    • radius : Number, maximum radius of 4 corners.
    • cornerRadius : JSON object of 4 corners.
      {\ntl: {x : radiusX, y: radiusY, convex : true},\ntr: {x : radiusX, y: radiusY, convex : true},\nbl: {x : radiusX, y: radiusY, convex : true},\nbr: {x : radiusX, y: radiusY, convex : true},\n}\n
  • Set
    rect.setRadius(value);\nrect.setRadiusTL(value);  // number, or {x,y}\nrect.setRadiusTR(value);  // number, or {x,y}\nrect.setRadiusBL(value);  // number, or {x,y}\nrect.setRadiusBR(value);  // number, or {x,y}\n
    or
    rect.radius = radius;\nrect.radiusTL = radius;  // number, or {x,y}\nrect.radiusTR = radius;  // number, or {x,y}\nrect.radiusBL = radius;  // number, or {x,y}\nrect.radiusBR = radius;  // number, or {x,y}\n
    • radius :
      • Number : 4 corners with the same radius.
        • 0 : No round corner
        • > 0 : Convex round corner
        • < 0 : Concave round corner
      • JSON
        • 4 corners with the same radius X/Y
          {\nx: radiusX,\ny: radiusY\n}\n
        • Eeach radius of corner
          {\ntl: radius,\ntr: radius,\nbl: radius,\nbr: radius\n}\n
          or ```javascript { tl: {x : radiusX, y: radiusY}, tr: {x : radiusX, y: radiusY}, bl: {x : radiusX, y: radiusY}, br: {x : radiusX, y: radiusY}, }
"},{"location":"shape-roundrectangle/#iteration","title":"Iteration","text":"
  • Get
    var iteration = rect.iteration;\n
  • Set
    rect.setIteration(value);\n
    or
    rect.iteration = value;\n

Number of interpolation points in each round corner. Default value is 4.

  • 0 : Draw a straight line instead of arc.
"},{"location":"shape-roundrectangle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-roundrectangle/#create-mask","title":"Create mask","text":"
var mask = rect.createGeometryMask();\n

See mask

"},{"location":"shape-roundrectangle/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-spinner/","title":"Spinner","text":""},{"location":"shape-spinner/#introduction","title":"Introduction","text":"

Loading animations on shape.

  • Author: Rex
  • Game object
"},{"location":"shape-spinner/#live-demos","title":"Live demos","text":"
  • Spinners
    • Arrow
    • AIO
  • Custom spinner
  • Loading animation
"},{"location":"shape-spinner/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-spinner/#install-plugin","title":"Install plugin","text":""},{"location":"shape-spinner/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin(\n\"rexspinnerplugin\",\n\"https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexspinnerplugin.min.js\",\n\"rexSpinner\",\n\"rexSpinner\"\n);\n
  • Add spinner object
    var aio = scene.rexSpinner.add.aio(config);\nvar arrow = scene.rexSpinner.add.arrow(config);\nvar downArrow = scene.rexSpinner.add.downArrow(config);\nvar leftArrow = scene.rexSpinner.add.leftArrow(config);\nvar rightArrow = scene.rexSpinner.add.rightArrow(config);\nvar upArrow = scene.rexSpinner.add.upArrow(config);\nvar audio = scene.rexSpinner.add.audio(config);\nvar ball = scene.rexSpinner.add.ball(config);\nvar bars = scene.rexSpinner.add.bars(config);\nvar box = scene.rexSpinner.add.box(config);\nvar clock = scene.rexSpinner.add.clock(config);\nvar cube = scene.rexSpinner.add.cube(config);\nvar dots = scene.rexSpinner.add.dots(config);\nvar facebook = scene.rexSpinner.add.facebook(config);\nvar grid = scene.rexSpinner.add.grid(config);\nvar hearts = scene.rexSpinner.add.hearts(config);\nvar ios = scene.rexSpinner.add.ios(config);\nvar orbit = scene.rexSpinner.add.orbit(config);\nvar oval = scene.rexSpinner.add.oval(config);\nvar pie = scene.rexSpinner.add.pie(config);\nvar puff = scene.rexSpinner.add.puff(config);\nvar radio = scene.rexSpinner.add.radio(config);\nvar rings = scene.rexSpinner.add.rings(config);\nvar spinner = scene.rexSpinner.add.spinner(config);\n
"},{"location":"shape-spinner/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SpinnerPlugin from \"phaser3-rex-plugins/templates/spinner/spinner-plugin.js\";\nvar config = {\n// ...\nplugins: {\nscene: [\n{\nkey: \"rexSpinner\",\nplugin: SpinnerPlugin,\nmapping: \"rexSpinner\",\n},\n// ...\n],\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add spinner object
    var aio = scene.rexSpinner.add.aio(config);\nvar arrow = scene.rexSpinner.add.arrow(config);\nvar downArrow = scene.rexSpinner.add.downArrow(config);\nvar leftArrow = scene.rexSpinner.add.leftArrow(config);\nvar rightArrow = scene.rexSpinner.add.rightArrow(config);\nvar upArrow = scene.rexSpinner.add.upArrow(config);  var audio = scene.rexSpinner.add.audio(config);\nvar ball = scene.rexSpinner.add.ball(config);\nvar bars = scene.rexSpinner.add.bars(config);\nvar box = scene.rexSpinner.add.box(config);\nvar clock = scene.rexSpinner.add.clock(config);\nvar cube = scene.rexSpinner.add.cube(config);\nvar dots = scene.rexSpinner.add.dots(config);\nvar facebook = scene.rexSpinner.add.facebook(config);\nvar grid = scene.rexSpinner.add.grid(config);\nvar hearts = scene.rexSpinner.add.hearts(config);\nvar ios = scene.rexSpinner.add.ios(config);\nvar orbit = scene.rexSpinner.add.orbit(config);\nvar oval = scene.rexSpinner.add.oval(config);\nvar pie = scene.rexSpinner.add.pie(config);\nvar puff = scene.rexSpinner.add.puff(config);\nvar radio = scene.rexSpinner.add.radio(config);\nvar rings = scene.rexSpinner.add.rings(config);\nvar spinner = scene.rexSpinner.add.spinner(config);    
"},{"location":"shape-spinner/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { AIO, Arrow, Audio, Ball, Bars, Box, Clock, Cube, Custom, Dots, Facebook, Grid, Hearts, Ios, Orbit, Oval, Puff, Radio, Rings, Spinner\n} from \"phaser3-rex-plugins/templates/spinner/spinner-components.js\";\n
  • Add spinner object
    var spinner = new Audio(scene, config);\nscene.add.existing(spinner);\n
"},{"location":"shape-spinner/#add-spinner-object","title":"Add spinner object","text":""},{"location":"shape-spinner/#general","title":"General","text":"
var spinner = scene.rexSpinner.add.audio({\n// x: 0,\n// y: 0,\n// width: 64,\n// height: 64,\n// color: 0xffffff,\n\n// duration: 1000,\n// start: true,\n// delay: 0,\n// repeatDelay: 0,\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • color : Fill color, or stroke color. Default value is 0xffffff
  • duration : Duration of animation.
  • start : Start animation when object created.
  • false : Don't play animation at beginning.
  • delay : Delay time in ms before running.
  • repeatDelay : Delay time between 2 periods.
"},{"location":"shape-spinner/#arrow","title":"Arrow","text":"
var spinner = scene.rexSpinner.add.audio({\n// ...\n// direction: 'down'\n});\n
  • direction :
    • 0, 'right' : Arrow from left to right.
    • 1, 'down' : Arrow from up to down. Default behavior.
    • 2, 'left' : Arrow from right to left.
    • 3, 'up' : Arrow from down to up.
"},{"location":"shape-spinner/#aio","title":"AIO","text":"

All-in-one

var spinner = scene.rexSpinner.add.aio({\n// ...\n// animationMode: undefined\n});\n
  • animationMode :
    • undefined : Play random spinner animation.
    • 'leftArrow' : Play leftArrow spinner animation.
    • 'rightArrow' : Play rightArrow spinner animation.
    • 'upArrow' : Play upArrow spinner animation.
    • 'downArrow' : Play dowbArrow spinner animation.
    • 'audio' : Play audio spinner animation.
    • 'ball' : Play ball spinner animation.
    • 'bars' : Play bars spinner animation.
    • 'box' : Play box spinner animation.
    • 'clock' : Play clock spinner animation.
    • 'cube' : Play cube spinner animation.
    • 'dots' : Play dots spinner animation.
    • 'facebook' : Play facebook spinner animation.
    • 'grid' : Play grid spinner animation.
    • 'hearts' : Play hearts spinner animation.
    • 'ios' : Play ios spinner animation.
    • 'oribit' : Play oribit spinner animation.
    • 'oval' : Play oval spinner animation.
    • 'pie' : Play pie spinner animation.
    • 'puff' : Play puff spinner animation.
    • 'radio' : Play radio spinner animation.
    • 'rings' : Play rings spinner animation.
    • 'spinner' : Play spinner spinner animation.
"},{"location":"shape-spinner/#play-animation","title":"Play animation","text":""},{"location":"shape-spinner/#start","title":"Start","text":"
  • Start playing, won't restart when playing
    spinner.start();\n
  • Restart with new duration
    spinner.start(duration);\n
"},{"location":"shape-spinner/#pause","title":"Pause","text":"
spinner.pause();\n
"},{"location":"shape-spinner/#resume","title":"Resume","text":"
spinner.resume();\n
"},{"location":"shape-spinner/#stop","title":"Stop","text":"
spinner.stop();\n
"},{"location":"shape-spinner/#play-animation-manually","title":"Play animation manually","text":"
  1. Set start to false in config
  2. Set progress manually
    spinner.setValue(t);\n
    or
    spinner.value = t;\n
    • t : 0 ~ 1
"},{"location":"shape-spinner/#is-running","title":"Is running","text":"
var isRunning = spinner.isRunning;\n
"},{"location":"shape-spinner/#color","title":"Color","text":"
  • Get
    var color = spinner.color;\n
  • Set
    spinner.setColor(color);\n
    or
    spinner.color = color;\n
    • color : Fill color, or stroke color, in number.
"},{"location":"shape-spinner/#alpha","title":"Alpha","text":"
  • Get
    var alpha = spinner.alpha;\n
  • Set
    spinner.setAlpha(alpha);\n// spinner.alpha = alpha;\n
"},{"location":"shape-spinner/#duration","title":"Duration","text":"
  • Get
    var duration = spinner.duration;\n
  • Set, will apply to next animation playing.
    spinner.setDuration(duration);\n
    or
    spinner.duration = duration;\n
"},{"location":"shape-spinner/#ease","title":"Ease","text":"
  • Get
    var ease = spinner.ease;\n
  • Set, will apply to next animation playing.
    spinner.setEasen(ease);\n
    or
    spinner.ease = ease;\n
"},{"location":"shape-spinner/#set-animation-mode","title":"Set animation mode","text":"

AIO-spinner only

aioSpinner.setAnimationMode(mode);\n
  • mode :
    • undefined : Play random spinner animation.
    • 'leftArrow' : Play leftArrow spinner animation.
    • 'rightArrow' : Play rightArrow spinner animation.
    • 'upArrow' : Play upArrow spinner animation.
    • 'downArrow' : Play dowbArrow spinner animation.
    • 'audio' : Play audio spinner animation.
    • 'ball' : Play ball spinner animation.
    • 'bars' : Play bars spinner animation.
    • 'box' : Play box spinner animation.
    • 'clock' : Play clock spinner animation.
    • 'cube' : Play cube spinner animation.
    • 'dots' : Play dots spinner animation.
    • 'facebook' : Play facebook spinner animation.
    • 'grid' : Play grid spinner animation.
    • 'hearts' : Play hearts spinner animation.
    • 'ios' : Play ios spinner animation.
    • 'oribit' : Play oribit spinner animation.
    • 'oval' : Play oval spinner animation.
    • 'pie' : Play pie spinner animation.
    • 'puff' : Play puff spinner animation.
    • 'radio' : Play radio spinner animation.
    • 'rings' : Play rings spinner animation.
    • 'spinner' : Play spinner spinner animation.
aioSpinner.setRandomAnimationMode();\n
"},{"location":"shape-spinner/#custom-spinner","title":"Custom spinner","text":"
var customSpinner = scene.rexSpinner.add.custom({\n// x: 0,\n// y: 0,\n// width: 64,\n// height: 64,\n// color: 0xffffff,\n\n// duration: 1000,\n// start: true,\n\ncreate: {\n// shapeType: [name0, name1, ...],\n// shapeType: number,\n// shapeType: name,\n},\n\n// create: function() {\n// \n// },\n\nupdate: function() {\n\n},\n})\n
  • create : Callback to create shapes
    • A plain object with shapeType: name, or shapeType: number
      • shapeType :
        • 'arc' : Create Arc shape.
        • 'circle' : Create Circle shape.
        • 'ellipse' : Create Ellipse shape.
        • 'line' : Create Line shape.
        • 'lines' : Create Lines shape.
        • 'rectangle' : Create Rectangle shape.
        • 'roundRectangle' : Create Round rectangle shape.
        • 'triangle' : Create Triangle shape.
      • nameArray : An array of unique string name for each shape.
      • name : An unique string name of this shape.
      • number : Amount of shapes to create.
    • A callback
      function() {\n// this : This spinner game object\nvar shape = this.createShape(shapeType, name);\nthis.addShape(shape);\n}\n
      • this.createShape(shapeType, name) : Crate a shape instance, with an unique name.
      • this.addShape(shape) : Add this shape instance to this custom spinner.
  • update : Callback when porgressing
    function() {\n// this : This spinner game object\nvar centerX = this.centerX;\nvar centerY = this.centerY;\nvar radius = this.radius;\nvar color = this.color;\nvar shapes = this.getShapes();\nvar shape = this.getShape(name);\nvar t = this.value;\n// ...\n}\n
    • this.value : Progress, 0~1.
    • Position :
      • this.centerX, this.centerY : Center position of this spinner. The coordinate of top-left point is (0,0)
      • this.radius : Minimun value of this.centerX, this.centerY, to draw shape at square.
    • Color :
      • this.color : Color property of this spinner.
    • Shape instances : Change properties of shape instances.
      • this.getShapes() : Return all shapes in an array.
      • this.getShape(name) : Return a shape by the unique string name.
"},{"location":"shape-spinner/#shape-class","title":"Shape class","text":"

See Shape class

"},{"location":"shape-spinner/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-spinner/#create-mask","title":"Create mask","text":"
var mask = customSpinner.createGeometryMask();\n

See mask

"},{"location":"shape-spinner/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-star/","title":"Star","text":""},{"location":"shape-star/#introduction","title":"Introduction","text":"

Star shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-star/#usage","title":"Usage","text":""},{"location":"shape-star/#create-shape-object","title":"Create shape object","text":"
var star = scene.add.star(x, y, points, innerRadius, outerRadius, fillColor);\n// var star = scene.add.star(x, y, points, innerRadius, outerRadius, fillColor, fillAlpha);\n
  • points : The number of points on the star. Default is 5.
  • innerRadius : The inner radius of the star. Default is 32.
  • outerRadius : The outer radius of the star. Default is 64.
"},{"location":"shape-star/#custom-class","title":"Custom class","text":"
  • Define class
    class MyStar extends Phaser.GameObjects.Star {\nconstructor(scene, x, y, points, innerRadius, outerRadius, fillColor) {\nsuper(scene, x, y, points, innerRadius, outerRadius, fillColor);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var star = new MyStar(scene, x, y, points, innerRadius, outerRadius, fillColor);\n
"},{"location":"shape-star/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = star.fillColor;\nvar alpha = star.fillAlpha;\n
    • Set
      star.setFillStyle(color, alpha);\n
    • Clear
      star.setFillStyle();\n
  • Stroke color
    • Get
      var color = star.strokeColor;\n
    • Set
      star.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      star.setStrokeStyle();\n

No tint methods

Uses star.setFillStyle(color, alpha) to change color.

"},{"location":"shape-star/#alpha","title":"Alpha","text":"
  • Get
    var alpha = star.alpha;\n
  • Set
    star.setAlpha(alpha);\n// star.alpha = alpha;\n
"},{"location":"shape-star/#radius","title":"Radius","text":"
  • Inner radius
    • Get
      var innerRadius = star.innerRadius;\n
    • Set
      star.setInnerRadius(innerRadius);\n
      or
      star.innerRadius = innerRadius;\n
  • Outer radius
    • Get
      var outerRadius = star.outerRadius;\n
    • Set
      star.setOuterRadius(outerRadius);\n
      or
      star.outerRadius = outerRadius;\n
  • Points
    • Get
      var points = star.points;\n
    • Set
      star.setPoints(points);\n
      or
      star.points = points;\n
"},{"location":"shape-star/#display-size","title":"Display size","text":"
  • Get
    var width = star.displayWidth;\nvar height = star.displayHeight;\n
  • Set
    star.setDisplaySize(width, height);\n
    or
    star.displayWidth = width;\nstar.displayHeight = height;\n
"},{"location":"shape-star/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-star/#create-mask","title":"Create mask","text":"
var mask = star.createGeometryMask();\n

See mask

"},{"location":"shape-star/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-toggleswitch/","title":"Toggle switch","text":""},{"location":"shape-toggleswitch/#introduction","title":"Introduction","text":"

Toggle-switch input.

  • Author: Rex
  • Game object
"},{"location":"shape-toggleswitch/#live-demos","title":"Live demos","text":"
  • Toggle-switch
"},{"location":"shape-toggleswitch/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-toggleswitch/#install-plugin","title":"Install plugin","text":""},{"location":"shape-toggleswitch/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextoggleswitchplugin', 'https://raw.githubusercontent.com/rexrainbow/    phaser3-rex-notes/master/dist/rextoggleswitchplugin.min.js', true);\n
  • Add toggle-switch input
    var toggleSwitch = scene.add.rexToggleSwitch(x, y, width, height, color, config);\n
  • Add toggle-switch shape (without click input)
    var toggleSwitch = scene.add.rexToggleSwitchShape(x, y, width, height, color, config);\n
"},{"location":"shape-toggleswitch/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ToggleSwitchPlugin from 'phaser3-rex-plugins/plugins/toggleswitch-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexToggleSwitchPlugin',\nplugin: ToggleSwitchPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add toggle-switch input
    var toggleSwitch = scene.add.rexToggleSwitch(x, y, width, height, color, config);\n
  • Add toggle-switch shape (without click input)
    var toggleSwitch = scene.add.rexToggleSwitchShape(x, y, width, height, color, config);\n
"},{"location":"shape-toggleswitch/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ToggleSwitch from 'phaser3-rex-plugins/plugins/toggleswitch.js';\n
  • Add toggle-switch input
    var toggleswitch = new ToggleSwitch(scene, x, y, width, height, color, config);\nscene.add.existing(toggleSwitch);\n
  • Add toggle-switch shape (without click input)
    // import ToggleSwitchShape from 'phaser3-rex-plugins/plugins/toggleswitchshape.js';\nvar toggleSwitch = new ToggleSwitchShape(scene, x, y, width, height, color, config);\nscene.add.existing(toggleSwitch);\n
"},{"location":"shape-toggleswitch/#create-toggle-switch-input","title":"Create toggle-switch input","text":"
var toggleSwitch = scene.add.rexToggleSwitch(x, y, width, height, color, config);\n

or

var toggleSwitch = scene.add.rexToggleSwitch({\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\n\ncolor: 0x005cb2,\ntrackFillAlpha: 1,\nfalseValueTrackColor: undefined,\nfalseValueTrackFillAlpha: 1,\n\nthumbColor: 0xffffff,\nthumbAlpha: 1,\n\ntrackWidth: 0.9,\ntrackHeight: 0.5,\ntrackCornerRadius: (trackHeight * 0.5),\n\nthumbHeight: (trackHeight * 0.9),\nthumbWidth: (thumbHeight),\nthumbCornerRadius: (thumbHeight * 0.5),\n\nthumbLeft: 0.3,\nthumbRight: (1 - thumbLeft),\nrtl: false,\n\nanimationDuration: 150,\n\nvalue: false,\n\nclick: undefined,\n// click: {\n//     mode: 1,            // 0|'press'|1|'release'\n//     clickInterval: 100  // ms\n//     threshold: undefined\n// },\nreadOnly: false,\n});\n
  • width, height : Size of toggleswitch.
  • Track fill style
    • color, trackFillAlpha : Track color and alpha when value is true.
    • falseValueTrackColor, falseValueTrackFillAlpha : Track color and alpha when value is false.
      • Default value of falseValueTrackColor is the grayscale of color.
  • Thumb fill style
    • thumbColor, thumbAlpha : Thumb color and alpha
  • Track size
    • trackWidth : Width ration of track. Default value is 0.9.
    • thumbWidth : Height ratio of track. Default value is 0.5.
    • trackCornerRadius : Ratio of track corner. Default value is half of trackHeight.
  • Thumb size
    • thumbWidth : Width ration of thumb. Default value is equal to thumbHeight.
    • thumbHeight : Height ratio of thumb. Default value trackHeight * 0.5.
    • thumbCornerRadius : Ratio of thumb corner. Default value is half of thumbHeight.
  • Thumb position
    • thumbLeft : Thumb position if value is false. Default value is 0.3.
    • thumbRight : Thumb position if value is true. Default value is 1 - thumbLeft.
    • rtl : Moving direction of thumb when when value changes from false to true.
      • false : Thumb moves from left to right. Default behavior.
      • true : Thumb moves from right to left.
  • animationDuration : Duration of drawing path of checker.
  • value : Initial value.
  • click : Configuration of click input
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
    • click.threshold : Cancel clicking detecting when dragging distance is larger then this threshold.
      • undefined : Ignore this feature. Default behavior.
  • readOnly : Set ture to disable input.
"},{"location":"shape-toggleswitch/#custom-class","title":"Custom class","text":"
  • Define class
    class MyToggleSwitch extends RexPlugins.GameObjects.ToggleSwitch {\nconstructor(scene, x, y, width, height, color, config) {\nsuper(scene, x, y, width, height, color, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var toggleSwitch = new MyToggleSwitch(scene, x, y, width, height, color, config);\n
"},{"location":"shape-toggleswitch/#value","title":"Value","text":"
  • Get
    var value = toggleSwitch.value;\n// var value = toggleSwitch.value;\n
  • Set
    toggleSwitch.setValue(value);\n// toggleSwitch.setValue(value, duration);\n
    or
    toggleSwitch.value = value;\n
  • Toggle
    toggleSwitch.toggleValue();\n// toggleSwitch.toggleValue(duration);\n
    or
    toggleSwitch.value = !toggleSwitch.value;\n// toggleSwitch.value = !toggleSwitch.value;\n
"},{"location":"shape-toggleswitch/#read-only","title":"Read only","text":"
  • Get
    var readOnly = toggleSwitch.readOnly;\n
  • Set
    toggleSwitch.setReadOnly();\n// toggleSwitch.setReadOnly(true);\n
    or
    toggleSwitch.readOnly = true;\n
"},{"location":"shape-toggleswitch/#track-fill-style","title":"Track fill style","text":"
  • Get
    var color = toggleSwitch.trackFillColor;\nvar alpha = toggleSwitch.trackFillAlpha;\n
    var color = toggleSwitch.falseValueTrackColor;\nvar alpha = toggleSwitch.falseValueTrackFillAlpha;\n
  • Set
    toggleSwitch.setTrackFillStyle(color, alpha);\n// toggleSwitch.trackFillColor = color;\n// toggleSwitch.trackFillAlpha = alpha;\n
    toggleSwitch.setFalseValueTrackFillStyle(color, alpha);\n// toggleSwitch.falseValueTrackColor = color;\n// toggleSwitch.falseValueTrackFillAlpha = alpha;\n
"},{"location":"shape-toggleswitch/#thumb-fill-style","title":"Thumb fill style","text":"
  • Get
    var color = toggleSwitch.thumbColor;\nvar alpha = toggleSwitch.thumbAlpha;\n
  • Set
    toggleSwitch.setThumbStyle(color, alpha);\n// toggleSwitch.thumbColor = color;\n// toggleSwitch.thumbAlpha = alpha;\n
"},{"location":"shape-toggleswitch/#toggle-animation","title":"Toggle animation","text":"
  • Duration
    • Get
      var duration = toggleSwitch.toggleAnimProgress;\n
    • Set
      toggleSwitch.setToggleAnimationDuration(duration);\ntoggleSwitch.toggleAnimProgress = duration;\n
"},{"location":"shape-toggleswitch/#size","title":"Size","text":"
  • Get
    var width = toggleSwitch.width;\nvar height = toggleSwitch.height;\n
  • Set
    toggleSwitch.setSize(width, height);\n
    or
    toggleSwitch.width = width;\ntoggleSwitch.height = height;\n
"},{"location":"shape-toggleswitch/#display-size","title":"Display size","text":"
  • Get
    var width = toggleSwitch.displayWidth;\nvar height = toggleSwitch.displayHeight;\n
  • Set
    toggleSwitch.setDisplaySize(width, height);\n
    or
    toggleSwitch.displayWidth = width;\ntoggleSwitch.displayHeight = height;\n
"},{"location":"shape-toggleswitch/#track-size-ratio","title":"Track size ratio","text":"
  • Get
    var trackWidth = toggleSwitch.trackWidth;\nvar trackHeight = toggleSwitch.trackHeight;\n
    • trackWidth, trackHeight : Size ratio of track
  • Set
    toggleSwitch.setTrackSize(trackWidth, trackHeight);\n// toggleSwitch.trackWidth = trackWidth;\n// toggleSwitch.trackHeight = trackHeight;\n
"},{"location":"shape-toggleswitch/#track-corner-ratio","title":"Track corner ratio","text":"
  • Get
    var trackRadius = toggleSwitch.trackRadius;\n
    • trackRadius : Corner ratio of track
  • Set
    toggleSwitch.setTrackRadius(trackRadius);\n// toggleSwitch.trackRadius = trackRadius;\n
"},{"location":"shape-toggleswitch/#thumb-size-ratio","title":"Thumb size ratio","text":"
  • Get
    var thumbWidth = toggleSwitch.thumbWidth;\nvar thumbHeight = toggleSwitch.thumbHeight;\n
    • trackWidth, trackHeight : Size ratio of thumb
  • Set
    toggleSwitch.setThumbSize(thumbWidth, thumbHeight);\n// toggleSwitch.thumbWidth = thumbWidth;\n// toggleSwitch.thumbHeight = thumbHeight;\n
"},{"location":"shape-toggleswitch/#thumb-corner-ratio","title":"Thumb corner ratio","text":"
  • Get
    var thumbRadius = toggleSwitch.thumbRadius;\n
    • thumbRadius : Corner ratio of track
  • Set
    toggleSwitch.setThumbRadius(thumbRadius);\n// toggleSwitch.thumbRadius = thumbRadius;\n
"},{"location":"shape-toggleswitch/#thumb-position-ratio","title":"Thumb position ratio","text":"
  • Get
    var thumbLeft = toggleSwitch.thumbLeftX;\nvar thumbRight = toggleSwitch.thumbRightX;\n
    var rtl = toggleSwitch.rtl;\n
  • Set
    toggleSwitch.setThumbPosition(thumbLeft, thumbRight);\n// toggleSwitch.thumbLeftX = thumbLeft;\n// toggleSwitch.thumbRightX = thumbRight;\n
    toggleSwitch.setRTL(rtl);\n// toggleSwitch.rtl = rtl;\n
"},{"location":"shape-toggleswitch/#events","title":"Events","text":"
  • On value change
    toggleSwitch.on('valuechange', function(value) {\n// value: checked\n})\n
"},{"location":"shape-toggleswitch/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-toggleswitch/#create-mask","title":"Create mask","text":"
var mask = toggleSwitch.createGeometryMask();\n

See mask

"},{"location":"shape-toggleswitch/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-triangle/","title":"Triangle","text":""},{"location":"shape-triangle/#introduction","title":"Introduction","text":"

Triangle shape, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"shape-triangle/#usage","title":"Usage","text":""},{"location":"shape-triangle/#create-shape-object","title":"Create shape object","text":"
var triangle = scene.add.triangle(x, y, x1, y1, x2, y2, x3, y3, fillColor);\n// var triangle = scene.add.triangle(x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha);\n
"},{"location":"shape-triangle/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTriangle extends Phaser.GameObjects.Triangle {\nconstructor(scene, x, y, x1, y1, x2, y2, x3, y3, fillColor) {\nsuper(scene, x, y, x1, y1, x2, y2, x3, y3, fillColor);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var triangle = new MyTriangle(scene, x, y, x1, y1, x2, y2, x3, y3, fillColor);\n
"},{"location":"shape-triangle/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = triangle.fillColor;\nvar alpha = triangle.fillAlpha;\n
    • Set
      triangle.setFillStyle(color, alpha);\n
    • Clear
      triangle.setFillStyle();\n
  • Stroke color
    • Get
      var color = triangle.strokeColor;\n
    • Set
      triangle.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      triangle.setStrokeStyle();\n

No tint methods

Uses triangle.setFillStyle(color, alpha) to change color.

"},{"location":"shape-triangle/#alpha","title":"Alpha","text":"
  • Get
    var alpha = triangle.alpha;\n
  • Set
    triangle.setAlpha(alpha);\n// triangle.alpha = alpha;\n
"},{"location":"shape-triangle/#set-vertices","title":"Set vertices","text":"
triangle.setTo(x1, y1, x2, y2, x3, y3);\n
"},{"location":"shape-triangle/#triangle-width","title":"Triangle width","text":"
triangle.setLineWidth(startWidth, endWidth);\n
  • endWidth : The end width of the triangle. Only used in WebGL.
"},{"location":"shape-triangle/#display-size","title":"Display size","text":"
  • Get
    var width = triangle.displayWidth;\nvar height = triangle.displayHeight;\n
  • Set
    triangle.setDisplaySize(width, height);\n
    or
    triangle.displayWidth = width;\ntriangle.displayHeight = height;\n
"},{"location":"shape-triangle/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-triangle/#create-mask","title":"Create mask","text":"
var mask = triangle.createGeometryMask();\n

See mask

"},{"location":"shape-triangle/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shape-triangle2/","title":"Triangle 2","text":""},{"location":"shape-triangle2/#introduction","title":"Introduction","text":"

Trangle shape inside a rectangle bounds.

  • Author: Rex
  • Game object
"},{"location":"shape-triangle2/#live-demos","title":"Live demos","text":"
  • Ease direction
  • Rotate
"},{"location":"shape-triangle2/#usage","title":"Usage","text":"

Sample code

"},{"location":"shape-triangle2/#install-plugin","title":"Install plugin","text":""},{"location":"shape-triangle2/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextriangleplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextriangleplugin.min.js', true);\n
  • Add triangle object
    var triangle = scene.add.rexTriangle(x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-triangle2/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TrianglePlugin from 'phaser3-rex-plugins/plugins/triangle-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTrianglePlugin',\nplugin: TrianglePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add triangle object
    var triangle = scene.add.rexTriangle(x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-triangle2/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Triangle from 'phaser3-rex-plugins/plugins/triangle.js';\n
  • Add triangle object
    var triangle = new Triangle(scene, x, y, width, height, fillColor, fillAlpha);\nscene.add.existing(triangle);\n
"},{"location":"shape-triangle2/#install-plugin_1","title":"Install plugin","text":"

Install plugin in configuration of game

var config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTrianglePlugin',\nplugin: TrianglePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"shape-triangle2/#create-instance","title":"Create instance","text":"
var triangle = scene.add.rexTriangle(x, y, width, height, fillColor, fillAlpha);\n

or

var triangle = scene.add.rexTriangle({\nx: 0,\ny: 0,\nwidth: 2,\nheight: 2,\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n\narrowOnly: false,\n\ndirection: 0,\neaseDuration: 0,\npadding: 0,\n// padding: {\n//     left: 0,\n//     right: 0,\n//     top: 0,\n//     bottom: 0,\n// },\n\nradius: undefined,\n});\n
  • x, y : Position of this object.
  • width, height : Size of this object.
  • arrowOnly :
    • false : Fill and stroke triangle shape. Default behavior.
    • true : Only stroke arrow of triangle shape.
  • direction : Direction of triangle's arrow.
    • 0, or 'right' : Arrow to right. Default value.
    • 1, or 'down' : Arrow to down.
    • 2, or 'left' : Arrow to left.
    • 3, or 'up' : Arrow to up.
  • easeDuration : Ease duration when direction changed.
    • 0 : No ease transform. Default value.
  • padding : Space around triagnle.
    • A number. Default value is 0.
    • A plain object
      {\nleft:0, right:0, top: 0, bottom: 0\n}\n
  • radius : Put 3 vertices of trangle in a circle.
    • undefined : Disable this mode. Default behavior.
    • 0~1 : Radius in ratio of min(half-width, half-height)
"},{"location":"shape-triangle2/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTriangle extends Triangle {\nconstructor(scene, x, y, width, height, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var triangle = new MyTriangle(scene, x, y, width, height, fillColor, fillAlpha);\n
"},{"location":"shape-triangle2/#color","title":"Color","text":"
  • Fill color
    • Get
      var color = triangle.fillColor;\nvar alpha = triangle.fillAlpha;\n
    • Set
      triangle.setFillStyle(color, alpha);\n
    • Clear
      triangle.setFillStyle();\n
  • Stroke color
    • Get
      var color = triangle.strokeColor;\n
    • Set
      triangle.setStrokeStyle(lineWidth, color, alpha);\n
    • Clear
      triangle.setStrokeStyle();\n

No tint methods

Uses triangle.setFillStyle(color, alpha) to change color.

"},{"location":"shape-triangle2/#alpha","title":"Alpha","text":"
  • Get
    var alpha = triangle.alpha;\n
  • Set
    triangle.setAlpha(alpha);\n// triangle.alpha = alpha;\n
"},{"location":"shape-triangle2/#size","title":"Size","text":"
  • Get
    var width = triangle.width;\nvar height = triangle.height;\n
  • Set
    triangle.setSize(width, height);\n
    or
    triangle.width = width;\ntriangle.height = height;\n
"},{"location":"shape-triangle2/#display-size","title":"Display size","text":"
  • Get
    var width = triangle.displayWidth;\nvar height = triangle.displayHeight;\n
  • Set
    triangle.setDisplaySize(width, height);\n
    or
    triangle.displayWidth = width;\ntriangle.displayHeight = height;\n
"},{"location":"shape-triangle2/#direction","title":"Direction","text":"
  • Get
    var direction = triangle.direction;\n
    • 0 : Arrow to right. Default value.
    • 1 : Arrow to down.
    • 2 : Arrow to left.
    • 3 : Arrow to up.
  • Set
    triangle.setDirection(direction);\n// triangle.direction = direction;\n
    or
    triangle.setDirection(direction, easeDuration);\n
    • direction :
      • 0, or 'right' : Arrow to right.
      • 1, or 'down' : Arrow to down.
      • 2, or 'left' : Arrow to left.
      • 3, or 'up' : Arrow to up.
    • easeDuration : Override current ease-duration time.
  • Toggle
    triangle.toggleDirection();\n// triangle.direction += 2;\n
    or
    triangle.toggleDirection(easeDuration);\n
"},{"location":"shape-triangle2/#padding","title":"Padding","text":"
  • Get
    var padding = triangle.padding;\n
    • padding :
      { left, right, top, bottom }\n
  • Set
    triangle.setPadding(padding);\n
    or
    triangle.setPadding({\nleft, right, top, bottom\n});\n
    or
    triangle.setPadding({\nx, y\n});\n
"},{"location":"shape-triangle2/#ease-duration","title":"Ease duration","text":"
  • Get
    var easeDuration = triangle.easeDuration;\n
  • Set
    triangle.setEaseDuration(easeDuration);\n
"},{"location":"shape-triangle2/#arrow-only","title":"Arrow only","text":"
  • Get
    var arrowOnly = triangle.arrowOnly;\n
  • Set
    triangle.setArrowOnly(enable);\n// triangle.arrowOnly = enable;\n
"},{"location":"shape-triangle2/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"shape-triangle2/#create-mask","title":"Create mask","text":"
var mask = triangle.createGeometryMask();\n

See mask

"},{"location":"shape-triangle2/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shatter-image/","title":"Image","text":""},{"location":"shatter-image/#introduction","title":"Introduction","text":"

Shatter image to triangle faces.

Reference: Delaunay Triangulation

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"shatter-image/#live-demos","title":"Live demos","text":"
  • Shatter image
"},{"location":"shatter-image/#usage","title":"Usage","text":"

Sample code

"},{"location":"shatter-image/#install-plugin","title":"Install plugin","text":""},{"location":"shatter-image/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexshatterimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexshatterimageplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexShatterImage(x, y, texture, frame, config);\n
"},{"location":"shatter-image/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ShatterImagePlugin from 'phaser3-rex-plugins/plugins/shatterimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexShatterImagePlugin',\nplugin: ShatterImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexShatterImage(x, y, texture, frame, config);\n
"},{"location":"shatter-image/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ShatterImage } from 'phaser3-rex-plugins/plugins/shatterimage.js';\n
  • Add image object
    var image = new ShatterImage(scene, x, y, texture, frame, config);\nscene.add.existing(image);\n
"},{"location":"shatter-image/#create-instance","title":"Create instance","text":"
var image = scene.add.rexShatterImage(x, y, texture, frame, {\n// ringRadiusList: [1 / 27, 3 / 27, 9 / 27],\n// ringRadiusList: function(width, height) {\n//    return [1 / 27, 3 / 27, 9 / 27];\n// },\n\n// samplesPerRing: 12\n// variation: 0.25,    \n});\n

or

var image = scene.add.rexShatterImage({\n// x: 0,\n// y: 0,\nkey,\n// frame: null,\n\n// ringRadiusList: [1 / 27, 3 / 27, 9 / 27],\n// ringRadiusList: function(width, height) {\n//    return [1 / 27, 3 / 27, 9 / 27];\n// },\n\n// samplesPerRing: 12,\n// variation: 0.25,\n\n});\n
  • ringRadiusList :
    • A list of number. Default value is [1 / 27, 3 / 27, 9 / 27]
    • A callback to return a list of number
      function(width, height) {\nreturn [1 / 27, 3 / 27, 9 / 27];\n}\n

Add perspectiveimage from JSON

var perspectiveimage = scene.make.rexShatterImage({\nx: 0,\ny: 0,\nkey: null,\nframe: null,\n\n// ringRadiusList: [1 / 27, 3 / 27, 9 / 27],\n// ringRadiusList: function(width, height) {\n//    return [1 / 27, 3 / 27, 9 / 27];\n// },\n\n// samplesPerRing: 12,\n// variation: 0.25,\n\n\nadd: true\n});\n
"},{"location":"shatter-image/#custom-class","title":"Custom class","text":"
  • Define class
    class MyShatterImage( extends ShatterImage( {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyShatterImage(scene, x, y, texture, frame, config);\n
"},{"location":"shatter-image/#shatter-image","title":"Shatter image","text":"
image.shatter(centerX, centerY);\n// image.shatter();\n

or

image.shatter(centerX, centerY, {\n// ringRadiusList:\n// samplesPerRing: \n// variation\n});\n

or

image.shatter({\n// centerX: \n// centerY: \n// ringRadiusList:\n// samplesPerRing: \n// variation\n});\n
  • centerX, centerY : Center position of shatter.
    • undefined : Default value is center of image.

Shatter image into triangle faces.

"},{"location":"shatter-image/#position-of-shatter-center","title":"Position of Shatter center","text":"
var shatterCenter = image.shatterCenter; // {x, y}\n
"},{"location":"shatter-image/#faces","title":"Faces","text":"
var faces = image.faces;\n

Faces will be sorted nearby shatter-center to far away.

"},{"location":"shatter-image/#properties","title":"Properties","text":"
  • Alpha
    • Get
      var alpha = face.alpha;\n
    • Set
      face.alpha = alpha;\n
      or
      face.setAlpha(value);\n
  • Tint color
    • Get
      var color = face.tint;\n
    • Set
      face.tint = color;\n
      or
      face.setTint(color);\n
  • Angle
    • Get
      var radians = face.rotation;\n// var degree = face.angle;\n
    • Set
      face.rotation = radians;\n// face.angle = degree;\n
      or
      face.setRotation(radians);\n// face.setAngle(degree);\n
  • Center position
    • Get
      var x = face.x;\nvar y = face.y;\n
      • x : 0(left) ~ 1(right)
      • y : 1(top) ~ 0(bottom)
    • Set
      face.x = x;\nface.y = y;\n
      or
      face.translate(x, y);\n
      • x : 0(left) ~ 1(right)
      • y : 1(top) ~ 0(bottom)
"},{"location":"shatter-image/#update-properties","title":"Update properties","text":"
  • Start updating
    image.startUpdate();\n
    or
    image.ignoreDirtyCache = true;\n
  • Stop updating
    image.stopUpdate();\n
    or
    image.ignoreDirtyCache = false;\n
"},{"location":"shatter-image/#tween-properties","title":"Tween properties","text":"
image.startUpdate();\nscene.tweens.add({\ntargets: image.faces,\nalpha: 0,\nangle: function () { return -90 + Math.random() * 180; },\ny: '-=0.5',\nease: 'Linear',       // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\ndelay: scene.tweens.stagger(20),\nrepeat: 0,            // -1: infinity\nyoyo: false,\nonComplete: function () {\nimage.stopUpdate()\n}\n});\n
"},{"location":"shatter-image/#reset-image","title":"Reset image","text":"

Display original image with 2 faces.

image.resetImage();\n
"},{"location":"shatter-image/#tint-color","title":"Tint color","text":"
  • Get
    var color = image.tint;\n
  • Set
    image.tint = color;\n
    or
    image.setTint(color);\n
"},{"location":"shatter-image/#other-properties","title":"Other properties","text":"

See Mesh game object, game object

"},{"location":"shatter-image/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"shatter-image/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"shatter-rendertexture/","title":"Render texture","text":""},{"location":"shatter-rendertexture/#introduction","title":"Introduction","text":"

Shatter render texture to triangle faces.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"shatter-rendertexture/#live-demos","title":"Live demos","text":"
  • RenderTexture
"},{"location":"shatter-rendertexture/#usage","title":"Usage","text":"

Sample code

"},{"location":"shatter-rendertexture/#install-plugin","title":"Install plugin","text":""},{"location":"shatter-rendertexture/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexshatterimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexshatterimageplugin.min.js', true);\n
  • Add render texture object
    var image = scene.add.rexShatterRenderTexture(x, y, width, height, config);\n
"},{"location":"shatter-rendertexture/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ShatterImagePlugin from 'phaser3-rex-plugins/plugins/shatterimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexShatterImagePlugin',\nplugin: ShatterImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add render texture object
    var image = scene.add.rexShatterRenderTexturege(x, y, width, height, config);\n
"},{"location":"shatter-rendertexture/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ShatterRenderTexture } from 'phaser3-rex-plugins/plugins/shatterimage.js';\n
  • Add render texture object
    var image = new ShatterRenderTexture(scene, x, y, width, height, config);\nscene.add.existing(image);\n
"},{"location":"shatter-rendertexture/#create-instance","title":"Create instance","text":"
var image = scene.add.rexShatterRenderTexturege(x, y, width, height, {\n// gridWidth: 32,\n// girdHeight: 32\n});\n

or

var image = scene.add.rexShatterRenderTexturege({\n// x: 0,\n// y: 0,\n// width: 32,\n// height: 32,\n// gridWidth: 32,\n// girdHeight: 32\n});\n

Add prespective render texture from JSON

var image = scene.make.rexShatterRenderTexturege({\nx: 0,\ny: 0,    width: 32,\nheight: 32,\n\n// gridWidth: 32,\n// girdHeight: 32,\n\nadd: true\n});\n
"},{"location":"shatter-rendertexture/#custom-class","title":"Custom class","text":"
  • Define class
    class MyShatterRenderTexturege extends ShatterRenderTexturege {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyShatterRenderTexturege(scene, x, y, width, height, config);\n
"},{"location":"shatter-rendertexture/#internal-render-texture","title":"Internal render texture","text":"
var rt = image.rt;\n
  • rt : Render texture
"},{"location":"shatter-rendertexture/#paste-texture","title":"Paste texture","text":"
  • Paste game object
    image.rt.draw(gameObject, x, y);\n// image.rt.draw(gameObject, x, y, alpha, tint);\n
  • gameObject : a game object, or an array of game objects
  • Paste game objects in a group
    image.rt.draw(group, x, y);\n// image.rt.draw(group, x, y, alpha, tint);\n
  • Paste game objects in a scene
    image.rt.draw(scene.children, x, y);\n// image.rt.draw(scene.children, x, y, alpha, tint);\n
  • Paste texture
    image.rt.draw(key, x, y);\n// image.rt.draw(key, x, y, alpha, tint);\n
    or
    image.rt.drawFrame(key, frame, x, y);\n// image.rt.drawFrame(key, frame, x, y, alpha, tint);\n
    • key : The key of the texture to be used, as stored in the Texture Manager.
"},{"location":"shatter-rendertexture/#erase","title":"Erase","text":"
image.rt.erase(gameObject, x, y);\n
  • gameObject : a game object, or an array of game objects
"},{"location":"shatter-rendertexture/#clear","title":"Clear","text":"
image.rt.clear();\n
"},{"location":"shatter-rendertexture/#fill","title":"Fill","text":"
image.rt.fill(rgb, alpha);\n// image.rt.fill(rgb, alpha, x, y, width, height);\n
"},{"location":"shatter-rendertexture/#other-properties","title":"Other properties","text":"

See Shatter image game object, Mesh game object, game object

"},{"location":"shatter-rendertexture/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"shatter-rendertexture/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"ship/","title":"Ship","text":""},{"location":"ship/#introduction","title":"Introduction","text":"

Move game object as a space ship by cursor keys.

  • Author: Rex
  • Arcade behavior of game object
"},{"location":"ship/#usage","title":"Usage","text":"

Sample code

"},{"location":"ship/#install-plugin","title":"Install plugin","text":""},{"location":"ship/#load-minify-file","title":"Load minify file","text":"
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexshipplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexshipplugin.min.js', true);\n
  • Add ship behavior
    var ship = scene.plugins.get('rexshipplugin').add(gameObject, config);\n
"},{"location":"ship/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine and install plugin in configuration of game
    import ShipPlugin from 'phaser3-rex-plugins/plugins/ship-plugin.js';\nvar config = {\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexShip',\nplugin: ShipPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add ship behavior
    var ship = scene.plugins.get('rexShip').add(gameObject, config);\n
"},{"location":"ship/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable arcade physics engine in configuration of game
    var config = {\n// ...\nphysics: {\ndefault: 'arcade',\narcade: {\n// debug: true\n}\n}\n}\nvar game = new Phaser.Game(config);\n
  • Import class
    import Ship from 'phaser3-rex-plugins/plugins/ship.js';\n
  • Add ship behavior
    var ship = new Ship(gameObject, config);\n
"},{"location":"ship/#create-instance","title":"Create instance","text":"
var ship = scene.plugins.get('rexShip').add(gameObject, {\n// maxSpeed: 200,\n// acceleration: 200,\n// drag: 0.99,\n// turnSpeed: 300,\n// wrap: true,\n// padding: 0,\n// enable: true,\n// cursorKeys: scene.input.keyboard.createCursorKeys()\n});\n
  • Movement
    • maxSpeed
    • acceleration
    • drag
  • Rotation
    • turnSpeed : Angular velocity
  • Wrap
    • wrap : Set true to enable wrap mode. Default value is true.
    • padding
  • enable : set false to disable moving.
  • cursorKeys : CursorKey object, using keyboard's cursorKeys by default.
"},{"location":"ship/#set-max-speed","title":"Set max speed","text":"
ship.setMaxSpeed(speed);\n
"},{"location":"ship/#set-acceleration","title":"Set acceleration","text":"
ship.setAcceleration(acc);\n
"},{"location":"ship/#set-drag","title":"Set drag","text":"
ship.setDrag(drag);\n
"},{"location":"ship/#set-turn-speed","title":"Set turn speed","text":"
ship.setTurnSpeed(angularVelocity);\n
"},{"location":"ship/#set-wrap-mode","title":"Set wrap mode","text":"
ship.setWrapMode(wrap, padding);\n
  • wrap : Set true to enable wrap mode.
"},{"location":"skew-image/","title":"Image","text":""},{"location":"skew-image/#introduction","title":"Introduction","text":"

Skewable Image.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"skew-image/#live-demos","title":"Live demos","text":"
  • Skew image
"},{"location":"skew-image/#usage","title":"Usage","text":"

Sample code

"},{"location":"skew-image/#install-plugin","title":"Install plugin","text":""},{"location":"skew-image/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquadimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquadimageplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexSkewImage(x, y, texture, frame);\n
"},{"location":"skew-image/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuadImagePlugin from 'phaser3-rex-plugins/plugins/quadimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuadImagePlugin',\nplugin: QuadImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexSkewImage(x, y, texture, frame);\n
"},{"location":"skew-image/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { SkewImage } from 'phaser3-rex-plugins/plugins/quadimage.js';\n
  • Add image object
    var image = new SkewImage(scene, x, y, texture, frame);\nscene.add.existing(image);\n
"},{"location":"skew-image/#create-instance","title":"Create instance","text":"
var image = scene.add.rexSkewImage(x, y, texture, frame);\n

or

var image = scene.add.rexSkewImage({\n// x: 0,\n// y: 0,\nkey,\n// frame: null,\n});\n

Add quadimage from JSON

var quadimage = scene.make.rexSkewImage({\nx: 0,\ny: 0,\n\nkey: null,\nframe: null,\n\nadd: true\n});\n
"},{"location":"skew-image/#custom-class","title":"Custom class","text":"
  • Define class
    class MySkewImage extends SkewImage {\nconstructor(scene, x, y, texture, frame) {\nsuper(scene, x, y, texture, frame);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MySkewImage(scene, x, y, texture, frame);\n
"},{"location":"skew-image/#skew","title":"Skew","text":"
  • Set
    image.setSkewX(skewXRad);\nimage.setSkewXDeg(skewXDeg);\n
    image.setSkewY(skewXRad);\nimage.setSkewYDeg(skewXDeg);\n
    image.setSkew(skewXRad, skewYRad);\nimage.setSkewDeg(skewXDeg, skewYDeg);\n
    image.skewX = skewXRad;\nimage.skewXDeg = skewXDeg;\n
    image.skewY = skewYRad;\nimage.skewYDeg = skewYDeg;\n
  • Get
    var skewXRad = image.skewX;\nvar skewXDeg = image.skewXDeg;\n
    var skewYRad = image.skewY;\nvar skewYDeg = image.skewYDeg;\n
"},{"location":"skew-image/#other-properties","title":"Other properties","text":"

See Mesh game object, game object

"},{"location":"skew-image/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"skew-image/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"skew-rendertexture/","title":"Render texture","text":""},{"location":"skew-rendertexture/#introduction","title":"Introduction","text":"

Skewable render texture.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"skew-rendertexture/#live-demos","title":"Live demos","text":""},{"location":"skew-rendertexture/#usage","title":"Usage","text":""},{"location":"skew-rendertexture/#install-plugin","title":"Install plugin","text":""},{"location":"skew-rendertexture/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexquadimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexquadimageplugin.min.js', true);\n
  • Add render texture object
    var image = scene.add.rexSkewRenderTexture(x, y, width, height);\n
"},{"location":"skew-rendertexture/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import QuadImagePlugin from 'phaser3-rex-plugins/plugins/quadimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexQuadImagePlugin',\nplugin: QuadImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add render texture object
    var image = scene.add.rexSkewRenderTexturege(x, y, width, height);\n
"},{"location":"skew-rendertexture/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { SkewRenderTexture } from 'phaser3-rex-plugins/plugins/quadimage.js';\n
  • Add render texture object
    var image = new SkewRenderTexture(scene, x, y, width, height);\nscene.add.existing(image);\n
"},{"location":"skew-rendertexture/#create-instance","title":"Create instance","text":"
var image = scene.add.rexSkewRenderTexturege(x, y, width, height);\n

or

var image = scene.add.rexSkewRenderTexturege({\n// x: 0,\n// y: 0,\n// width: 32,\n// height: 32,\n});\n

Add prespective render texture from JSON

var image = scene.make.rexSkewRenderTexturege({\nx: 0,\ny: 0,    width: 32,\nheight: 32,\n\nadd: true\n});\n
"},{"location":"skew-rendertexture/#custom-class","title":"Custom class","text":"
  • Define class
    class MySkewRenderTexturege extends SkewRenderTexturege {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MySkewRenderTexturege(scene, x, y, width, height);\n
"},{"location":"skew-rendertexture/#internal-render-texture","title":"Internal render texture","text":"
var rt = image.rt;\n
  • rt : Render texture
"},{"location":"skew-rendertexture/#paste-texture","title":"Paste texture","text":"
  • Paste game object
    image.rt.draw(gameObject, x, y);\n// image.rt.draw(gameObject, x, y, alpha, tint);\n
  • gameObject : a game object, or an array of game objects
  • Paste game objects in a group
    image.rt.draw(group, x, y);\n// image.rt.draw(group, x, y, alpha, tint);\n
  • Paste game objects in a scene
    image.rt.draw(scene.children, x, y);\n// image.rt.draw(scene.children, x, y, alpha, tint);\n
  • Paste texture
    image.rt.draw(key, x, y);\n// image.rt.draw(key, x, y, alpha, tint);\n
    or
    image.rt.drawFrame(key, frame, x, y);\n// image.rt.drawFrame(key, frame, x, y, alpha, tint);\n
    • key : The key of the texture to be used, as stored in the Texture Manager.
"},{"location":"skew-rendertexture/#erase","title":"Erase","text":"
image.rt.erase(gameObject, x, y);\n
  • gameObject : a game object, or an array of game objects
"},{"location":"skew-rendertexture/#clear","title":"Clear","text":"
image.rt.clear();\n
"},{"location":"skew-rendertexture/#fill","title":"Fill","text":"
image.rt.fill(rgb, alpha);\n// image.rt.fill(rgb, alpha, x, y, width, height);\n
"},{"location":"skew-rendertexture/#other-properties","title":"Other properties","text":"

See Skew image game object, Mesh game object, game object

"},{"location":"skew-rendertexture/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"skew-rendertexture/#shader-effects","title":"Shader effects","text":"

Support postFX effects

Note

No preFX effect support

"},{"location":"slider/","title":"Slider","text":""},{"location":"slider/#introduction","title":"Introduction","text":"

Drag thumb on a slider bar.

  • Author: Rex
  • Behavior of game object
"},{"location":"slider/#live-demos","title":"Live demos","text":"
  • Slider
  • Color picker
"},{"location":"slider/#usage","title":"Usage","text":"

Sample code

"},{"location":"slider/#install-plugin","title":"Install plugin","text":""},{"location":"slider/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexsliderplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexsliderplugin.min.js', true);\n
  • Add slider behavior
    var slider = scene.plugins.get('rexsliderplugin').add(gameObject, config);\n
"},{"location":"slider/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import SliderPlugin from 'phaser3-rex-plugins/plugins/slider-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexSlider',\nplugin: SliderPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add slider behavior
    var slider = scene.plugins.get('rexSlider').add(gameObject, config);\n
"},{"location":"slider/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Slider from 'phaser3-rex-plugins/plugins/slider.js';\n
  • Add slider behavior
    var slider = new Slider(gameObject, config);\n
"},{"location":"slider/#create-instance","title":"Create instance","text":"
var slider = scene.plugins.get('rexSlider').add(gameObject, {\n// endPoints: [\n//     {x:0, y:0},\n//     {x:0, y:0}\n// ],\n// value: 0,\n// enable: true,\n\n// valuechangeCallback: null,\n// valuechangeCallbackScope: null\n});\n
  • endPoints : An array of 2 end-points ([{x,y}, {x,y}])
  • value : Initial value between 0 to 1
  • enable : Set true to drag thumb
  • valuechangeCallback , valuechangeCallbackScope : Bind this callback to valuechange event
"},{"location":"slider/#set-end-points","title":"Set end-points","text":"
slider.setEndPoints(p0x, p0y, p1x, p1y);\n// slider.setEndPoints(p0, p1); // p0, p1: {x, y}\n// slider.setEndPoints(points); // points: [p0, p1]\n
"},{"location":"slider/#get-value","title":"Get value","text":"
var value = slider.value;          // value: between 0 to 1\n// var value = slider.getValue();  // value: between 0 to 1\n// var value = slider.getValue(min, max);  // value: between min to max\n
"},{"location":"slider/#set-value","title":"Set value","text":"
slider.value = newValue;       // newValue: between 0 to 1\n// slider.setValue(newValue);  // newValue: between 0 to 1\n// slider.setValue(newValue, min, max);  // newValue: between min to max\n
slider.addValue(inc);  // inc: between 0 to 1\n// slider.addValue(inc, min, max);  // inc: between min to max\n

Fires valuechange event if new value is not equal to current value.

"},{"location":"slider/#events","title":"Events","text":"
  • Value changed
    slider.on('valuechange', function(newValue, prevValue){ /* ... */ });\n
    • newValue: between 0 to 1
    • prevValue: between 0 to 1
"},{"location":"slider/#drag","title":"Drag","text":""},{"location":"slider/#drag-enable","title":"Drag enable","text":"
  • Get
    var enable = slider.enable;\n
  • Set
    slider.setEnable(enable);  // enable: true, or false\nslider.enable = enable;\n
  • Toggle
    slider.toggleEnable();\n
"},{"location":"slider/#is-dragging","title":"Is dragging","text":"
var isDragging = slider.isDragging;\n
"},{"location":"snap/","title":"Snap","text":""},{"location":"snap/#introduction","title":"Introduction","text":"

Snap a value to nearest grid slice, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"snap/#usage","title":"Usage","text":""},{"location":"snap/#round","title":"Round","text":"
var out = Phaser.Math.Snap.To(value, gap);\n// var out = Phaser.Math.Snap.To(value, gap, start);\n

Example: set gap to 5

  • Set value to 12, return 10
  • Set value to 14, return 15
"},{"location":"snap/#ceil","title":"Ceil","text":"
var out = Phaser.Math.Snap.Ceil(value, gap);\n// var out = Phaser.Math.Snap.Ceil(value, gap, start);\n

Example: set gap to 5

  • Set value to 12, return 15
  • Set value to 14, return 15
"},{"location":"snap/#floor","title":"Floor","text":"
var out = Phaser.Math.Snap.Floor(value, gap);\n// var out = Phaser.Math.Snap.Floor(value, gap, start);\n

Example: set gap to 5

  • Set value to 12, return 10
  • Set value to 14, return 10
"},{"location":"snapshot/","title":"Snapshot","text":""},{"location":"snapshot/#introduction","title":"Introduction","text":"

Get snapshot image, built-in methods of phaser.

  • Author: Richard Davey
"},{"location":"snapshot/#usage","title":"Usage","text":""},{"location":"snapshot/#get-snapshot-image","title":"Get snapshot image","text":"
  • Whole canvas
    game.renderer.snapshot(callback);\n// game.renderer.snapshot(callback, type, encoderOptions);\n
  • A rectangle area
    game.renderer.snapshotArea(x, y, width, height, callback);\n// game.renderer.snapshot(x, y, width, height, callback, type, encoderOptions);\n
    • x, y, width, height : Top-left position and size based on game viewport. (not the world)
  • A pixel
    game.renderer.snapshotPixel(x, y, callback);\n

Parameters:

  • type : 'image/png'
  • encoderOptions : 0.92
  • callback :
    function(image){ /* ... */};\n
    • image : Image element
"},{"location":"sprite/","title":"Sprite","text":""},{"location":"sprite/#introduction","title":"Introduction","text":"

Display of both static and animated images, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"sprite/#usage","title":"Usage","text":""},{"location":"sprite/#load-texture","title":"Load texture","text":"

Texture for static image

scene.load.image(key, url);\n

Reference: load image

"},{"location":"sprite/#load-atlas","title":"Load atlas","text":"

Atlas for animation images

scene.load.atlas(key, textureURL, atlasURL);\n

Reference: load atlas

"},{"location":"sprite/#add-sprite-object","title":"Add sprite object","text":"
var sprite = scene.add.sprite(x, y, key);\n// var sprite = scene.add.sprite(x, y, key, frame);\n

Add sprite from JSON

var sprite = scene.make.sprite({\nx: 0,\ny: 0,\nkey: '',\n// frame: '',\n\n// angle: 0,\n// alpha: 1\n// flipX: true,\n// flipY: true,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n\n// anims: {\n// key: ,\n// repeat: ,\n// ...\n// },\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
  • key :
    • A string
    • An array of string to pick one element at random
  • x, y, scale.x, scale.y :
    • A number
    • A callback to get return value
      function() { return 0; }\n
    • Random integer between min and max
      { randInt: [min, max] }\n
    • Random float between min and max
      { randFloat: [min, max] }\n
"},{"location":"sprite/#custom-class","title":"Custom class","text":"
  • Define class
    class MySprite extends Phaser.GameObjects.Sprite {\nconstructor(scene, x, y, texture, frame) {\nsuper(scene, x, y, texture, frame);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var sprite = new MySprite(scene, x, y, key);\n
"},{"location":"sprite/#texture","title":"Texture","text":"

See game object - texture

"},{"location":"sprite/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"sprite/#create-mask","title":"Create mask","text":"
var mask = sprite.createBitmapMask();\n

See mask

"},{"location":"sprite/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"sprite/#animation","title":"Animation","text":""},{"location":"sprite/#create-animation","title":"Create animation","text":"
  • Global animation for all sprites
    scene.anims.create(config);\n
  • Private animation for this sprite
    sprite.anims.create(config);\n

config : See Add animation section.

"},{"location":"sprite/#create-aseprite-animation","title":"Create Aseprite animation","text":"
  • Global Aseprite animation for all sprites
    scene.anims.createFromAseprite(key, tags);\n
  • Private Aseprite animation for this sprite
    sprite.anims.createFromAseprite(key, tags);\n
"},{"location":"sprite/#remove-animation","title":"Remove animation","text":"
  • Remove from global animation manager
    scene.anims.remove(key);\n
    or
    sprite.anims.globalRemove(key);\n
  • Remove from private animation state
    sprite.anims.remove(key);\n
"},{"location":"sprite/#get-animation","title":"Get animation","text":"
  • Get global animation object
    var anim = scene.anims.get(key);\n
  • Get private animation object
    var anim = sprite.anims.get(key);\n
"},{"location":"sprite/#has-animation","title":"Has animation","text":"
  • Has global animation object
    var hasAnim = scene.anims.exists(key);\n
  • Get private animation object
    var hasAnim = sprite.anims.exists(key);\n
"},{"location":"sprite/#play-animation","title":"Play animation","text":"
  • Play
    sprite.play(key);\n// sprite.play(key, ignoreIfPlaying);\n
    • key : Animation key string, or animation config
      • String key of animation
      • Animation config, to override default config
        {\nkey,\nframeRate,\nduration,\ndelay,\nrepeat,\nrepeatDelay,\nyoyo,\nshowOnStart,\nhideOnComplete,\nstartFrame,\ntimeScale\n}\n
  • Play in reverse
    sprite.playReverse(key);\n// sprite.playReverse(key, ignoreIfPlaying);\n
    • key : Animation key string, or animation config
  • Play after delay
    sprite.playAfterDelay(key, delay);\n
    • key : Animation key string, or animation config
  • Play after repeat
    sprite.playAfterRepeat(key, repeatCount);\n
    • key : Animation key string, or animation config
"},{"location":"sprite/#chain","title":"Chain","text":"
  • Chain next animation
    sprite.chain(key);\n
    • key : Animation key string, or animation config
  • Chain next and next animation
    sprite.chain(key0).chain(key1);\n
    • key0, key1 : Animation key string, or animation config
"},{"location":"sprite/#stop","title":"Stop","text":"
  • Immediately stop
    sprite.stop();\n
  • Stop after delay
    sprite.stopAfterDelay(delay);\n
  • Stop at frame
    sprite.stopOnFrame(frame);\n
    • frame : Frame object in current animation.
      var currentAnim = sprite.anims.currentAnim;\nvar frame = currentAnim.getFrameAt(index);\n
  • Stop after repeat
    sprite.stopAfterRepeat(repeatCount);\n
"},{"location":"sprite/#restart","title":"Restart","text":"
sprite.anims.restart();\n// sprite.anims.restart(includeDelay, resetRepeats);\n
"},{"location":"sprite/#time-scale","title":"Time scale","text":"
  • Get
    var timeScale = sprite.anims.globalTimeScale;\n
  • Set
    sprite.anims.globalTimeScale = timeScale;\n

See also Global time scale

"},{"location":"sprite/#properties","title":"Properties","text":"
  • Has started
    var hasStarted = sprite.anims.hasStarted;\n
  • Is playing
    var isPlaying = sprite.anims.isPlaying;\n
  • Is paused
    var isPaused = sprite.anims.isPaused;\n
  • Total frames count
    var frameCount = sprite.anims.getTotalFrames();\n
  • Delay
    var delay = sprite.anims.delay;\n
  • Repeat
    • Total repeat count
      var repeatCount = sprite.anims.repeat;\n
    • Repeat counter
      var repeatCount = sprite.anims.repeatCounter;\n
    • Repeat delay
      var repeatDelay = sprite.anims.repeatDelay;\n
    • Yoyo
      var repeatDelay = sprite.anims.yoyo;\n
  • Current animation key
    var key = sprite.anims.getName();\n
    • key : Return '' if not playing any animation.
  • Current frame name
    var frameName = sprite.anims.getFrameName();\n
    • frameName : Return '' if not playing any animation.
  • Current animation
    var currentAnim = sprite.anims.currentAnim;\n
  • Current frame
    var currentFrame = sprite.anims.currentFrame;\n
"},{"location":"sprite/#events","title":"Events","text":"
  • On start
    sprite.on('animationstart', function(currentAnim, currentFrame, sprite){});\n
    sprite.on('animationstart-' + key, function(currentAnim, currentFrame, sprite){});\n
  • On restart
    sprite.on('animationrestart', function(currentAnim, currentFrame, sprite){});\n
    sprite.on('animationrestart-' + key, function(currentAnim, currentFrame, sprite){});\n
  • On complete
    sprite.on('animationcomplete', function(currentAnim, currentFramee, sprite){});\n
    sprite.on('animationcomplete-' + key, function(currentAnim, currentFramee, sprite){});\n
  • On stop
    sprite.on('animationstop', function(currentAnim, currentFrame, sprite){});\n
    sprite.on('animationstop-' + key, function(currentAnim, currentFrame, sprite){});\n
  • On update
    sprite.on('animationupdate', function(currentAnim, currentFrame, sprite){});\n
    sprite.on('animationupdate-' + key, function(currentAnim, currentFrame, sprite){});\n
  • On repeat
    sprite.on('animationrepeat', function(currentAnim, currentFrame, sprite){});\n
    sprite.on('animationrepeat-' + key, function(currentAnim, currentFrame, sprite){});\n
"},{"location":"statemanager/","title":"State manager","text":""},{"location":"statemanager/#introduction","title":"Introduction","text":"

Another version of Finite state machine.

  • Author: Rex
  • Object
"},{"location":"statemanager/#usage","title":"Usage","text":"

Sample code

"},{"location":"statemanager/#install-plugin","title":"Install plugin","text":""},{"location":"statemanager/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexstatemanagerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexstatemanagerplugin.min.js', true);\n
  • Add StateManager object
    var states = scene.plugins.get('rexstatemanagerplugin').add(config);\n
"},{"location":"statemanager/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import StateManagerPlugin from 'phaser3-rex-plugins/plugins/statemanager-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexStateManager',\nplugin: StateManagerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add StateManager object
    var states = scene.plugins.get('rexStateManager').add(config);\n
"},{"location":"statemanager/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import StateManager from 'phaser3-rex-plugins/plugins/statemanager.js';\n
  • Add StateManager object
    var states = new StateManager(config);\n
"},{"location":"statemanager/#create-instance","title":"Create instance","text":"
var states = scene.plugins.get('rexStateManager').add({\neventEmitter: undefined\n});\n
  • eventEmitter
    • undefined : Create a private event emitter, default value.
    • false : Don't add any event emitter, i.e. no event will be fired.
    • Event emitter object : Fire event through this event emitter.
"},{"location":"statemanager/#custom-class","title":"Custom class","text":"
  • Define class
    class MyStates extends StateManager {\nconstructor(config) {\nsuper(config);\n\nthis.addStates({\nA: {\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {}\n},\n// ...\n});\n}\n}\n
  • Create instance
    var states = new MyStates(config);\n
"},{"location":"statemanager/#add-new-state","title":"Add new state","text":"

states.addState(name, {\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {}\n})\n
states.addState({\nname: 'A',\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {}\n})\n

or

states.addStates({\n'A' : {\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {}\n},\n// ...\n})\n
states.addStates([\n{\nname: 'A',\nnext: 'B',  // function() { return 'B'; }\nenter: function() {},\nexit: function() {}\n},\n// ...\n]);\n

"},{"location":"statemanager/#read-state","title":"Read state","text":"
  • Current state
    var curState = state.state;\n
  • Previous state
    var preState = state.prevState;\n
"},{"location":"statemanager/#start-at-state","title":"Start at state","text":"

Set new state without triggering any state-changing callbacks or events.

state.start(newState);\n
"},{"location":"statemanager/#next-state","title":"Next state","text":"
graph TB\n\nnext[\"states.next()\"] --> next_A[\"stateA.next()<br>return 'B'\"]\n\nnext_A --> eventStateChange[\"states.emit('statechange', states)<br>states.prevState -> states.state\"]\n\nsubgraph State changing\n\neventStateChange --> exit_A[\"stateA.exit()\"]\nexit_A --> eventExitA[\"states.emit('exit_A', states)\"]\n\neventExitA --> enter_B[\"stateB.enter()\"]\nenter_B --> eventEnterB[\"states.emit('enter_B', states)\"]\n\nsubgraph Exit\nexit_A\neventExitA\nend\n\nsubgraph Enter\nenter_B\neventEnterB\nend\n\nend\n\ngoto[\"states.goto('B')\"] --> eventStateChange\n\nsubgraph Request\n\nsubgraph Next\nnext\nnext_A\nend\n\nsubgraph Goto\ngoto\nend\n\nend
"},{"location":"statemanager/#request","title":"Request","text":"
  • Get next state by callback
    states.next();    // nextState = stateA.next()    \n
  • Goto state
    states.goto(nextState);\n// states.state = nextState;\n
"},{"location":"statemanager/#state-changing","title":"State-changing","text":"

These callbacks or events will be triggered if state is changing.

For example, state is changing from 'A' to 'B'.

  1. event statechange
    states.on('statechange', function(states) {\nconsole.log( states.prevState + '->' + states.state );\n});\n
  2. callback stateA.exit
  3. event exit_A
    states.on('exit_A', function(states) {\n/*...*/\n});\n
  4. callback stateB.enter
  5. event enter_B
    states.on('enter_B', function(states) {\n/*...*/\n});\n
"},{"location":"statemanager/#enable","title":"Enable","text":"
states.setEnable();\n// states.setEnable(false); // disable\n

or

states.toggleEnable();\n

states.next() and states.goto() will be ignored if disabled.

"},{"location":"statemanager/#update","title":"Update","text":"
  • Start
    states.startUpdate();\nstates.startPreUpdate();\nstates.startPostUpdate();\n// Assume that `scene` is assigned in config of constructor\n
    or
    states.startUpdate(scene);\nstates.startPreUpdate(scene);\nstates.startPostUpdate(scene);\n
    • scene : Scene object
  • Stop
    states.stopUpdate();\nstates.stopPreUpdate();\nstates.stopPostUpdate();\n
  • Get scene
    var scene = states.getScene();\n// var scene = states._scene;\n
"},{"location":"statemanager/#remove-state","title":"Remove state","text":"
  • Remve a state
    states.removeState(stateName);\n
  • Remve all states
    states.removeAllStates();\n
"},{"location":"step/","title":"Step","text":""},{"location":"step/#introduction","title":"Introduction","text":"

Interpolate points between previous position and current position with fixed step length.

  • Author: Rex
  • Behavior of game object
"},{"location":"step/#live-demos","title":"Live demos","text":"
  • Step
"},{"location":"step/#usage","title":"Usage","text":"

Sample code

"},{"location":"step/#install-plugin","title":"Install plugin","text":""},{"location":"step/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexstepplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexstepplugin.min.js', true);\n
  • Add step behavior
    var step = scene.plugins.get('rexstepplugin').add(gameObject, config);\n
"},{"location":"step/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import StepPlugin from 'phaser3-rex-plugins/plugins/step-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexStep',\nplugin: StepPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add move-to behavior
    var step = scene.plugins.get('rexStep').add(gameObject, config);\n
"},{"location":"step/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Step from 'phaser3-rex-plugins/plugins/step.js';\n
  • Add move-to behavior
    var step = new Step(gameObject, config);\n
"},{"location":"step/#create-instance","title":"Create instance","text":"
var step = scene.plugins.get('rexStep').add(gameObject, {\n// enable: true,\n// stepLength: 5,    \n});\n
  • enable : Set true to fire step event for each interpolate point.
  • stepLength : Fixed length between each interpolate point.
"},{"location":"step/#enable","title":"Enable","text":"
  • Enable (default)
    step.setEnable();\n
    or
    step.enable = true;\n
  • Disable
    step.setEnable(false);\n
    or
    step.enable = false;\n
"},{"location":"step/#set-step-length","title":"Set step length","text":"
step.setStepLength(stepLength);\n// step.stepLength = stepLength;\n
"},{"location":"step/#events","title":"Events","text":"
  • On each interpolate point
    step.on('step', function(gameObject, step, x, y){\n\n}, scope);\n
    • Invoke step.cancelStep() to cancel interpolation.
  • On interpolate points between previous position and current position
    step.on('steps', function(gameObject, step, points){\n\n}, scope);\n
    • points : Array of point {x, y}
"},{"location":"step/#inject-methods","title":"Inject methods","text":"
  • Inject methods into game object
    scene.plugins.get('rexStep').injectMethods(gameObject);\n
  • Inject methods into class of game object
    scene.plugins.get('rexStep').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexStep').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into class of game object
    scene.plugins.get('rexStep').injectMethods(GameObjectClass.prototype);\n// scene.plugins.get('rexStep').injectMethods(Phaser.GameObjects.Sprite.prototype);\n
  • Inject methods into root class of game object
    scene.plugins.get('rexStep').injectMethodsToRootClass(e);\n// scene.plugins.get('rexStep').injectMethods(Phaser.GameObjects.GameObject.prototype);\n
"},{"location":"step/#injected-methods","title":"Injected methods","text":"
  • Step start
    gameObject.stepStart(stepLength);\n// gameObject.stepStart({stepLength});\n
  • Step stop
    gameObject.stepStop();\n
  • Events
    • Step
      gameObject.on('step.step', function(gameObject, x, y) { });\n
"},{"location":"structs-list/","title":"List","text":""},{"location":"structs-list/#introduction","title":"Introduction","text":"

An ordered list, built-in data structure of phaser.

  • Author: Richard Davey
"},{"location":"structs-list/#usage","title":"Usage","text":""},{"location":"structs-list/#create-instance","title":"Create instance","text":"
var list = new Phaser.Structs.List();\n
"},{"location":"structs-list/#add-child","title":"Add child","text":"
list.add(child);\n
list.addAt(child, index);\n
"},{"location":"structs-list/#exist","title":"Exist","text":"
var hasChild = list.exists(child);\n
"},{"location":"structs-list/#get-child","title":"Get child","text":"
var firstChild = list.first;\nvar nextChild = list.next;\nvar prevChild = list.previous;\nvar lastChild = list.last;\n
var child = list.getByName(name);\n
var child = list.getRandom(startIndex, length);\n
var child = list.getFirst(property, value, startIndex, endIndex);\n// value: the value to test the property against. Must pass a strict (`===`) comparison check.\n
var child = list.getAll(property, value, startIndex, endIndex);\n// value: the value to test the property against. Must pass a strict (`===`) comparison check.\n
var child = list.count(property, value);\n// value: the value to test the property against. Must pass a strict (`===`) comparison check.\n
"},{"location":"structs-list/#get-children","title":"Get children","text":"
var children = list.list;\n
"},{"location":"structs-list/#sort-children","title":"Sort children","text":"
  • Sort by property
    list.sort(property);\n// list.sort(property, handler);\n
    • property : The property to lexically sort by.
    • handler :
      function (childA, childB) {\nreturn 0; // 0, 1, -1\n}\n
"},{"location":"structs-list/#remove-child","title":"Remove child","text":"
list.remove(child);\n
list.removeAt(index);\n
list.removeBetween(startIndex, endIndex);\n
list.removeAll();\n
"},{"location":"structs-list/#order-of-child","title":"Order of child","text":"
list.moveTo(child, index);\n
list.bringToTop(child);\n
list.sendToBack(child);\n
list.moveUp(child);\n
list.moveDown(child);\n
list.moveAbove(child1, child2);  // Move child1 above child2\n
list.moveBelow(child1, child2);  // Move child1 below child2\n
list.swap(child1, child2);\n
list.reverse();\n
list.shuffle();\n
"},{"location":"structs-list/#replace-child","title":"Replace child","text":"
list.replace(oldChild, newChild);\n
"},{"location":"structs-list/#set-properties","title":"Set properties","text":"
list.setAll(property, value, startIndex, endIndex);\n
"},{"location":"structs-list/#for-each-child","title":"For each child","text":"
  • Iterate current children list
    list.each(callback);\n// list.each(callback, context);\n// list.iterate(callback, context, arg0, arg1, ...);\n
    • callback :
      function(child, arg0, arg1, ...) {\n\n}\n
"},{"location":"structs-list/#children-counts","title":"Children counts","text":"
var size = list.length;\n
"},{"location":"structs-set/","title":"Set","text":""},{"location":"structs-set/#introduction","title":"Introduction","text":"

A collection of unique elements, built-in data structure of phaser.

  • Author: Richard Davey
"},{"location":"structs-set/#usage","title":"Usage","text":""},{"location":"structs-set/#create-instance","title":"Create instance","text":"
var set = new Phaser.Structs.Set();\n

or

var set = new Phaser.Structs.Set(elements);\n
"},{"location":"structs-set/#add-an-element","title":"Add an element","text":"
set.set(element);\n
"},{"location":"structs-set/#remove-an-element","title":"Remove an element","text":"
set.delete(element);\n
"},{"location":"structs-set/#remove-all-elements","title":"Remove all elements","text":"
set.clear();\n
"},{"location":"structs-set/#has-element","title":"Has element","text":"
set.contains(element);\n
"},{"location":"structs-set/#get-elements","title":"Get elements","text":"
var elements = set.entries;\n

or get a shallow copy of elements

var elements = set.getArray();\n
"},{"location":"structs-set/#element-counts","title":"Element counts","text":"
var size = set.size;\n
"},{"location":"structs-set/#for-each-element","title":"For each element","text":"
  • For when you know this Set will be modified during the iteration.
    set.each(function(element, index) {\n// return false;  // return false to cancel iteration\n}, scope)\n
  • For when you absolutely know this Set won't be modified during the iteration.
    set.iterate(function(element, index) {\n// return false;  // return false to cancel iteration\n}, scope)\n
"},{"location":"structs-set/#set-operations","title":"Set operations","text":"
  • C = A | B
    var setC = setA.union(setB);\n
  • C = A & B
    var setC = setA.intersect(setB);\n
  • C = A - B
    var setC = setA.difference(setB);\n
"},{"location":"tagplayer/","title":"Tag player","text":""},{"location":"tagplayer/#introduction","title":"Introduction","text":"

Text commands to control sprites, texts, sound effect or backgroun music.

  • Author: Rex
  • Member of scene
"},{"location":"tagplayer/#live-demos","title":"Live demos","text":"
  • Sprite
  • Textbox
  • Custom game object
  • Viewport-coordinate
"},{"location":"tagplayer/#usage","title":"Usage","text":"

Sample code

"},{"location":"tagplayer/#install-plugin","title":"Install plugin","text":""},{"location":"tagplayer/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextagplayerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextagplayerplugin.min.js', true);\n
  • Add tag-player object
    var tagPlayer = scene.plugins.get('rextagplayerplugin').add(scene, config);\n
"},{"location":"tagplayer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TagPlayerPlugin from 'phaser3-rex-plugins/plugins/tagplayer-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTagPlayerPlugin',\nplugin: TagPlayerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add tag-player object
    var tagPlayer = scene.plugins.get('rexTagPlayerPlugin').add(scene, config);\n
"},{"location":"tagplayer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TagPlayer from 'phaser3-rex-plugins/plugins/tagplayer.js';\n
  • Add tag-player object
    var tagPlayer = new TagPlayer(scene, config);\n
"},{"location":"tagplayer/#create-instance","title":"Create instance","text":"
var tagPlayer = scene.plugins.get('rexTagPlayerPlugin').add(scene, {\nparser: {\ndelimiters: '[]',\ncomment: '//',\n// translateTagNameCallback: undefined,\n}\n\nsprites: {\n// createGameObject: 'sprite',\n// fade: 500,  \n// fade: {mode: 'tint', time: 500},\n// viewportCoordinate: false,\n// symbols: undefined,  // { key:value }\n}, // sprites: false,\n\ntexts: {\n// createGameObject: undefined,        \n// fade: 500,\n// fade: {mode: 'tint', time: 500},\n// viewportCoordinate: false,\n// symbols: undefined,  // { key:value }\n}\n// texts: false,\n\nlayers: undefined, // []\n\nsounds: {\nbgm: {\ninitial: undefinied,\nloop: true,\nfade: 500\n},\nbgm2: {\ninitial: undefinied,\nloop: true,\nfade: 500\n}\n},\n\nclickTarget: scene,\n});\n
  • parser : Configuration of parser.
    • parser.delimiters : Delimiters of tag.
      • A single string with 2 characters. Default value is '[]'.
      • A array with 2 strings. e.x. ['[[',']]'].
    • parser.comment : Start word of a comment line. Default value is '//'.
      • null, or false : No comment line.
    • parser.translateTagNameCallback : Callback to translate tag-name
      • undefined : Use original tag-name. Default behavior.
      • A function, return new tag name.
        function(tagName) {\nreturn newTagName;\n}\n
  • sprites : Configuration of sprites.
    • sprites.createGameObject :
      • 'sprite' : Create sprite game object. Default behavior.
      • 'image' : Create image game object.
      • Callback to return a game object
        function(scene, a, b, c) {\n// return gameObject;\n}\n
        • a, b, c : Parameters pass from [sprite.name=a,b,c]
    • sprites.fade :
      • 0 : No fade-in or fade-out when adding or removing a sprite.
      • A number : Duration of fading. Default value is 500.
      • A plain object contains mode, time
        • sprite.fade.mode : Fade mode
          • 'tint', or 0 : Fade-in or fade-out via tint property.
          • 'alpha', or 1 : Fade-in or fade-out via alpha property.
          • 'revealUp', or 2 : Reveal up for fade-in.
          • 'revealDown', or 3 : Reveal down for fade-in.
          • 'revealLeft', or 4 : Reveal left for fade-in.
          • 'revealRight', or 5 : Reveal right for fade-in.
        • sprite.fade.time : Duration of fading. Default value is 500.
    • sprites.viewportCoordinate : Apply viewportCoordinate behavior to sprite game object.
      • true : Attach vpx, vpy, vp to sprite game object.
        • vpx, vpy : Number between 0~1. Proportion of viewport.
        • vp : Viewport in rectangle
      • false : Do nothing, default behavior.
    • sprites.symbols : Convert string value to number value when Set or Ease property of game object.
      • A plain object contains string key and number value.
    • false, null : No sprite manager
  • texts : Configuration of texts.
    • texts.createGameObject :
      • undefined, or 'text' : Create text game object. Default behavior.
      • Callback to return a game object
        function(scene, a, b, c) {\n// return gameObject;\n}\n
        • a, b, c : Parameters pass from [text.name=a,b,c]
    • texts.fade :
      • 0 : No fade-in or fade-out when adding or removing a text game object.
      • A number : Duration of fading. Default value is 500.
      • A plain object contains mode, time
        • texts.fade.mode : Fade mode
          • 'tint', or 0 : Fade-in or fade-out via tint property.
          • 'alpha', or 1 : Fade-in or fade-out via alpha property.
          • 'revealUp', or 2 : Reveal up for fade-in.
          • 'revealDown', or 3 : Reveal down for fade-in.
          • 'revealLeft', or 4 : Reveal left for fade-in.
          • 'revealRight', or 5 : Reveal right for fade-in.
        • texts.fade.time : Duration of fading. Default value is 500.
    • texts.viewportCoordinate : Apply viewportCoordinate behavior to text game object.
      • true : Attach vpx, vpy, vp to sprite game object.
        • vpx, vpy : Number between 0~1. Proportion of viewport.
        • vp : Viewport in rectangle
      • false : Do nothing, default behavior.
    • texts.symbols : Convert string value to number value when Set or Ease property of game object.
      • A plain object contains string key and number value.
    • false, null : No text manager
  • layers :
    • undefined : Don't create layerManger.
    • Array of string : Pre-create layer game objects in layerManger.
  • sounds : Configuration of sound effect, or background music.
    • sounds.bgm.initial, sounds.bgm2.initial : Initial music instance created by scene.sound.add(key) before starting playing content.
      • undefined : No initial music instance, default value.
    • sounds.bgm.loop, sounds.bgm2.loop :
      • true : Loop background music, default behavior.
      • false : Play background music once.
    • sounds.bgm.fade, sounds.bgm2.fade :
      • 0 : No fade-in or fade-out when starting or stopping a background music.
      • A number : Fade-in or fade-out (cross-fade) when starting or stopping a background music. Default value is 500.
  • clickTarget : Click target.
    • scene : Any pointer down on this scene. Default target.
"},{"location":"tagplayer/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTagPlayer extends TagPlayer {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\n}\n// ...\n}\n
  • Create instance
    var tagPlayer = new MyTagPlayer(scene, config);\n
"},{"location":"tagplayer/#game-object-manager","title":"Game object manager","text":"
tagPlayer.addGameObjectManager({\nname: goType,\ncreateGameObject: function(scene, ...) {\nreturn gameObject\n},\n\n// fade: 500,\n// fade: {mode: 'tint', time: 500},\n\n// viewportCoordinate: false,\n// viewportCoordinate: { viewport: new Phaser.Geom.Rectangle() },\n\n// defaultLayer: layerName,\n\n// symbols: undefined,  // { key:value },\n})\n
  • name : Name of this game object manager, a string.
  • createGameObject : Callback to return a game object
    function(scene, a, b, c) {\n// return gameObject;\n}\n
    • a, b, c : Parameters pass from [goType.name=a,b,c]
  • fade : Tint-fade (if game object has tint property) or alpha-fade game object when creating or destroying a game object.
    • 0 : No fade-in or fade-out when adding or removing a game object.
    • A number : Duration of fading. Default value is 500.
    • A plain object contains mode, time
      • fade.mode : Fade mode
        • 'tint', or 0 : Fade-in or fade-out via tint property.
        • 'alpha', or 1 : Fade-in or fade-out via alpha property.
        • 'revealUp', or 2 : Reveal up for fade-in.
        • 'revealDown', or 3 : Reveal down for fade-in.
        • 'revealLeft', or 4 : Reveal left for fade-in.
        • 'revealRight', or 5 : Reveal right for fade-in.
      • fade.time : Duration of fading. Default value is 500.
  • viewportCoordinate : Apply viewportCoordinate behavior to sprite game object.
    • false : Do nothing, default behavior.
    • true, or an object :
      • viewport :
        • undefined : Rectangle of display area under main camera of current scene. Default value.
        • A rectangle
  • defaultLayer : Put this game object into layer inside of layerManager.
  • symbols : Convert string value to number value when Set or Ease property of game object.
    • A plain object contains string key and number value.
"},{"location":"tagplayer/#built-in-commands","title":"Built-in commands","text":"

goType : name parameter in config of tagPlayer.addGameObjectManager method

  • Add game object : [goType.name=a,b,c]
    • Tint-fade-in, or alpha-fade-in if fade is not 0
  • Remove game object : [/goType.name]
    • Tint-fade-out, or alpha-fade-out if fade is not 0
  • Remove all game objects : [/goType]
    • Tint-fade-out, or alpha-fade-out if fade is not 0
  • Call method : [goType.name.methodName=value0,value1,value2]
  • Set property : [goType.name.x=value], [goType.name.alpha=value], ....
  • Ease property :
    [goType.name.prop.easeMode=value,duration]\n[goType.name.prop.easeMode=value,duration,repeat]\n[goType.name.prop.easeMode=value,duration,easeFunction,repeat]\n[goType.name.prop.easeMode=value]\n
    • prop : Any number property of this sprite.
    • easeMode : One of these modes
      • to, toLeft, toRight, toUp, toDown
      • yoyo, yoyoLeft, yoyoRight, yoyoUp, yoyoDown
      • from, fromLeft, fromRight, fromUp, fromDown
    • duration : Default value is 1000
    • easeFunction : Default value is 'Linear'
    • repeat : Default value is 0
  • Wait ease task of game object's number property : [wait=goType.name.prop]
    • Also fire event 'wait.' + goType
      tagPlayer.on('wait.' + goType, function(name, prop) {\n})\n
  • Wait a game objects are destroyed : [wait=goType.name]
    • Also fire event 'wait.' + goType
      tagPlayer.on('wait.' + goType, function(name, prop) {\n// prop parameter are `undefined` here\n})\n
  • Wait all game objects are destroyed : [wait=goType]
    • Also fire event 'wait.' + goType
      tagPlayer.on('wait.' + goType, function(name, prop) {\n// name and prop parameter are `undefined` here\n})\n
  • Wait boolean data in game object's data manager set to true/false : [wait=goType.name.dataKey]/[wait=goType.name.!dataKey]
    • Also fire event 'wait.' + goType
      tagPlayer.on('wait.' + goType, function(name, prop) {\n})\n
"},{"location":"tagplayer/#execute-commands","title":"Execute commands","text":"
tagPlayer.play(commands);\n

or

tagPlayer.playPromise(commands)\n.then(function(){\n// Typing content complete\n})\n
"},{"location":"tagplayer/#pause","title":"Pause","text":"
  • Pause
    tagPlayer.pause();\n
  • Pause until event
    tagPlayer.pauseUntilEvent(eventEmitter, eventName);\n
  • Is paused (not playing)
    var isPaused = !tagPlayer.isPlaying;\n

Invoke this method during tag-start,tag-end, or content events to suspend parsing.

"},{"location":"tagplayer/#resume","title":"Resume","text":"
tagPlayer.resume();\n
"},{"location":"tagplayer/#time-scale","title":"Time scale","text":"

Time scale of typing, typing animation, sprite animation and easing of sprite's properties.

  • Get
    var timeScale = tagPlayer.timeScale;\n
  • Set
    tagPlayer.setTimeScale(timeScale);    
    tagPlayer.timeScale = timeScale;\n
"},{"location":"tagplayer/#events","title":"Events","text":"
  • On typing content complete
    tagPlayer.on('complete', function() {\n\n})\n
"},{"location":"tagplayer/#tags-of-content","title":"Tags of content","text":""},{"location":"tagplayer/#sprite","title":"Sprite","text":"
  • Add sprite : [sprite.name=textureKey,frameKey]
    • Tint-fade-in if sprite.fade is not 0
  • Remove sprite : [/sprite.name]
    • Tint-fade-out if sprite.fade is not 0
  • Remove all sprites : [/sprite]
    • Tint-fade-out if sprite.fade is not 0
  • Call method : [sprite.name.methodName=value0,value1,value2]
  • Set property : [sprite.name.x=value], [sprite.name.alpha=value], ....
  • Ease property :
    [sprite.name.prop.easeMode=value,duration]\n[sprite.name.prop.easeMode=value,duration,repeat]\n[sprite.name.prop.easeMode=value,duration,easeFunction,repeat]\n[sprite.name.prop.easeMode=value]\n
    • prop : Any number property of this sprite.
    • easeMode : One of these modes
      • to, toLeft, toRight, toUp, toDown
      • yoyo, yoyoLeft, yoyoRight, yoyoUp, yoyoDown
      • from, fromLeft, fromRight, fromUp, fromDown
    • duration : Default value is 1000
    • easeFunction : Default value is 'Linear'
    • repeat : Default value is 0
  • Set texture : [sprite.name.texture=textureKey,frameKey]
  • Play animation : [sprite.name.play=animationKey], or [sprite.name.play=animationKey0,animationKey1,...]
    • Can play animation without adding sprite first.
  • Stop animation : [/sprite.name.play], or [sprite.name.stop]
  • Pause animation : [sprite.name.pause]
"},{"location":"tagplayer/#text","title":"Text","text":"
  • Add text : [text.name]
    • Tint-fade-in if text.fade is not 0
  • Remove text : [/text.name]
    • Tint-fade-out if text.fade is not 0
  • Remove all texts : [/text]
    • Tint-fade-out if text.fade is not 0
  • Call method : [text.name.methodName=value0,value1,value2]
  • Set property : [text.name.x=value], [text.name.alpha=value], ....
  • Ease property :
    [sprite.name.prop.easeMode=value,duration]\n[sprite.name.prop.easeMode=value,duration,repeat]\n[sprite.name.prop.easeMode=value,duration,easeFunction,repeat]\n[sprite.name.prop.easeMode=value]\n
    • prop : Any number property of this sprite.
    • easeMode : One of these modes
      • to, toLeft, toRight, toUp, toDown
      • yoyo, yoyoLeft, yoyoRight, yoyoUp, yoyoDown
      • from, fromLeft, fromRight, fromUp, fromDown
    • duration : Default value is 1000
    • easeFunction : Default value is 'Linear'
    • repeat : Default value is 0
  • Set text
    [text.name.text]\ncontent\\\\n\nnewline\\\\n\nnewline\n
  • Typing text
    [text.name.typing]\n// [text.name.typing=speed]\ncontent\\\\n\nnewline\\\\n\nnewline\n
"},{"location":"tagplayer/#sound-effect","title":"Sound effect","text":"
  • Play : [se=key], [se2=key]
    • Sound effect will be destroyed when complete
  • Play with fade in volume : [se=key,1000], [se2=key,1000]
  • Fade in volume : [se.fadein=1000], [se2.fadein=1000]
  • Fade out volume : [se.fadeout=1000], [se2.fadeout=1000]
  • Fade out volume then stop : [se.fadeout=1000,stop], [se2.fadeout=1000,stop]
  • Set volume : [se.volume=1], [se2.volume=1]
"},{"location":"tagplayer/#background-music","title":"Background music","text":"
  • Play, stop : [bgm=key], [/bgm], [bgm2=key], [/bgm2]
    • Previous background music will be stopped and destroyed.
    • Cross fade to next background music if sounds.bgm.fade/sounds.bgm2.fade is not 0
  • Play with fade in volume : [bgm=key,1000], [bgm2=key,1000]
  • Pause, resume : [bgm.pause], [/bgm.pause], [bgm2.pause], [/bgm2.pause]
  • Fade in volume : [bgm.fadein=1000], [bgm2.fadein=1000]
  • Fade out volume : [bgm.fadeout=1000], [bgm2.fadeout=1000]
  • Fade out volume then stop : [bgm.fadeout=1000,stop], [bgm2.fadeout=1000,stop]
  • Cross fade to another background music : [bgm.cross=key,10000], [bgm2.cross=key,10000]
  • Set volume : [bgm.volume=1], [bgm2.volume=1]
  • Mute : [bgm.mute], [bgm2.mute], [bgm.unmute], [bgm2.unmute]
"},{"location":"tagplayer/#camera","title":"Camera","text":"
  • Fade-in effect : [camera.fadein], [camera.fadein=1000], or [camera.fadein=duration,red,green,blue]
  • Fade-out effect : [camera.fadeout], [camera.fadeout=1000], or [camera.fadeout=duration,red,green,blue]
  • Flash effect : [camera.flash], [camera.flash=1000], or [camera.flash=duration,red,green,blue]
  • Shake effect : [camera.shake], [camera.shake=1000], or [camera.shake=duration,intensity]
  • Zoom
    • Set zoom : [camera.zoom=2]
    • Zoom to : [camera.zoom.to=1,1000], or [camera.zoom.to=zoomValue,duration,Cubic]
  • Rotate
    • Set angle : [camera.rotate=90], angle in degrees
    • Rotate to : [camera.rotate.to=0,1000], or [camera.rotate.to=deg,duration,Cubic], angle in degrees
  • Scroll
    • Scroll x,y : [camera.scroll=0,200]
    • Scroll x,y to : [camera.scroll.to=0,200,1000], or [camera.rotate.to=x,y,duration,Cubic]
"},{"location":"tagplayer/#wait-conditions","title":"Wait conditions","text":"
  • Wait click : [wait=click], [click]
    • Also fire event 'wait.click'
       tagPlayer.on('wait.click', function() {\n})\n
  • Wait key-down : [wait=enter], [wait=space], ....
    • Also fire event 'wait.keydown'
       tagPlayer.on('wait.keydown', function(keyName) {\n})\n
  • Wait time : [wait=1000]
    • Also fire event 'wait.time'
       tagPlayer.on('wait.time', function(time) {\n})\n
  • Wait sound effect : [wait=se], [wait=se2]
    • Also fire event 'wait.music'
       tagPlayer.on('wait.music', function(music) {\n// var key = music.key;\n})\n
  • Wait background music : [wait=bgm], [wait=bgm2]
    • Also fire event 'wait.music'
       tagPlayer.on('wait.music', function(music) {\n// var key = music.key;\n})\n
  • Wait camera effect : [wait=camera.fadein], [wait=camera.fadeout], [wait=camera.flash], [wait=camera.shake], [wait=camera.zoom], [wait=camera.rotate], [wait=camera.scroll]
    • Also fire event 'wait.camera'
       tagPlayer.on('wait.camera', function(effectName) {\n// effectName : 'camera.fadein', 'camera.fadeout', 'camera.flash', 'camera.shake', 'camera.zoom', 'camera.rotate', 'camera.scroll'\n})\n
  • Wait ease task of sprite's property : [wait=sprite.name.prop]
    • Also fire event 'wait.sprite'
      tagPlayer.on('wait.sprite', function(name, prop) {\n})\n
  • Wait a sprite are destroyed : [wait=sprite.name]
    • Also fire event 'wait.sprite'
      tagPlayer.on('wait.sprite', function(name, prop) {\n// prop parameter are `undefined` here\n})\n
  • Wait all sprites are destroyed : [wait=sprite]
    • Also fire event 'wait.sprite'
      tagPlayer.on('wait.sprite', function(name, prop) {\n// name and prop parameter are `undefined` here\n})\n
  • Wait boolean data in sprite's data manager set to true/false : [wait=sprite.name.dataKey]/[wait=sprite.name.!dataKey]
    • Also fire event 'wait.sprite'
      tagPlayer.on('wait.sprite', function(name, prop) {\n})\n
  • Wait callback : [wait], or [wait=xxx] (xxx is any string which not been used in above case)
    • Fire event 'wait'
      tagPlayer.on('wait', function(callback) {\n// Invoke `callback()` to continue typing\n})\n
    • Fire event 'wait.xxx'
      tagPlayer.on('wait.xxx', function(callback) {\n// Invoke `callback()` to continue typing\n})\n
  • Combine conditions : [wait=cond0|cond1|...]
    • Wait click, or enter key down : [wait=click|enter]
    • Wait click, enter key down, or 100ms : [wait=click|enter|1000]
"},{"location":"tagplayer/#custom-tag","title":"Custom tag","text":"

Assume that adding a custom tag : [custom=10,20][/custom]

  • On parse/execute a +custom tag, will add a custom command child
    tagPlayer.on('+custom', function(parser, a, b) {\n// console.log('Parse +custom tag:', a, b)\n})\n
    • a, b, ... : Parameters after =
    • Set content callback, will invoke this callback when getting a content
      var callback = function(content) {\n// ...\n}\ntagPlayer.setContentCallback(callback, scope);\n
  • On parse/execute a -custom tag, will add a custom command child
    tagPlayer.on('-custom', function(parser) {\n// console.log('Parse -custom tag')\n})\n
    • Clear content callback
      tagPlayer.setContentCallback();\n
"},{"location":"tagplayer/#content","title":"Content","text":"

These lines will be skipped :

  • Empty line, which only has space characters.
  • Comment line, start with '//'.

New line symbol '\\n' will be removed, use \\\\n to insert a new line character.

Content will pass to one of these callback/event

  1. Set content callback
    tagPlayer.setContentCallback(callback, scope);\n
    • Clear content callback
      tagPlayer.setContentCallback();\n
  2. On parse/execute a content, after a [custom] tag.
    tagPlayer.on('custom#content', function(content) {   })\n
  3. On parse/execute a content, after any tag.
    tagPlayer.on('content', function(content) {   })\n
"},{"location":"tagplayer/#game-objects","title":"Game objects","text":"
  • Get game object by name
    var gameObject = tagPlayer.getGameObject(goType, name);\n
  • Get all game objects of a game object manager
    var gameObjects = tagPlayer.getGameObject(goType);\n
    • gameObjects : {name: gameObject}
  • Add existed game object into game object manager
    tagPlayer.addGameObject(goType, name, gameObject);\n
"},{"location":"tagplayer/#data","title":"Data","text":"
  • Get
    var value = tagPlayer.getData(key);\nvar values = tagPlayer.getData(keys); // keys: an array of keys\nvar value = tagPlayer.data.values[key];\n
  • Set
    tagPlayer.setData(key, value);\ntagPlayer.incData(key, value);    tagPlayer.setData(obj); // obj: {key0:value0, key1:value1, ...}\ntagPlayer.data.values[key] = value;\ntagPlayer.data.values[key] += inc;\n
    or
    tagPlayer.toggleData(key);\n
  • Enable
    tagPlayer.setDataEnabled();\n
  • Events :
    • Set data evant
      tagPlayer.on('setdata', function(tagPlayer, key, value){ /* ... */ });\n
    • Change data event
      tagPlayer.on('changedata', function(tagPlayer, key, value, previousValue){ /* ... */ });\n
      tagPlayer.on('changedata-' + key, function(tagPlayer, value, previousValue){ /* ... */ });\n

See data manager

Note

Ensure data manager is created before binding any data-changed events.

"},{"location":"tagtext/","title":"Tag Text","text":""},{"location":"tagtext/#introduction","title":"Introduction","text":"

Displays text with multi-color, font face, or font size with tags.

  • Author: Rex
  • Game object
"},{"location":"tagtext/#live-demos","title":"Live demos","text":"
  • Tag text
"},{"location":"tagtext/#usage","title":"Usage","text":"

Sample code

"},{"location":"tagtext/#install-plugin","title":"Install plugin","text":""},{"location":"tagtext/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextagtextplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextagtextplugin.min.js', true);\n
  • Add text object
    var txt = scene.add.rexTagText(x, y, content, config);\n
"},{"location":"tagtext/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TagTextPlugin from 'phaser3-rex-plugins/plugins/tagtext-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTagTextPlugin',\nplugin: TagTextPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text object
    var txt = scene.add.rexTagText(x, y, content, config);\n
"},{"location":"tagtext/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TagText from 'phaser3-rex-plugins/plugins/tagtext.js';\n
  • Add text object
    var txt = new TagText(scene, x, y, content, config);\nscene.add.existing(txt);\n
"},{"location":"tagtext/#add-text-object","title":"Add text object","text":"
var tags = {\ntag0: {\ncolor: 'red'\n},\ntag1: {\ncolor: 'blue'\n}\n};\nvar txt = scene.add.rexTagText(x, y, '<class=\"tag0\">h</class>ello', {tags:tags});\n// var txt = scene.add.rexTagText(x, y, '<class=\"tag0\">h</class>ello', { fontFamily: 'Arial', fontSize: 64, color: '#00ff00', tags:tags });\n
  • tags : {tagName:tag}, see Properties of tag.

Default style

{\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\nbackgroundColor2: null,\nbackgroundHorizontalGradient: true,\nbackgroundStrokeColor: null,\nbackgroundStrokeLineWidth: 2,\n\nbackgroundCornerRadius: 0,\n// 0   : no round corner, \n// > 0 : convex round corner\n// < 0 : concave round corner\n\nbackgroundCornerIteration: null, color: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},\nunderline: {\ncolor: '#000',\nthickness: 0,\noffset: 0\n},\nstrikethrough: {\ncolor: '#000',\nthickness: 0,\noffset: 0\n},    // align: 'left',  // Equal to halign\nhalign: 'left', // 'left'|'center'|'right'\nvalign: 'top',  // 'top'|'center'|'bottom'\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\nmaxLines: 0,\nlineSpacing: 0,\nfixedWidth: 0,\nfixedHeight: 0,\nlineSpacing: 0,\ntestString: '|M\u00c9qgy',\n\nwrap: {\nmode: 'none'     // 0|'none'|1|'word'|2|'char'|'character'\nwidth: null\n},\n// wordWrap: { width: 0 },   // Compatible with Text game object\n\n// rtl: false,\nmetrics: false,\n// metrics: {\n//     ascent: 0,\n//     descent: 0,\n//     fontSize: 0\n// },\n\n// images: {\n//    key: { y:-8 }\n// }\n\ntags: {\n//tag0: {\n//  color: 'red'\n//},\n//tag1: {\n//  color: 'blue'\n//}\n}\n}\n
var txt = scene.add.rexTagText({\nx: 0,\ny: 0,\ntext: '',\nstyle: {\nfontSize: '64px',\nfontFamily: 'Arial',\ncolor: '#ffffff',\nalign: 'center',\nbackgroundColor: '#ff00ff',\ntags: {}\n}\n})\n

or

var txt = scene.make.rexTagText({\nx: 100,\ny: 100,\npadding: {\nleft: 64,\nright: 16,\ntop: 20,\nbottom: 40\n//x: 32,    // 32px padding on the left/right\n//y: 16     // 16px padding on the top/bottom\n},\ntext: 'Text\\nGame Object\\nCreated from config',\nstyle: {\nfontSize: '64px',\nfontFamily: 'Arial',\ncolor: '#ffffff',\nalign: 'center',\nbackgroundColor: '#ff00ff',\ntags: {}\n},\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
  • Alignment
    • halign, or align : Horizontal alignment.
      • left, center, right
    • valign : Vertical alignment.
      • top, center, bottom
  • images : See Image
"},{"location":"tagtext/#properties-of-tag","title":"Properties of tag","text":"
{\nfontFamily: 'Courier',   // or 'family', 'font-family'\nfontSize: '16px',        // or 'size', 'font-size'\nfontStyle: 'bold italic',// or 'style', 'font-style'\ncolor: 'red',            // or 'font-color'\nstroke: {\ncolor: 'blue',\nthickness: 1\n},\nshadow: {\ncolor: 'black',\noffsetX: 2,\noffsetY: 2,\nblur: 2\n},\nunderline: {            // or 'u'\ncolor: 'blue',\nthickness: 3,\noffset: -1\n},\nstrikethrough: {        // or 's'\ncolor: 'red',\nthickness: 3,\noffset: -1\n},    y: 0,\nimg: textureKey,\narea: areaKey,\n}\n
"},{"location":"tagtext/#custom-class","title":"Custom class","text":"
  • Define class
    class MyText extends TagText {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyText(scene, x, y, '<class=\"tag0\">h</class>ello', {tags:tags});\n
"},{"location":"tagtext/#add-tag","title":"Add tag","text":"
  • Add a tag
    txt.addTag(name, prop);\n
    • name : Tag name.
    • prop : See Properties of tag
  • Add tags
    txt.addTags({\nname: prop\n});\n
"},{"location":"tagtext/#wrap","title":"Wrap","text":"
  • Wrap by word or character.
    var txt = scene.make.text({\nx: 400,\ny: 100,\ntext: 'The sky above the port was the color of television, tuned to a dead channel.',\norigin: { x: 0.5, y: 0.5 },\nstyle: {\nfont: 'bold 25px Arial',\nfill: 'white',\nwrap: {\nmode: 'word'     // 0|'none'|1|'word'|2|'char'|'character'\nwidth: 300\n}\n}\n});\n
  • Wrap mode
    • Get
      var mode = txt.style.wrapMode;\n
    • Set
      txt.setWrapMode(mode);\n
      • 'none', or 0 : No wrap
      • 'word', or 1 : Word wrap
      • 'character', or 2 : Character wrap
  • Wrap width
    • Get
      var width = txt.style.wrapWidth;\n
    • Set
      txt.setWrapWidth(width);\n// txt.setWordWrapWidth(width);\n
"},{"location":"tagtext/#content","title":"Content","text":"
  • Get source text
    var curContent = txt.text;\n
  • Get plain text
    var plainText = txt.getPlainText();\n
  • Get sub-string
    var text = txt.getText(start, end);\n
  • Set
    txt.setText('<class=\"name1\">wor</class>ld');\n// txt.text = '<class=\"name1\">wor</class>ld';\n
  • Append
    txt.appendText(text);\n// txt.text += '\\n' + text;\n
    or
    txt.appendText(text, false);\n// txt.text += text;\n
"},{"location":"tagtext/#set-style","title":"Set style","text":"
txt.setStyle(style);\ntxt.setFont(font);  // font: {fontFamily, fontSize, fontStyle}\ntxt.setFontFamily(family);\ntxt.setFontSize(size);\ntxt.setFontStyle(style);\n
"},{"location":"tagtext/#color","title":"Color","text":"
  • Text color
    • Get
      var color = txt.style.color;\n
    • Set
      txt.setColor(color);\n
      or
      txt.setFill(color);\n
  • Stroke color, thickness
    • Get
      var color = txt.style.stroke;\nvar thickness = txt.style.strokeThickness;\n
    • Set
      txt.setStroke(color, thickness);\n
    • Clear
      txt.setStroke();\n
  • Underline color, thickness
    • Get
      var color = txt.style.underlineColor;\nvar thickness = txt.style.underlineThickness;\nvar offset = txt.style.underlineOffset;\n
    • Set
      txt.setUnderline(color, thickness, ofset);\ntxt.setUnderlineColor(color);\ntxt.setUnderlineThinkness(thickness);\ntxt.setUnderlineOffset(ofset);\n
  • Strikethrough color, thickness
    • Get
      var color = txt.style.strikethroughColor;\nvar thickness = txt.style.strikethroughThickness;\nvar offset = txt.style.strikethroughOffset;\n
    • Set
      txt.setStrikethrough(color, thickness, ofset);\ntxt.setStrikethroughColor(color);\ntxt.setStrikethroughThinkness(thickness);\ntxt.setStrikethroughOffset(ofset);\n
  • Background
    • Color, or gradient color
      • Get
        var color = txt.style.backgroundColor;\nvar color2 = txt.style.backgroundColor2;\nvar isHorizontalGradient = txt.style.backgroundHorizontalGradient;\n
      • Set
        txt.setBackgroundColor(color);\n// txt.setBackgroundColor(color, color2, isHorizontalGradient);\n
    • Stroke color
      • Get
        var color = txt.style.backgroundStrokeColor;\nvar lineWidth = txt.style.backgroundStrokeLineWidth;\n
      • Set
        txt.setBackgroundStrokeColor(color, lineWidth);\n
    • Round rectangle
      • Get
        var radius = txt.style.backgroundCornerRadius;\nvar iteration = txt.style.backgroundCornerIteration;\n
      • Set
        txt.setBackgroundCornerRadius(radius);\n// txt.setBackgroundCornerRadius(radius, iteration);\n
        • radius :
          • 0 : No round corner
          • > 0 : Convex round corner
          • < 0 : Concave round corner
        • iteration :
          • undefined : Round rectangle
          • 0 : Octagon
  • Shadow
    • Get
      var color = txt.style.shadowColor;\nvar offsetX = txt.style.shadowOffsetX;\nvar offsetY = txt.style.shadowOffsetY;\nvar blur = txt.style.shadowBlur;\nvar stroke = txt.style.shadowStroke;\nvar enabled = txt.style.shadowFill;\n
    • Set
      txt.setShadow(x, y, color, blur, shadowStroke, shadowFill);\ntxt.setShadowOffset(x, y);\ntxt.setShadowColor(color);\ntxt.setShadowBlur(blur);\ntxt.setShadowStroke(enabled);\ntxt.setShadowFill(enabled);\n
"},{"location":"tagtext/#image","title":"Image","text":"
  • Uses texture key as image key by default.
  • Add image render information
    txt.addImage(imgKey, {\nkey: textureKey,\nframe: frameName,\nwidth: undefined,\nheight: undefined,\ny: 0,\nleft: 0,\nright: 0\n});\n
    • imgKey : Image key used in text content, i.e. [img=imgKey].
    • key : Texture key.
    • frame : Frame name.
    • width : Render width, set undefined to use the cut width of frame.
    • height : Render height, set undefined to use the cut height of frame.
    • y : Extra offset y.
    • left : Left padding space.
    • Right : Right padding space.
  • Add some image render informations
    txt.addImage(data);\n
    • data : {imgKey, config}
"},{"location":"tagtext/#hit-area-of-words","title":"Hit area of words","text":""},{"location":"tagtext/#hitting-events","title":"Hitting events","text":"
  • Pointer down
    txt.on('areadown', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areadown-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
  • Pointer up
    txt.on('areaup', function(key, pointer, localX, localY, event){\n\n}, scope)\n
    or
    txt.on('areaup-' + key, function(pointer, localX, localY, event){\n\n}, scope)\n
"},{"location":"tagtext/#draw-hit-areas","title":"Draw hit-areas","text":"
txt.drawAreaBounds(graphics, color);\n
  • graphics : Graphics game object
  • color : Default value is 0xffffff
"},{"location":"tagtext/#line-spacing","title":"Line spacing","text":"

This value is added to the height of the font when calculating the overall line height.

  • Get
    var lineSpacing = txt.style.lineSpacing;\n
  • Set
    txt.setLineSpacing(value);\n
"},{"location":"tagtext/#padding","title":"Padding","text":"
  • Get
    var left = txt.padding.left;\nvar top = txt.padding.top;\nvar right = txt.padding.right;\nvar bottom = txt.padding.bottom;\n
  • Set
    txt.setPadding(left, top, right, bottom);\n// txt.setPadding(padding); // padding: {left, top, right, bottom}\n
"},{"location":"tagtext/#max-lines","title":"Max lines","text":"
  • Get
    var maxLines = txt.style.maxLines;\n
  • Set
    txt.setMaxLines(max);\n
"},{"location":"tagtext/#fixed-size","title":"Fixed size","text":"
  • Get
    var width = txt.style.fixedWidth;\nvar height = txt.style.fixedHeight;\n
  • Set
    txt.setFixedSize(width, height);\n
"},{"location":"tagtext/#left-margin-of-text","title":"Left margin of text","text":"
var leftMargin = txt.measureTextMargins(testString).left;\n
  • testString : Measure left margin of this text.
"},{"location":"tagtext/#shift-start-position-of-text","title":"Shift start position of text","text":"
txt.setXOffset(value);\n
"},{"location":"tagtext/#resolution","title":"Resolution","text":"
  • Get
    var resolution = txt.style.resolution;\n
  • Set
    txt.setResolution(resolution);\n
"},{"location":"tagtext/#inline-style","title":"Inline style","text":"

Define style inline text.

  • <style='color:red'>Some text</style>
  • <style='size:30px'>Some text</style>
  • <style='y:-12;size:20px'>Some text</style>
  • <style='stroke:blue 1px'>Some text</style> (color thickness)
  • <style='shadow:blue 2px 2px 2px'>Some text</style> (color offsetX offsetY blur)
  • <style='underline:blue 3px -1px'>Some text</style> (color thickness offset)
  • <style='strikethrough:blue 3px -1px'>Some text</style> (color thickness offset)

Or mix them

  • <style='color:red;size:30px'>Some text</style>
"},{"location":"tagtext/#test-string","title":"Test string","text":"

Set the test string to use when measuring the font.

txt.setTestString(text);\n
"},{"location":"tagtext/#save-texture","title":"Save texture","text":"
txt.generateTexture(key);\n// txt.generateTexture(key, x, y, width, height);\n
"},{"location":"tagtext/#rtl","title":"RTL","text":"
  • Set rtl in style config when creating this text game object
  • Change rtl during runtime
    txt.setRTL(rtl).setText(newContent);\n
    • Invoke setRTL method before setting new content.
"},{"location":"tagtext/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"tagtext/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"tagtext/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"tcrp-player/","title":"Player","text":""},{"location":"tcrp-player/#introduction","title":"Introduction","text":"

Player of T ime-C ommand-R ecorder-P layer, to run commands on time.

  • Author: Rex
  • Member of scene
"},{"location":"tcrp-player/#live-demos","title":"Live demos","text":"
  • Replay drawing
"},{"location":"tcrp-player/#usage","title":"Usage","text":"

Sample code

"},{"location":"tcrp-player/#install-plugin","title":"Install plugin","text":""},{"location":"tcrp-player/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextcrpplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextcrpplugin.min.js', true);\n
  • Create instance
    var player = scene.plugins.get('rextcrpplugin').addPlayer(scene, config);\n
"},{"location":"tcrp-player/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TCRPPlugin from 'phaser3-rex-plugins/plugins/tcrp-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTCRP',\nplugin: TCRPPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var player = scene.plugins.get('rexTCRP').addPlayer(scene, config);\n
"},{"location":"tcrp-player/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TCRP from 'phaser3-rex-plugins/plugins/tcrp.js';\n
  • Create instance
    var player = new TCRP.Player(scene, config);\n
"},{"location":"tcrp-player/#create-instance","title":"Create instance","text":"
var player = scene.plugins.get('rexTCRP').addPlayer(scene, {\n// timeUnit: 0,        // 'ms'|0|'s'|'sec'|1\n// dtMode: 0,          // 'abs'|'absolute'|0|'inc'|'increment'|1\n// commands: [],       // [[time, command], [time, command], ...]\n// timeScale: 1,\n// scope: undefined\n});\n
  • scene : A scene object, or a game object.
  • timeUnit : see next section
  • dtMode : see next section
  • commands : see next section
  • timeScale
"},{"location":"tcrp-player/#load-commands","title":"Load commands","text":"
player.load(commands, scope, {\n// timeUnit: 0,        // 'ms'|0|'s'|'sec'|1\n// dtMode: 0           // 'abs'|'absolute'|0|'inc'|'increment'|1\n});\n
  • Commands : see also Run commands
    [\n[time, command],\n[time, command],\n...\n]\n
    • Format of each row :
      [time, fnName, param0, param1, ...]\n// [time, callback, param0, param1, ...]\n
      [time, [fnName, param0, param1, ...]]\n// [time, [callback, param0, param1, ...]]\n
      [time, [command0, command1, ...]]\n
  • timeUnit: time-unit of time
    • 'ms', or 0 : time in millisecond
    • 's', 'sec', or 1 : time in second
  • dtMode: mode of counting time
    • 'abs', 'absolute', or 0 : timeout = time
    • 'inc', 'increment', 1 : timeout = time + previous-time
"},{"location":"tcrp-player/#clear-all-commands","title":"Clear all commands","text":"
player.clear();\n
"},{"location":"tcrp-player/#append-command","title":"Append command","text":"
player.append(time, fn, param0, param1, ...);\n
  • time : Delay time
  • fn :
    • A function (callback) object.
    • A string , to get function (callback) object from scope.
  • param0, param1 ... : Parameters of callback.
"},{"location":"tcrp-player/#start-playing","title":"Start playing","text":"
player.start();\n// player.start(startAt);  // Start-at time in ms\n
"},{"location":"tcrp-player/#events","title":"Events","text":"
  • Start
    player.on('start', function(scene, player){});\n
  • Pause
    player.on('pause', function(scene, player){});\n
  • Resume
    player.on('resume', function(scene, player){});\n
  • Stop
    player.on('stop', function(scene, player){});\n
  • Complete
    player.on('complete', function(scene, player){});\n
  • Run command
    player.on('runcommand', function(commands, scope){});\n
"},{"location":"tcrp-player/#pause-resume-stop-playing","title":"Pause, Resume, stop playing","text":"
player.pause();\nplayer.resume();\nplayer.stop();\n
"},{"location":"tcrp-player/#seek-elapsed-time","title":"Seek elapsed time","text":"
player.seek(time);   // Elapsed time in ms\n
"},{"location":"tcrp-player/#seek-to-next-command","title":"Seek to next command","text":"
player.seekToNext();\n

Seek to time of next command. i.e. run next command immediately.

"},{"location":"tcrp-player/#state-of-player","title":"State of player","text":"
var isPlaying = player.isPlaying;\nvar completed = player.completed;\nvar now = player.now;\n
"},{"location":"tcrp-player/#time-scale","title":"Time-scale","text":"
  • Set
    player.setTimeScale(value);\n// player.timeScale = value;\n
  • Get
    var timeScale = player.timeScale;\n
"},{"location":"tcrp-recoder/","title":"Recoder","text":""},{"location":"tcrp-recoder/#introduction","title":"Introduction","text":"

Recorder of T ime-C ommand-R ecorder-P layer, to store commands with time.

  • Author: Rex
  • Member of scene
"},{"location":"tcrp-recoder/#live-demos","title":"Live demos","text":"
  • Replay drawing
"},{"location":"tcrp-recoder/#usage","title":"Usage","text":"

Sample code

"},{"location":"tcrp-recoder/#install-plugin","title":"Install plugin","text":""},{"location":"tcrp-recoder/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextcrpplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextcrpplugin.min.js', true);\n
  • Create instance
    var recorder = scene.plugins.get('rextcrpplugin').addRecorder(scene);\n
"},{"location":"tcrp-recoder/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TCRPPlugin from 'phaser3-rex-plugins/plugins/tcrp-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTCRP',\nplugin: TCRPPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var recorder = scene.plugins.get('rexTCRP').addRecorder(scene);\n
"},{"location":"tcrp-recoder/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TCRP from 'phaser3-rex-plugins/plugins/tcrp.js';\n
  • Create instance
    var recorder = new TCRP.Recorder(scene);\n
"},{"location":"tcrp-recoder/#create-instance","title":"Create instance","text":"
var recorder = scene.plugins.get('rexTCRP').addRecorder(scene);\n
  • Destroy when scene stopped

or

var recorder = scene.plugins.get('rexTCRP').addRecorder(gameObject);\n
  • Destroy when game object destroyed
"},{"location":"tcrp-recoder/#start-recording","title":"Start recording","text":"
recorder.start();\n// recorder.start(startAt);  // start-at time in ms\n
"},{"location":"tcrp-recoder/#push-commands","title":"Push commands","text":"
recorder.addCommand([fnName, param0, param1, ...]);\n// recorder.addCommand([command0, command1, ...]);\n// recorder.addCommand([fnName, param0, param1, ...], offset);  // time-offset in ms\n

See also Run commands

"},{"location":"tcrp-recoder/#get-commands","title":"Get commands","text":"
var commands = recorder.getCommands();        // Get a shallow copy of commands\n// var commands = recorder.getCommands(true); // Get reference of commands\n

Format of return commands:

[\n[time, [command]],\n[time, [command0,command1]],\n...\n]\n
"},{"location":"tcrp-recoder/#clear-commands","title":"Clear commands","text":"
recorder.clear();\n
"},{"location":"tcrp-recoder/#pause-resume-stop-recording","title":"Pause, Resume, stop recording","text":"
recorder.pause();\nrecorder.resume();\nrecorder.stop();\n
"},{"location":"tcrp-recoder/#seek-elapsed-time","title":"Seek elapsed time","text":"
recorder.seek(time);   // elapsed time in ms\n
"},{"location":"tcrp-recoder/#state-of-recorder","title":"State of recorder","text":"
var isRecording = recorder.isRecording;\nvar now = recorder.now;\n
"},{"location":"tcrp-recoder/#time-scale","title":"Time-scale","text":"
  • Set
    recorder.setTimeScale(value);\n// recorder.timeScale = value;\n
  • Get
    var timeScale = recorder.timeScale;\n
"},{"location":"tcrp-recoder/#events","title":"Events","text":"
  • Start
    recorder.on('start', function(scene, recorder){});\n
  • Pause
    recorder.on('pause', function(scene, recorder){});\n
  • Resume
    recorder.on('resume', function(scene, recorder){});\n
  • Stop
    recorder.on('stop', function(scene, recorder){});\n
"},{"location":"text/","title":"Text","text":""},{"location":"text/#introduction","title":"Introduction","text":"

Drawing text on canvas, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"text/#usage","title":"Usage","text":""},{"location":"text/#add-text-object","title":"Add text object","text":"
var txt = scene.add.text(x, y, 'hello');\n// var txt = scene.add.text(x, y, 'hello', { fontFamily: 'Arial', fontSize: 64, color: '#00ff00' });\n

Default style

{\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},\nalign: 'left',  // 'left'|'center'|'right'|'justify'\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\nmaxLines: 0,\nlineSpacing: 0,\nfixedWidth: 0,\nfixedHeight: 0,\nrtl: false,\ntestString: '|M\u00c9qgy',\nwordWrap: {\nwidth: null,\ncallback: null,\ncallbackScope: null,\nuseAdvancedWrap: false\n},\nmetrics: false,\n// metrics: {\n//     ascent: 0,\n//     descent: 0,\n//     fontSize: 0\n// },\n}\n

Add text from JSON

var txt = scene.make.text({\nx: 100,\ny: 100,\npadding: {\nleft: 64,\nright: 16,\ntop: 20,\nbottom: 40\n//x: 32,    // 32px padding on the left/right\n//y: 16     // 16px padding on the top/bottom\n},\ntext: 'Text\\nGame Object\\nCreated from config',\nstyle: {\nfontSize: '64px',\nfontFamily: 'Arial',\ncolor: '#ffffff',\nalign: 'center',  // 'left'|'center'|'right'|'justify'\nbackgroundColor: '#ff00ff'\n},\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
"},{"location":"text/#custom-class","title":"Custom class","text":"
  • Define class
    class MyText extends Phaser.GameObjects.Text {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyText(scene, x, y, 'hello');\n
"},{"location":"text/#word-wrap","title":"Word wrap","text":"
  • Wrap by width
    var txt = scene.make.text({\nx: 400,\ny: 100,\ntext: 'The sky above the port was the color of television, tuned to a dead channel.',\norigin: { x: 0.5, y: 0.5 },\nstyle: {\nfont: 'bold 25px Arial',\nfill: 'white',\nwordWrap: { width: 300 }\n},\n// origin: {x: 0.5, y: 0.5},\n});\n
  • Wrap by callback
    var txt = scene.make.text({\nx: 400,\ny: 300,\ntext: 'The sky above the port was the color of television, tuned to a dead channel.',\norigin: 0.5,\nstyle: {\nfont: 'bold 30px Arial',\nfill: 'white',\nwordWrap: { callback: wordWrap, scope: this }\n},\n// origin: {x: 0.5, y: 0.5},\n});\n\nfunction wordWrap (text, textObject)\n{\n// First parameter will be the string that needs to be wrapped\n// Second parameter will be the Text game object that is being wrapped currently\n\n// This wrap just puts each word on a separate line, but you could inject your own\n// language-specific logic here.\nvar words = text.split(' ');\n\n// You can return either an array of individual lines or a string with line breaks (e.g. \\n) in\n// the correct place.\nreturn words;\n}\n
  • Wrap width
    • Get
      var width = txt.style.wordWrapWidth;\nvar useAdvancedWrap = txt.style.wordWrapUseAdvanced;\n
    • Set
      txt.setWordWrapWidth(width);\n// txt.setWordWrapWidth(width, useAdvancedWrap);\n
  • Wrap callback
    • Get
      var callback = txt.style.wordWrapCallback;\nvar scope = txt.style.wordWrapCallbackScope;\n
    • Set
      txt.setWordWrapCallback(callback, scope);\n
"},{"location":"text/#content","title":"Content","text":"
  • Get
    var content = txt.text;\n
  • Set
    txt.setText(text);\n// txt.text = text;\n
  • Append
    txt.appendText(text);\n// txt.text += '\\n' + text;\n
    or
    txt.appendText(text, false);\n// txt.text += text;\n
"},{"location":"text/#set-style","title":"Set style","text":"
txt.setStyle(style);\ntxt.setFont(font);\ntxt.setFontFamily(family);\ntxt.setFontSize(size);\ntxt.setFontStyle(style);\n
"},{"location":"text/#set-align","title":"Set align","text":"
txt.setAlign(align);\n
  • align : 'left', 'center', 'right', 'justify'
"},{"location":"text/#color","title":"Color","text":"
  • Text color
    • Get
      var color = txt.style.color;\n
    • Set
      txt.setColor(color);\n
      or
      txt.setFill(color);\n
  • Stroke color, thickness
    • Get
      var color = txt.style.stroke;\nvar thickness = txt.style.strokeThickness;\n
    • Set
      txt.setStroke(color, thickness);\n
    • Clear
      txt.setStroke();\n
  • Background color
    • Get
      var color = txt.style.backgroundColor;\n
    • Set
      txt.setBackgroundColor(color);\n
  • Shadow
    • Get
      var color = txt.style.shadowColor;\nvar offsetX = txt.style.shadowOffsetX;\nvar offsetY = txt.style.shadowOffsetY;\nvar blur = txt.style.shadowBlur;\nvar stroke = txt.style.shadowStroke;\nvar enabled = txt.style.shadowFill;\n
    • Set
      txt.setShadow(x, y, color, blur, shadowStroke, shadowFill);\ntxt.setShadowOffset(x, y);\ntxt.setShadowColor(color);\ntxt.setShadowBlur(blur);\ntxt.setShadowStroke(enabled);\ntxt.setShadowFill(enabled);\n
"},{"location":"text/#line-spacing","title":"Line spacing","text":"

This value is added to the height of the font when calculating the overall line height.

  • Get
    var lineSpacing = txt.lineSpacing;\n
  • Set
    txt.setLineSpacing(value);\n
"},{"location":"text/#letter-spacing","title":"Letter spacing","text":"
  • Get
    var letterSpacing = txt.letterSpacing;\n
  • Set
    txt.setLetterSpacing(value);\n
  • value : Positive or negative value.

Note

Enabling this feature will cause Phaser to render each character in this Text object one by one, rather than use a draw for the whole string. This makes it extremely expensive when used with either long strings, or lots of strings in total.

"},{"location":"text/#padding","title":"Padding","text":"
  • Get
    var left = txt.padding.left;\nvar top = txt.padding.top;\nvar right = txt.padding.right;\nvar bottom = txt.padding.bottom;\n
  • Set
    txt.setPadding(left, top, right, bottom);\n// txt.setPadding(padding); // padding: {left, top, right, bottom}\n
"},{"location":"text/#max-lines","title":"Max lines","text":"
  • Get
    var maxLines = txt.style.maxLines;\n
  • Set
    txt.setMaxLines(max);\n
"},{"location":"text/#fixed-size","title":"Fixed size","text":"
  • Get
    var width = txt.style.fixedWidth;\nvar height = txt.style.fixedHeight;\n
  • Set
    txt.setFixedSize(width, height);\n
"},{"location":"text/#test-string","title":"Test string","text":"

Set the test string to use when measuring the font.

txt.style.setTestString(text);\n
"},{"location":"text/#rtl","title":"RTL","text":"
  • Set rtl in style config when creating this text game object
  • Change rtl during runtime
    txt.setRTL(rtl).setText(newContent);\n
    • Invoke setRTL method before setting new content.
"},{"location":"text/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"text/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"text/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"textedit/","title":"Edit","text":""},{"location":"textedit/#introduction","title":"Introduction","text":"

Create an input text object above a text object to edit string content.

  • Author: Rex
  • Behavior of text object
"},{"location":"textedit/#live-demos","title":"Live demos","text":"
  • Text edit
  • Text area
  • Number edit
  • With rexui-Label
  • Text game object inside container
"},{"location":"textedit/#usage","title":"Usage","text":"

Sample code

"},{"location":"textedit/#install-plugin","title":"Install plugin","text":""},{"location":"textedit/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextexteditplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextexteditplugin.min.js', true);\n
  • Open editor
    • Add text-edit behavior, will open editor under 'pointerdown' event.
      var editor = scene.plugins.get('rextexteditplugin').add(textGameObject, config);\n
    • Open editor directly
      var editor = scene.plugins.get('rextexteditplugin').edit(textGameObject, config);\n
"},{"location":"textedit/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TextEditPlugin from 'phaser3-rex-plugins/plugins/textedit-plugin.js';\nvar config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTextEdit',\nplugin: TextEditPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Open editor
    • Add text-edit behavior, will open editor under 'pointerdown' event.
      var editor = scene.plugins.get('rexTextEdit').add(textGameObject, config);\n
    • Open editor directly
      var editor = scene.plugins.get('rexTextEdit').edit(textGameObject, config);\n
"},{"location":"textedit/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import { TextEdit, Edit } from 'phaser3-rex-plugins/plugins/textedit.js';\n
  • Open editor
    • Add text-edit behavior, will open editor under 'pointerdown' event.
      var editor = new TextEdit(textGameObject, config);\n
    • Open editor directly
      var editor = Edit(textGameObject, config);\n
"},{"location":"textedit/#open-text-editor","title":"Open text editor","text":"

Open editor directly.

var editor = scene.plugins.get('rexTextEdit').edit(textObject, {\n// inputType: 'text',   // 'text'|'password'|'textarea'|...\n// type: 'text',    // 'text'|'password'|'textarea'|...\n\n// enterClose: true,\n// selectAll: false,\n\n// onOpen: undefined,\n// onTextChanged: undefined,\n// onClose: undefined,\n\n// text: '',\n});\n// var editor = scene.plugins.get('rexTextEdit').edit(textObject, config, onClose);\n
  • textObject : Text object, bbcode text object, or tag text object.
  • config :
    • config.inputType, or config.type :
      • 'text' (default), or
      • 'password'
      • 'number'
    • config.onOpen : Callback invoked when input text is created.
      function (textObject) {\n}\n
    • config.onTextChanged : Callback invoked when input text changed.
      function (textObject, text) {\ntextObject.text = text;\n}\n
    • config.onClose : Callback invoked when input text is closed. This parameter is valid only when onClose parameter is not given.
      function (textObject) {\n}\n
    • enterClose :
      • true : Close input text when enter-key was pressed. Default value is true if inputType is not 'textarea'.
      • false : If inputType is set to 'textarea', default value will be false.
    • config.selectAll : Set true to select all text.
    • config.text : Initial string content. Default is the string content of textObject.
    • More configuration parameters...
  • onClose : Callback invoked when input text is closed.
    var callback = function(textObject) {\n}\n

Create a text editor (input element) above text object.

  • Size, font size, font family, font color, background color, background corner radius, padding-left, padding-right of text editor will be assigned from text object.
  • Text object will be invisible when text editor is opened.
  • Store reference of text editor at textObject._editor.
  • Text editor will be closed when
    • Press enter key and enterClose is set, or
    • Touch outside of editor, or
    • Open another text editor, or
    • Call editor.close()

Limitation of text game object

Don't assign height property of text game object. Because that text input element does not have vertical align setting, text will always align to middle/center.

"},{"location":"textedit/#create-instance","title":"Create instance","text":"

Add text-edit behavior, will open editor under 'pointerdown' event.

var editor = scene.plugins.get('rexTextEdit').add(textGameObject, {\n// type: 'text',   //'text','password','number'\n// enterClose: true,\n// selectAll: false,\n\n// onOpen: undefined,\n// onTextChanged: undefined,\n// onClose: undefined,\n\n// text: '',\n});\n
"},{"location":"textedit/#open-editor","title":"Open editor","text":"
editor.open(config);\n// editor.open(config, onClose);\n
  • config
    • config.type :
      • text (default), or
      • password
    • config.text : Initial string content.
    • config.onTextChanged : Callback invoked when input text changed.
      function (textObject, text) {\ntextObject.text = text;\n}\n
    • More configuration parameters...
  • onClose : Callback invoked when text editor is closed.
    var callback = function(textObject) {\n}\n

Create a text editor (input element) above text object.

  • Size, font size, font family, font color, background color of text editor will be equal to text object.
  • Text object will be invisible when text editor is opened.
"},{"location":"textedit/#is-opened","title":"Is opened","text":"
var isOpened = editor.isOpened;\n
"},{"location":"textedit/#close-editor","title":"Close editor","text":"
editor.close();\n

Text editor will be closed when

  • Press enter key, or
  • Touch outside of editor, or
  • Open another text editor, or
  • Call editor.close()
"},{"location":"textedit/#get-dom","title":"Get DOM","text":"
var inputText = editor.inputText.node;\n
"},{"location":"textedit/#bypass-key-input","title":"Bypass key input","text":"

See InputText/Bypass key input

"},{"location":"textedit/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"

See dom-element's Interactive with other game objects

"},{"location":"textpage/","title":"Page","text":""},{"location":"textpage/#introduction","title":"Introduction","text":"

Display text page by page on text object, bbcode text object, or tag text object.

  • Author: Rex
  • Behavior of text object
"},{"location":"textpage/#live-demos","title":"Live demos","text":"
  • BBCode text + page + typing
"},{"location":"textpage/#usage","title":"Usage","text":"

Sample code

"},{"location":"textpage/#install-plugin","title":"Install plugin","text":""},{"location":"textpage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextextpageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextextpageplugin.min.js', true);\n
  • Add page behavior
    var page = scene.plugins.get('rextextpageplugin').add(textGameObject, config);\n
"},{"location":"textpage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TextPagePlugin from 'phaser3-rex-plugins/plugins/textpage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTextPage',\nplugin: TextPagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add page behavior
    var page = scene.plugins.get('rexTextPage').add(textGameObject, config);\n
"},{"location":"textpage/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TextPage from 'phaser3-rex-plugins/plugins/textpage.js';\n
  • Add page behavior
    var page = new TextPage(textGameObject, config);\n
"},{"location":"textpage/#create-instance","title":"Create instance","text":"
var page = scene.plugins.get('rexTextPage').add(textGameObject, {\n// text: '',              // content in string or array\n// maxLines: undefined,\n// pageBreak: '\\f\\n',\n});\n
  • textObject : Text object, bbcode text object, tag text object, or bitmap text object
  • text : content in string or array, optional
  • maxLines : Max lines of a page.
    • undefined : Default value. For Text object, bbcode text object, tag text object
      • Use style property maxLines.
      • Count number of lines if it has fixedHeight setting.
    • A number : Max lines of a page, for bitmap text object
  • pageBreak : Symbol of page-break. Default value is '\\f\\n'. String after this page-break symbol will be placed to a new page.
"},{"location":"textpage/#set-content","title":"Set content","text":"
  • Set content
    page.setText(content);\n
    • content : String, number, or string array. Can insert pageBreak symbol.
  • Append content
    page.appendText(content);\n
    • content : String, number, or string array. Can insert pageBreak symbol.
  • Clear content
    page.clearText()\n
  • Append page
    page.appendPage(content);   // content in string or array\n
    • content : String, number, or string array. Don't insert pageBreak symbol.
"},{"location":"textpage/#show-page","title":"Show page","text":"
  • Display current page
    page.showPage();\n
  • Display next page
    page.showNextPage();\n
  • Display previous page
    page.showPreviousPage();\n
  • Display first page
    page.showFirstPage();\n
  • Display last page
    page.showLastPage();\n
  • Display page by index
    page.showPage(index);\n
  • Display page by line index
    page.showPageNyLineIndex(index);\n

Note

Initial page index is -1, so user could call page.showNextPage() to display first page.

"},{"location":"textpage/#get-lines-of-page","title":"Get lines of page","text":""},{"location":"textpage/#page-by-page","title":"Page by page","text":"
  • Get lines of current page
    var lines = page.getPage();\n
  • Get lines of next page
    var lines = page.getNextPage();\n
  • Get lines of previous page
    var lines = page.getPreviousPage();\n
  • Get lines of first page
    var lines = page.getFirstPage();\n
  • Get lines of last page
    var lines = page.getLastPage();\n
  • Get lines of page by page index
    var lines = page.getPage(index);\n
"},{"location":"textpage/#page-of-line","title":"Page of line","text":"
  • Get line of page by line index
    var lines = page.getPageByLineIndex(index);\n
  • Get page of next line
    var lines = page.getPageOfNextLine(index);\n
  • Get page of previous line
    var lines = page.getPageOfPreviousLine(index);\n
"},{"location":"textpage/#other-properties","title":"Other properties","text":""},{"location":"textpage/#page-by-page_1","title":"Page by page","text":"
  • Is last page
    var isLastPage = page.isLastPage;\n
  • Is first page
    var isFirstPage = page.isFirstPage;\n
  • Current page index
    var pageIndex = page.pageIndex;\n
  • Number of pages
    var pageIndex = page.pageCount;\n
"},{"location":"textpage/#page-of-line_1","title":"Page of line","text":"
  • Is last line
    var isLastLine = page.isLastLine;\n
  • Is first line
    var isFirstLine = page.isFirstLine;\n
  • Start line index
    var startLineIndex = page.startLineIndex;\n
  • End line index
    var endLineIndex = page.endLineIndex;\n
  • Number of lines
    var totalLinesCount = page.totalLinesCount;\n
"},{"location":"textplayer/","title":"Text player","text":""},{"location":"textplayer/#introduction","title":"Introduction","text":"

Typing characters on dynamic text, waiting click or key enter, play sound effect or backgroun music.

  • Author: Rex
  • Game object
"},{"location":"textplayer/#live-demos","title":"Live demos","text":"
  • BBCode
  • Play
  • Sprite control
  • Show page
  • Fast typing
  • Custom game object
  • Fade out page
  • Choices
    • Custonm tag
    • Choice dailog
  • Resolution
"},{"location":"textplayer/#usage","title":"Usage","text":"

Sample code

"},{"location":"textplayer/#install-plugin","title":"Install plugin","text":""},{"location":"textplayer/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextextplayerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextextplayerplugin.min.js', true);\n
  • Add text-player object
    var txt = scene.add.rexTextPlayer(config);\n
"},{"location":"textplayer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TextPlayerPlugin from 'phaser3-rex-plugins/plugins/textplayer-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTextPlayerPlugin',\nplugin: TextPlayerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text-player object
    var txt = scene.add.rexTextPlayer(config);\n
"},{"location":"textplayer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TextPlayer from 'phaser3-rex-plugins/plugins/textplayer.js';\n
  • Add text-player object
    var txt = new TextPlayer(scene, config);\nscene.add.existing(txt);\n
"},{"location":"textplayer/#create-instance","title":"Create instance","text":"
var txt = scene.add.rexTextPlayer({\nx: 0, y: 0,\nwidth: undefined, height: undefined,\nresolution: 1,\n\npadding: 0,  // {left: 0, right: 0, top: 0, bottom: 0}\n\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\n\ninnerBounds: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\noffsetX: 0,\noffsetY: 0,\nleftSpace: 0,\nrightSpace: 0,\n},\n\nparser: {\ndelimiters: '[]',\ncomment: '//',\n// translateTagNameCallback: undefined,\n}\n\nwrap: {\ncallback: undefined, // Default wrapping callback is dynamicText.runWordWrap()\nlineHeight:\n// maxLines: \npadding: { top: 0, left: 0, right: 0, bottom: 0 },\nletterSpacing: 0,\nwrapMode: 'word',  // 1|'word'|2|'char'|'character'|3|'mix'\nhAlign: 0, // 0|'left'|1|'center'|2|'right'|3|'justify'|'justify-left'|4|'justify-center'|5| justify-right'\nvAlign: 0, // 0|'top'|1|'center'|2|'bottom'\n\n},\n\ntyping: {\nspeed: 250,\nonTypingStart: function (children) {\nfor (var i = 0, cnt = children.length; i < cnt; i++) {\nchildren[i].setVisible(false);\n}\n},  // Default: set all children invisible\nanimation: undefined,  // Default: no typing animation, only invoke onStart callback\nanimation: {\nduration: 1000,\nyoyo: false,\nonStart: function(child) {\nchild.setVisible();\n},\nonProgress: function(child, t) {\n\n},\nonComplete: function(child) {\n\n}\n},\n\n// skipSpace: false,\n\n// minSizeEnable: false,\n\nfadeOutPage: undefined,  // Default: no fade-out-page animation\nfadeOutPage: function(children) {\nreturn eventEmitter;\nreturn promise;\n},\n\n},\n\nimages: {\n// key: {width, height}\n// key: {key, frame, width, height}\n},\n\nsprites: {\n// createCallback: 'sprite',\n// createCallback: function(scene, ...) { return gameObject; },\n\n// fade: 500,\n// fade: {mode: 'tint', time: 500},\n\n// viewportCoordinate: false,\n// viewportCoordinate: { viewport: new Phaser.Geom.Rectangle() },\n\n}, layers: undefined, // []\n\nsounds: {\nbgm: {\ninitial: undefinied,\nloop: true,\nfade: 500\n},\nbgm2: {\ninitial: undefinied,\nloop: true,\nfade: 500\n}\n},\n\nclickTarget: this,  // This text player    \nnextPageInput: null,\n// ignoreNextPageInput: false,\n\ntext: undefined\n});\n
  • x, y : Position of this text-player game object.
  • width : Fixed width.
    • A number : Width of this text-player game object.
      • Wrap-width is width - padding.left - padding.right.
    • undefined : Width of this text-player game object will be set after invoked runWordWrap method.
  • height : Fixed height.
    • A number : Height of this text-player game object.
    • undefined : Height of this text-player game object will be set after invoked runWordWrap method.
  • resolution : The resolution the content is rendered to its internal canvas at. Default value is 1.
  • padding : Padding of bounds.
    • A number
    • padding.left, padding.right, padding.top, padding.bottom
  • background : Properties of background round-rectangle.
    • background.color : Fill color.
      • null : No filling.
    • background.color2 : Gradient fill color.
      • null : No gradient filling.
    • background.horizontalGradient : Horizontal or vertical gradient filling.
      • true : Horizontal gradient filling.
      • false : Vertical gradient filling.
    • background.stroke : Stroke color.
      • null : No stroke.
    • background.strokeThickness : Line width of stroke.
    • background.cornerRadius : Corner-radius of round rectangle.
      • 0 : No round corner
      • > 0 : Convex round corner
      • < 0 : Concave round corner
    • background.cornerIteration : Iteration of corner-radius.
      • null : Draw corner-radius via arc directly.
      • A number : Draw corner-radius via lines
  • innerBounds : Properties of inner-bounds.
    • innerBounds.color : Fill color.
      • null : No filling.
    • innerBounds.color2 : Gradient fill color.
      • null : No gradient filling.
    • innerBounds.horizontalGradient : Horizontal or vertical gradient filling.
      • true : Horizontal gradient filling.
      • false : Vertical gradient filling.
    • innerBounds.stroke : Stroke color.
      • null : No stroke.
    • innerBounds.strokeThickness : Line width of stroke.
  • style : Initial text-style.
    • style.bold : Bold
    • style.italic : Italic
    • style.fontSize : Font size
    • style.fontFamily : Font family
    • style.color : Fill color
    • style.stroke : Stroke color
    • style.strokeThickness : Line width of stroke.
    • style.shadowColor : Shadow color.
      • null : No shadow.
    • style.shadowOffsetX : OffsetX of shadow.
    • style.shadowOffsetY : OffsetY of shadow.
    • style.shadowBlur : Blur of shadow.
    • style.offsetX : OffsetX.
    • style.offsetY : OffsetY.
    • style.leftSpace : Extra space between this character and previous character.
    • style.rightSpace : Extra space between this character and next character.
    • style.align : Override default line-alignment setting.
      • 0, 'left', 'top' : Align remainder lines to left/top.
      • 1, 'center' : Align remainder lines to center.
      • 2, 'right', 'bottom' : Align remainder lines to right/bottom.
      • undefined : Use default line-alignment setting.
  • wrap : Default configuration Horizontal/Vertical wrapping.
  • typing :
    • typing.speed : Default typing speed of each character.
    • typing.onTypingStart : Callback when typing start. Default is to set all children to invisible.
      function (children) {\nfor (var i = 0, cnt = children.length; i < cnt; i++) {\nchildren[i].setVisible(false);\n}\n
      • children : Array of child.
    • typing.animation : Configuration of typing animation
      • undefined : No typing animation, default behavior
    • typing.animation.duration : Duration of typing animation.
    • typing.animation.yoyo :
      • false : Mapping progress t to 0 - 1. Default behavior.
      • true : Mapping progress t to 0 - 1 - 0.
    • typing.animation.onStart : Callback when typing start of a character. Default is to set this child to visible.
      function(child) { child.setVisible(); }\n
      • child
    • typing.animation.onProgress : Callback when progress typing animation.
      function(child, t) {\n}\n
      • child
    • typing.animation.onComplete : Callback when typing animation complete.
      function(child) {\n}\n
      • child
    • typing.skipSpace :
      • false : Will have delay when typing space character. Default behavior.
      • true : Typing space character immediately.
    • typing.minSizeEnable :
      • true : Resize to minimun size for showing all visible characters.
      • false : Won't resize during typing. Default behavior.
    • typing.fadeOutPage : Callback to fade-out characters of previous page.
      • undefined : Default value, no fade-out-page animation.
      • Callback
        function(characters) {\nreturn tween;  // eventEmitter\nreturn promise;\n}\n
        • characters : Fade out targets.
        • Return value could be tween object (event emitter), or promise object.
          • Tween object : Wait until 'complete' event triggering.
          • Promise object : Wait until promoise resolving.
  • parser : Configuration of parser.
    • parser.delimiters : Delimiters of tag. Default value is '[]'.
    • parser.comment : Start word of a comment line. Default value is '//'.
      • null, or false : No comment line.
    • parser.translateTagNameCallback : Callback to translate tag-name
      • undefined : Use original tag-name. Default behavior.
      • A function, return new tag name.
        function(tagName) {\nreturn newTagName;\n}\n
  • images : Configuration of images.
  • sprites : Configuration of sprites.
    • sprites.createCallback :
      • 'sprite' : Create sprite game object. Default behavior.
      • 'image' : Create image game object.
      • Callback to return a game object
        function(scene, textureKey, frameName) {\n// return scene.add.sprite(0, 0, textureKey, frameName);\n}\n
    • sprites.fade :
      • 0 : No fade-in or fade-out when adding or removing a sprite.
      • A number : Duration of fading. Default value is 500.
      • A plain object contains mode, time
        • sprite.fade.mode : Fade mode
          • 'tint', or 0 : Fade-in or fade-out via tint property.
          • 'alpha', or 1 : Fade-in or fade-out via alpha property.
          • 'revealUp', or 2 : Reveal up for fade-in.
          • 'revealDown', or 3 : Reveal down for fade-in.
          • 'revealLeft', or 4 : Reveal left for fade-in.
          • 'revealRight', or 5 : Reveal right for fade-in.
        • sprite.fade.time : Duration of fading. Default value is 500.
    • sprites.viewportCoordinate : Apply viewportCoordinate behavior to sprite game object.
      • true : Attach vpx, vpy, vp to sprite game object.
        • vpx, vpy : Number between 0~1. Proportion of viewport.
        • vp : Viewport in rectangle
      • false : Do nothing, default behavior.
    • sprites.symbols : Convert string value to number value when Set or Ease property of game object.
      • A plain object contains string key and number value.
  • layers :
    • undefined : Don't create layerManger.
    • Array of string : Pre-create layer game objects in layerManger.
  • sounds : Configuration of sound effect, or background music.
    • sounds.bgm.initial, sounds.bgm2.initial : Initial music instance created by scene.sound.add(key) before starting playing content.
      • undefined : No initial music instance, default value.
    • sounds.bgm.loop, sounds.bgm2.loop :
      • true : Loop background music, default behavior.
      • false : Play background music once.
    • sounds.bgm.fade, sounds.bgm2.fade :
      • 0 : No fade-in or fade-out when starting or stopping a background music.
      • A number : Fade-in or fade-out (cross-fade) when starting or stopping a background music. Default value is 500.
  • nextPageInput : Wait condition to type next page
    • null, or false : Stop tying next page. Default behavior
      • Typing next manually via txt.typingNextPage().
    • 'click' : Wait click.
    • 'click|2000' : Wait one of condition: click, or 2000ms.
    • 'click|enter|2000' : Wait one of condition: click, enter key down, or 2000ms.
    • A function callback :
      function(callback) {\n// Invoke `callback()` to continue typing\n}\n
  • clickTarget : Click target, default is text player itself.
    • scene : Any pointer down on this scene.
  • ignoreNextPageInput : Set true to continue typing next page without any waiting.
  • text : Content of text to play.

or

var txt = scene.add.rexTextPlayer(x, y, width, height, config);\n

or

var txt = scene.add.rexTextPlayer(x, y, config);\n

Add textplayer from JSON

var txt = scene.make.rexTextPlayer({\nx: 0,\ny: 0,\n\n// origin: {x: 0.5, y: 0.5},\n// fill: null,\n\nadd: true\n});\n
"},{"location":"textplayer/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTextPlayer extends TextPlayer {\nconstructor(scene, x, y, config) {\nsuper(scene, x, y, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var txt = new MyTextPlayer(scene, x, y, config);\n
"},{"location":"textplayer/#game-object-manager","title":"Game object manager","text":"
txt.addGameObjectManager({\nname: goType,\ncreateGameObject: function(scene, ...) {\nreturn gameObject\n},\n\nfade: 500,\n// fade: {mode: 'tint', time: 500},\n\n// viewportCoordinate: false,\n// viewportCoordinate: { viewport: new Phaser.Geom.Rectangle() },\n\n// defaultLayer: layerName,\n\n// symbols: undefined,  // { key:value },\n})\n
  • name : Name of this game object manager, a string.
  • createGameObject : Callback to return a game object
    function(scene, a, b, c) {\n// return gameObject;\n}\n
    • a, b, c : Parameters pass from [goType.name=a,b,c]
  • fade : Tint-fade (if game object has tint property) or alpha-fade game object when creating or destroying a game object.
    • 0 : No fade-in or fade-out when adding or removing a game object.
    • A number : Duration of fading. Default value is 500.
    • A plain object contains mode, time
      • fade.mode : Fade mode
        • 'tint', or 0 : Fade-in or fade-out via tint property.
        • 'alpha', or 1 : Fade-in or fade-out via alpha property.
        • 'revealUp', or 2 : Reveal up for fade-in.
        • 'revealDown', or 3 : Reveal down for fade-in.
        • 'revealLeft', or 4 : Reveal left for fade-in.
        • 'revealRight', or 5 : Reveal right for fade-in.
      • fade.time : Duration of fading. Default value is 500.
  • viewportCoordinate : Apply viewportCoordinate behavior to sprite game object.
    • false : Do nothing, default behavior.
    • true, or an object :
      • viewport :
        • undefined : Rectangle of display area under main camera of current scene. Default value.
        • A rectangle
  • defaultLayer : Put this game object into layer inside of layerManager.
  • symbols : Convert string value to number value when Set or Ease property of game object.
    • A plain object contains string key and number value.
"},{"location":"textplayer/#built-in-commands","title":"Built-in commands","text":"

goType : name parameter in config of txt.addGameObjectManager method

  • Add game object : [goType.name=a,b,c]
    • Tint-fade-in, or alpha-fade-in if fade is not 0
  • Remove game object : [/goType.name]
    • Tint-fade-out, or alpha-fade-out if fade is not 0
  • Remove all game objects : [/goType]
    • Tint-fade-out, or alpha-fade-out if fade is not 0
  • Call method : [goType.name.methodName=value0,value1,value2]
  • Set property : [goType.name.x=value], [goType.name.alpha=value], ....
  • Ease property :
    [goType.name.prop.easeMode=value,duration]\n[goType.name.prop.easeMode=value,duration,repeat]\n[goType.name.prop.easeMode=value,duration,easeFunction,repeat]\n[goType.name.prop.easeMode=value]\n
    • prop : Any number property of this sprite.
    • easeMode : One of these modes
      • to, toLeft, toRight, toUp, toDown
      • yoyo, yoyoLeft, yoyoRight, yoyoUp, yoyoDown
      • from, fromLeft, fromRight, fromUp, fromDown
    • duration : Default value is 1000
    • easeFunction : Default value is 'Linear'
    • repeat : Default value is 0
  • Wait ease task of game object's number property : [wait=goType.name.prop]
    • Also fire event 'wait.' + goType
      txt.on('wait.' + goType, function(name, prop) {\n})\n
  • Wait a game objects are destroyed : [wait=goType.name]
    • Also fire event 'wait.' + goType
      txt.on('wait.' + goType, function(name, prop) {\n// prop parameter are `undefined` here\n})\n
  • Wait all game objects are destroyed : [wait=goType]
    • Also fire event 'wait.' + goType
      txt.on('wait.' + goType, function(name, prop) {\n// name and prop parameter are `undefined` here\n})\n
  • Wait boolean data in game object's data manager set to true/false : [wait=goType.name.dataKey]/[wait=goType.name.!dataKey]
    • Also fire event 'wait.' + goType
      txt.on('wait.' + goType, function(name, prop) {\n})\n
"},{"location":"textplayer/#typing-content","title":"Typing content","text":"
txt.play(content);\n

or

txt.playPromise(content)\n.then(function(){\n// Typing content complete\n})\n
"},{"location":"textplayer/#show-current-page","title":"Show current page","text":"
txt.showPage();\n
  • Set typing speed to 0.
  • Set animation progress to 1.
  • Skip all waiting events.
  • Stop current sound effects, and ignore remainder sound effects.
"},{"location":"textplayer/#typing-next-page","title":"Typing next page","text":"
txt.typingNextPage();\n
  • Set nextPageInput to null, or false in config.
"},{"location":"textplayer/#ignore-next-page-input","title":"Ignore next page input","text":"
  • Ignore next page input
    txt.setIgnoreNextPageInput();\n
  • Rollback waiting next page input
    txt.setIgnoreNextPageInput(false);\n
"},{"location":"textplayer/#pause","title":"Pause","text":"
  • Pause typing
    txt.pauseTyping();\n
  • Pause typing and typing animation
    txt.pause();\n
"},{"location":"textplayer/#resume","title":"Resume","text":"
  • Resume typing
    txt.resumeTyping();\n
  • Resume typing and typing animation
    txt.resume();\n
"},{"location":"textplayer/#typing-speed","title":"Typing speed","text":"
  • Get
    • Default typing speed
      var speed = txt.defaultTypingSpeed;\n
    • Current typing speed
      var speed = txt.typingSpeed;\n
  • Set
    • Default typing speed
      txt.setDefaultTypingSpeed(speed);\n
      txt.defaultTypingSpeed = speed;\n
    • Current typing speed
      txt.setTypingSpeed(speed);\n// txt.setTypingSpeed();    // Set speed to default speed\n
      txt.typingSpeed = speed;\n
"},{"location":"textplayer/#time-scale","title":"Time scale","text":"

Time scale of typing, typing animation, sprite animation and easing of sprite's properties.

  • Get
    var timeScale = txt.timeScale;\n
  • Set
    txt.setTimeScale(timeScale);    
    txt.timeScale = timeScale;\n
"},{"location":"textplayer/#status","title":"Status","text":"
  • Is playing : After txt.play(content), before typing all pages completed
    var isPlaying = txt.isPlaying\n
  • Is page typing : After txt.play(content), or txt.typingNextPage(), before page typing completed
    var isPageTyping = txt.isPageTYyping;\n
"},{"location":"textplayer/#events","title":"Events","text":"
  • On typing content complete
    txt.on('complete', function() {\n\n})\n
  • On typing a character or an image
    txt.on('typing', function(child) {\nif (child.type === 'text') {\nvar character = child.text;\n} else {\nvar textureLey = child.key;\nvar frameKey = child.frame;\n}\n})\n
  • On typing a page start
    txt.on('page.start', function() {\n\n})\n
  • On typing a page complete
    txt.on('page.complete', function() {\n\n})\n
"},{"location":"textplayer/#tags-of-content","title":"Tags of content","text":""},{"location":"textplayer/#content","title":"Content","text":"

These lines will be skipped :

  • Empty line, which only has space characters.
  • Comment line, start with '//'.

New line symbol '\\n' will be removed, use [r] to insert a new line character.

"},{"location":"textplayer/#content-output-switch","title":"Content output switch","text":"
  • Turn off content output : [content.off]
  • Turn on content output : [content.on]
"},{"location":"textplayer/#content-output-enable","title":"Content output enable","text":"
  • Content won't output if parser.setContentOutputEnable(false) under custom tag events
    • Fire 'parser.+custom#content' event if conent is ignored now
      txt.on('parser.+custom#content', function(parser, content) {\n\n})\n
  • Invoke parser.setContentOutputEnable() to turn on content output back.
"},{"location":"textplayer/#text-style","title":"Text style","text":"
  • Font color : [color=red]content[/color], [color=#FF0000]content[/color]
  • Font size : [size=24]content[/size]
  • Bold : [b]content[/b]
  • Italic : [i]content[/i]
  • Stroke : [stroke]content[/stroke], [stroke=red]content[/stroke]
    • strokeThickness is set in config
  • Shadow : [shadow]content[/shadow], [shadow=red]content[/shadow]
    • shadowOffsetX, shadowOffsetY, shadowBlur are set in config
  • Character offset Y : [y=-8]c[/y]ontent
  • Character offset X : [x=10]c[/x]ontent
  • Left space : [left=10]c[/left]ontent
  • Right space : conten[right=10]t[/right]
  • Line-align : [align=left], [align=center], [align=right]
"},{"location":"textplayer/#new-line","title":"New line","text":"
  • New line : [r]
    • New line via \\n will be ignored.
"},{"location":"textplayer/#page-break","title":"Page break","text":"
  • [pagebreak], or [pb] : Put remainder characters to next page.
"},{"location":"textplayer/#image","title":"Image","text":"

[img=key]

"},{"location":"textplayer/#render-size","title":"Render size","text":"
  • Set render size in config
    {\nimages: {\n// key: {width, height},\n// key: {key, frame, width, height, tintFill: false}\n}\n}\n
    • tintFill :
      • false : Keep original color. Default behavior.
      • true : Change fill-color by color tag. [color=...][img=...].
  • Set render size by method
    txt.addImage({\n// key: {width, height},\n// key: {key, frame, width, height, tintFill: false}\n})\n
  • Use origin render size by default
"},{"location":"textplayer/#space","title":"Space","text":"

[space=width]

"},{"location":"textplayer/#typing-speed_1","title":"Typing speed","text":"
  • No typing : [speed=0]
  • Set speed : [speed=1000]
  • Back to default speed : [/speed]
"},{"location":"textplayer/#sprite","title":"Sprite","text":"
  • Add sprite : [sprite.name=textureKey,frameKey]
    • Tint-fade-in if sprite.fade is not 0
  • Remove sprite : [/sprite.name]
    • Tint-fade-out if sprite.fade is not 0
  • Remove all sprites : [/sprite]
    • Tint-fade-out if sprite.fade is not 0
  • Call method : [sprite.name.methodName=value0,value1,value2]
  • Set property : [sprite.name.x=value], [sprite.name.alpha=value], ....
  • Ease property :
    [sprite.name.x.to=value,duration]\n
    [sprite.name.x.to=value,duration,repeat]\n
    [sprite.name.x.to=value,duration,easeFunction,repeat]\n
    [sprite.name.x.to=value]\n
    • duration : Default value is 1000
    • easeFunction : Default value is 'Linear'
    • repeat : Default value is 0
  • Yoyo ease property :
    [sprite.name.x.yoyo=value,duration]\n
    [sprite.name.x.yoyo=value,duration,repeat]\n
    [sprite.name.x.yoyo=value,duration,easeFunction,repeat]\n
    [sprite.name.x.yoyo=value]\n
  • Set texture : [sprite.name.texture=textureKey,frameKey]
  • Play animation : [sprite.name.play=animationKey], or [sprite.name.play=animationKey0,animationKey1,...]
    • Can play animation without adding sprite first.
  • Stop animation : [/sprite.name.play], or [sprite.name.stop]
  • Pause animation : [sprite.name.pause]
"},{"location":"textplayer/#sound-effect","title":"Sound effect","text":"
  • Play : [se=key], [se2=key]
    • Sound effect will be destroyed when complete
  • Play with fade in volume : [se=key,1000], [se2=key,1000]
  • Fade in volume : [se.fadein=1000], [se2.fadein=1000]
  • Fade out volume : [se.fadeout=1000], [se2.fadeout=1000]
  • Fade out volume then stop : [se.fadeout=1000,stop], [se2.fadeout=1000,stop]
  • Set volume : [se.volume=1], [se2.volume=1]
"},{"location":"textplayer/#background-music","title":"Background music","text":"
  • Play, stop : [bgm=key], [/bgm], [bgm2=key],[/bgm2]`
    • Previous background music will be stopped and destroyed.
    • Cross fade to next background music if sounds.bgm.fade/sounds.bgm2.fade is not 0
  • Play with fade in volume : [bgm=key,1000], [bgm2=key,1000]
  • Pause, resume : [bgm.pause], [/bgm.pause], [bgm2.pause], [/bgm2.pause]
  • Fade in volume : [bgm.fadein=1000], [bgm2.fadein=1000]
  • Fade out volume : [bgm.fadeout=1000], [bgm2.fadeout=1000]
  • Fade out volume then stop : [bgm.fadeout=1000,stop], [bgm2.fadeout=1000,stop]
  • Cross fade to another background music : [bgm.cross=key,10000], [bgm2.cross=key,10000]
  • Set volume : [bgm.volume=1], [bgm2.volume=1]
  • Mute : [bgm.mute], [bgm2.mute], [bgm.unmute], [bgm2.unmute]
"},{"location":"textplayer/#camera","title":"Camera","text":"
  • Fade-in effect : [camera.fadein], [camera.fadein=1000], or [camera.fadein=duration,red,green,blue]
  • Fade-out effect : [camera.fadeout], [camera.fadeout=1000], or [camera.fadeout=duration,red,green,blue]
  • Flash effect : [camera.flash], [camera.flash=1000], or [camera.flash=duration,red,green,blue]
  • Shake effect : [camera.shake], [camera.shake=1000], or [camera.shake=duration,intensity]
  • Zoom
    • Set zoom : [camera.zoom=2]
    • Zoom to : [camera.zoom.to=1,1000], or [camera.zoom.to=zoomValue,duration,Cubic]
  • Rotate
    • Set angle : [camera.rotate=90], angle in degrees
    • Rotate to : [camera.rotate.to=0,1000], or [camera.rotate.to=deg,duration,Cubic], angle in degrees
  • Scroll
    • Scroll x,y : [camera.scroll=0,200]
    • Scroll x,y to : [camera.scroll.to=0,200,1000], or [camera.rotate.to=x,y,duration,Cubic]
"},{"location":"textplayer/#wait-conditions","title":"Wait conditions","text":"
  • Wait click : [wait=click], [click]
    • Also fire event 'wait.click'
       txt.on('wait.click', function() {\n})\n
  • Wait key-down : [wait=enter], [wait=space], ....
    • Also fire event 'wait.keydown'
       txt.on('wait.keydown', function(keyName) {\n})\n
  • Wait time : [wait=1000]
    • Also fire event 'wait.time'
       txt.on('wait.time', function(time) {\n})\n
  • Wait sound effect : [wait=se], [wait=se2]
    • Also fire event 'wait.music'
       txt.on('wait.music', function(music) {\n// var key = music.key;\n})\n
  • Wait background music : [wait=bgm], [wait=bgm2]
    • Also fire event 'wait.music'
       txt.on('wait.music', function(music) {\n// var key = music.key;\n})\n
  • Wait camera effect : [wait=camera.fadein], [wait=camera.fadeout], [wait=camera.flash], [wait=camera.shake], [wait=camera.zoom], [wait=camera.rotate], [wait=camera.scroll]
    • Also fire event 'wait.camera'
       txt.on('wait.camera', function(effectName) {\n// effectName : 'camera.fadein', 'camera.fadeout', 'camera.flash', 'camera.shake', 'camera.zoom', 'camera.rotate', 'camera.scroll'\n})\n
  • Wait ease task of sprite's property : [wait=sprite.name.prop]
    • Also fire event 'wait.sprite'
       txt.on('wait.sprite', function(name, prop) {\n})\n
  • Wait all sprites are destroyed : [wait=sprite]
    • Also fire event 'wait.sprite'
       txt.on('wait.sprite', function(name, prop) {\n// name and prop parameter are `undefined` here\n})\n
  • Wait callback : [wait], or [wait=xxx] (xxx is any string which not been used in above case)
    • Fire event 'wait'
      txt.on('wait', function(callback) {\n// Invoke `callback()` to continue typing\n})\n
    • Fire event 'wait.xxx'
      txt.on('wait.xxx', function(callback) {\n// Invoke `callback()` to continue typing\n})\n
  • Combine conditions : [wait=cond0|cond1|...]
    • Wait click, or enter key down : [wait=click|enter]
    • Wait click, enter key down, or 100ms : [wait=click|enter|1000]
"},{"location":"textplayer/#custom-tag","title":"Custom tag","text":"

Assume that adding a custom tag : [custom=10,20][/custom].

+custom parses the open tag [custom=10,20] and -custom parses the closing tag [/custom]

  • On parse a +custom tag, will add a custom command child
    txt.on('parser.+custom', function(parser, a, b, params) {\n// console.log('Parse +custom tag:', a, b)\n})\n
    • parses opening tag
    • a, b, ... : Parameters after =
    • params : Arguments array used when executing +custom. Equal to [a, b] in this case.
    • Disable content after this start tag
      parser.setContentOutputEnable(false);\n
  • On execute a +custom command child
    txt.on('tag.+custom', function(a, b) {\n// console.log('Execute +custom tag:', a, b)\n})\n
    • a, b, ... : Parameters passed from params in 'parser.+custom' event.
  • On parse a -custom tag, will add a custom command child
    txt.on('parser.-custom', function(parser, params) {\n// console.log('Parse -custom tag')\n})\n
    • parses closing tag
    • params : Arguments array used when executing -custom. Equal to [] in this case.
    • Enable content after this start tag
      parser.setContentOutputEnable(true);\n
  • On execute a -custom command child
    txt.on('tag.-custom', function(...params) {\n// console.log('Execute -custom tag')\n})\n
    • params : Parameters passed from params in 'parser.-custom' event.
"},{"location":"textplayer/#size","title":"Size","text":"
  • Resize canvas size
    txt.setCanvasSize(width, height)\n
  • Reisze text wrapping size and canvas size.
    txt.setSize(width, height);\n
    or
    txt.setFixedSize(width, height);\n
  • Resize to minimun size to show all visible characters.
    txt.setToMinSize();\n
"},{"location":"textplayer/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"textplayer/#create-mask","title":"Create mask","text":"
var mask = txt.createBitmapMask();\n

See mask

"},{"location":"textplayer/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"texttranslation/","title":"Translation","text":""},{"location":"texttranslation/#introduction","title":"Introduction","text":"

Apply translated string (i18next) to text object, bbcode text object, tag text object, bitmap text object, or label game object

  • Author: Rex
  • Behavior of text object
"},{"location":"texttranslation/#live-demos","title":"Live demos","text":"
  • Inline resources
  • External resources
  • External yaml resource
"},{"location":"texttranslation/#usage","title":"Usage","text":"

Sample code

"},{"location":"texttranslation/#install-plugin","title":"Install plugin","text":""},{"location":"texttranslation/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in scene's config
    class Demo extends Phaser.Scene {\nconstructor() {\nsuper({\nkey: 'Scnee',\npack: {\nfiles: [{\ntype: 'plugin',\nkey: 'rextexttranslationplugin',\nurl: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextexttranslationplugin.min.js',\nstart: true,\nmapping: 'translation'  // Add text-translation plugin to `scene.translation`\n}]\n},\n// ...\n});\n}\n// ...\n}\n
  • Initialize i18next during preload stage
    scene.plugins.get('rextexttranslationplugin').initI18Next(scene, {\nlng: 'dev',\nfallbackLng: 'dev',\nns: 'translation',\n\n// resources: {\n//     'dev': {\n//         'translation': {\n//             key: value,  \n//         }\n//     }\n// }\n\n// debug: true,\n\n// backend: {\n//     loadPath: '',\n//     parse: function(data) { return JSON.parse(data); }\n// },\n})\n
  • Add translation behavior
    var translation = scene.plugins.get('rextexttranslationplugin').add(textGameObject, config);\n
"},{"location":"texttranslation/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TextTranslationPlugin from 'phaser3-rex-plugins/plugins/texttranslation-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTextTranslation',\nplugin: TextTranslationPlugin,\nstart: true,\nmapping: 'translation'  // Add text-translation plugin to `scene.translation`\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Initialize i18next during preload stage
    scene.plugins.get('rexTextTranslation').initI18Next(scene, {\nlng: 'dev',\nfallbackLng: 'dev',\nns: 'translation',\n\n// resources: {\n//     'dev': {\n//         'translation': {\n//             key: value,  \n//         }\n//     }\n// }\n\n// debug: true,\n\n// backend: {\n//     loadPath: '',\n//     parse: function(data) { return JSON.parse(data); }\n// },\n})\n
  • Add translation behavior
    var translation = scene.plugins.get('rexTextTranslation').add(textGameObject, config);\n
"},{"location":"texttranslation/#import-class","title":"Import class","text":"
  • Install rex plugins, i18next, i18next-http-backend from npm
    npm i phaser3-rex-plugins\nnpm i i18next\nnpm i i18next-http-backend\n
  • Import class
    import TextTranslationBehavior from 'phaser3-rex-plugins/plugins/texttranslation.js';\nimport i18next from 'i18next';\nimport Backend from 'i18next-http-backend';\nimport Awaitloader from 'phaser3-rex-plugins/plugins/awaitloader.js';\n
  • Initialize i18next during preload stage
    Awaitloader.call(scene.load, function (successCallback, failureCallback) {\ni18next\n.use(Backend)\n.init({\nlng: 'dev',\nfallbackLng: 'dev',\nns: 'translation',\n\n// resources: {\n//     'dev': {\n//         'translation': {\n//             key: value,  \n//         }\n//     }\n// }\n\n// debug: true,\n\n// backend: {\n//     loadPath: '',\n//     parse: function(data) { return JSON.parse(data); }\n// },\n}, successCallback);\n})\nTextTranslationBehavior.setI18Next(i18next);\n
    • Awaitloader : Using Awaitloader to load external resource.
    • Backend : i18next-http-backend module can be used to load external resource.
    • TextTranslationBehavior.setI18Next(i18next) : Pass i18next to TextTranslationBehavior.
      • TextTranslationBehavior.setI18Next is a static method.
  • Add translation behavior
    var translation = new TextTranslationBehavior(textGameObject, config);\n
"},{"location":"texttranslation/#initialize-i18next","title":"Initialize i18next","text":"
scene.plugins.get('rexTextTranslation').initI18Next(scene, {\nlng: 'dev',\nfallbackLng: 'dev',\nns: 'translation',\n\n// resources: {\n//     'dev': {\n//         'translation': {\n//             key: value,  \n//         }\n//     }\n// }\n\n// debug: true,\n\n// backend: {\n//     loadPath: '',\n//     parse: function(data) { return JSON.parse(data); }\n// },\n})\n

or

i18next\n.use(Backend)\n.init(config, onComplete);\n
  • lng : Language to use. Will fallback to 'dev'.
  • fallbackLng : Language to use if translations in user language are not available. Setting it explicitly to false will not trigger to load the fallbackLng at all.
  • ns : String or array of namespaces to load. Default value is 'translation'.
  • debug : Logs info level to console output. Helps finding issues with loading not working. Default value is false.
  • resources : Resources to initialize with.
  • backend.loadPath : Path where resources get loaded from, or a function returning a path.
    function(lngs, namespaces) { return customPath; }\n
  • backend.parse : Parse data after it has been fetched. Optional.
    function(data) { return JSON.parse(data); }\n

See also Configuration Options, and Backend Options

"},{"location":"texttranslation/#create-instance","title":"Create instance","text":"
var translation = scene.plugins.get('rexTextTranslation').add(textGameObject, {\n// translationKey: '',\n// interpolation: {},\n\n// updateText: true,\n\n// setText: function(gameObject, text) { \n//     gameObject.setText(text); \n// }\n});\n
  • textObject : text object, bbcode text object, tag text object, bitmap text object, or label game object
  • translationKey : Key in translation resource. See Essentials
  • interpolation : Integrating dynamic values into translation result. See Interpolation
  • updateText :
    • true : Update text object via translationKey, and interpolation. Default behavior.
    • false : Don't update text object now.
  • setText : Callback invoked when updating text object. Default value is
    function(gameObject, text) {\ngameObject.setText(text);\n}\n
"},{"location":"texttranslation/#set-translation-key","title":"Set translation key","text":"
translation\n.setTranslationKey(key)\n.updateText()\n
"},{"location":"texttranslation/#set-interpolation","title":"Set interpolation","text":"
  • Assign interpolation object
    translation\n.setInterpolation(object)\n.updateText()\n
  • Update current interpolation object
    translation\n.updateInterpolation(key, value)\n.updateText()\n
    or
    translation\n.updateInterpolation(object)\n.updateText()\n
"},{"location":"texttranslation/#update-text","title":"Update text","text":"

Update text object via translationKey, and interpolation.

translation.updateText()\n
"},{"location":"texttranslation/#change-language","title":"Change language","text":"
scene.plugins.get('rexTextTranslation').changeLanguage(language);\n// scene.plugins.get('rexTextTranslation').changeLanguage(language, onComplete);\n

or

i18next.changeLanguage(language, onComplete);\n

All translation behavior will update text object after changing language.

"},{"location":"texttranslation/#set-default-namespace","title":"Set default namespace","text":"
scene.plugins.get('rexTextTranslation').setDefaultNamespace(namespace);\n

or

i18next.setDefaultNamespace(namespace);\n
"},{"location":"texttranslation/#translate-string","title":"Translate string","text":"
var result = scene.plugins.get('rexTextTranslation').t(translationKey, interpolation);\n

or

var result = i18next.t(translationKey, interpolation);\n
"},{"location":"texttranslation/#events","title":"Events","text":"
  • On language changed, triggered by changeLanguage method.
    scene.plugins.get('rexTextTranslation').on('languageChanged', function (lng) {\n});\n
    or
    i18next.on('languageChanged', function (lng) {\n});\n
"},{"location":"texttruncator/","title":"Truncator","text":""},{"location":"texttruncator/#introduction","title":"Introduction","text":"

Constraints text game object size by truncating text with padding symbol on text object, bbcode text object, or tag text object.

  • Author: Rex
  • Behavior of text object
"},{"location":"texttruncator/#live-demos","title":"Live demos","text":"
  • Truncate text
  • Truncate BBCodeText
"},{"location":"texttruncator/#usage","title":"Usage","text":"

Sample code

"},{"location":"texttruncator/#install-plugin","title":"Install plugin","text":""},{"location":"texttruncator/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextexttruncatorplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextexttruncatorplugin.min.js', true);\n
  • Add text-truncator behavior
    var truncator = scene.plugins.get('rextexttruncatorplugin').add(textGameObject, config);\n
"},{"location":"texttruncator/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TextTruncatorPlugin from 'phaser3-rex-plugins/plugins/texttruncator-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTextTruncator',\nplugin: TextTruncatorPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text-truncator behavior
    var truncator = scene.plugins.get('rexTextTruncator').add(textGameObject, config);\n
"},{"location":"texttruncator/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TextTruncator from 'phaser3-rex-plugins/plugins/texttruncator.js';\n
  • Add text-truncator behavior
    var truncator = new TextTruncator(textGameObject, config);\n
"},{"location":"texttruncator/#create-instance","title":"Create instance","text":"
var truncator = scene.plugins.get('rexTextTruncator').add(textGameObject, {\n// enable: true,\n// symbol: '...',\n// maxWidth: undefined,\n// maxHeight: undefined,\n// text: '',              // content in string or array\n});\n
  • textObject : Text object, bbcode text object, tag text object, or bitmap text object
  • enable :
    • true : Truncate string with padding symbol. Default value.
    • false : Display all text.
  • symbol : Padding symbol. Default value is '...'
  • maxWidth : Maximum width of game object, for single-line mode.
    • undefined : Use fixedWidth as maximum width.
  • maxHeight : Maximum height of game object, for multiple-line mode.
    • undefined : Use fixedHeight as maximum height.
  • text : content in string or array, optional
"},{"location":"texttruncator/#truncation-modes","title":"Truncation modes","text":"
  • Single-line mode :
    • maxHeight or fixedHeight are not given, or 0
    • Have maxWidth or fixedWidth
  • Multiple-line mode
    • Have fixedWidth or wordWrap.width (wrap-width)
    • Have maxHeight or fixedHeight
"},{"location":"texttruncator/#set-content","title":"Set content","text":"
  • Set content
    truncator.setText(content);\n
    • content : String, number, or string array.
  • Append content
    truncator.appendText(content);\n
    • content : String, number, or string array.

Will update displaying content.

  • Get content back
    var text = truncator.text;\n
"},{"location":"texttruncator/#update-display-content","title":"Update display content","text":"
truncator.updateText();\n
"},{"location":"texttruncator/#set-enable","title":"Set enable","text":"
truncator.setEnable(enable).updateText();\n
"},{"location":"texttruncator/#set-paddding-symbol","title":"Set paddding symbol","text":"
truncator.setSymbol(symbol).updateText();\n
"},{"location":"texttruncator/#set-max-size","title":"Set max size","text":"
  • Max width
    • Set
      truncator.setMaxWidth(width).updateText();\n
    • Get
      var width = truncator.maxWidth;\n
  • Max height
    • Set
      truncator.setMaxHeight(height).updateText();\n
    • Get
      var height = truncator.maxHeight;\n
"},{"location":"texttyping/","title":"Typing","text":""},{"location":"texttyping/#introduction","title":"Introduction","text":"

Typing text on text object, bbcode text object, or tag text object.

  • Author: Rex
  • Behavior of text object
"},{"location":"texttyping/#live-demos","title":"Live demos","text":"
  • BBCode text + page + typing
  • Text wrap enable
  • TextBox, see text-box.
"},{"location":"texttyping/#usage","title":"Usage","text":"

Sample code

"},{"location":"texttyping/#install-plugin","title":"Install plugin","text":""},{"location":"texttyping/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextexttypingplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextexttypingplugin.min.js', true);\n
  • Add typing behavior
    var typing = scene.plugins.get('rextexttypingplugin').add(textGameObject, config);\n
"},{"location":"texttyping/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TextTypingPlugin from 'phaser3-rex-plugins/plugins/texttyping-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTextTyping',\nplugin: TextTypingPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add typing behavior
    var typing = scene.plugins.get('rexTextTyping').add(textGameObject, config);\n
"},{"location":"texttyping/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TextTyping from 'phaser3-rex-plugins/plugins/texttyping.js';\n
  • Add typing behavior
    var typing = new TextTyping(textGameObject, config);\n
"},{"location":"texttyping/#create-instance","title":"Create instance","text":"
var typing = scene.plugins.get('rexTextTyping').add(textGameObject, {\n// wrap: false,\n// speed: 333,       // typing speed in ms\n// typeMode: 0,      //0|'left-to-right'|1|'right-to-left'|2|'middle-to-sides'|3|'sides-to-middle'\n// setTextCallback: function(text, isLastChar, insertIdx){ return text; }  // callback before set-text\n// setTextCallbackScope: null,   \n});\n
  • textObject : Text object, bbcode text object, tag text object, or bitmap text object
  • wrap :
    • false : Don't insert \\n, default behavior.
    • true : Insert \\n to wrap content according to style of text, to prevent typing jittering.
  • speed : Typing speed in ms, default value is 333.
  • typeMode :
    • 'left-to-right', or 0 : Typing characters from left to right.
    • 'right-to-left', or 1 : Typing characters from right to left.
    • 'middle-to-sides', or 2 : Typing characters from middle to sides.
    • 'sides-to-middle', or 3 : Typing characters from sides to middle.
  • setTextCallback : Callback befor set-text, to decorate display text.
    function(text, isLastChar, insertIdx) { return text; }\n
  • setTextCallbackScope : Scope of setTextCallback function.
"},{"location":"texttyping/#start-typing","title":"Start typing","text":"
typing.start(text);\n// typing.start(text, speed); \n
  • text : Typing content string.
  • speed : Typing speed in ms.
"},{"location":"texttyping/#start-typing-from-line","title":"Start typing from line","text":"
typing.startFromLine(text, lineIndex);\n// typing.startFromLine(text, lineIndex, speed);\n
  • text : Typing content string.
  • lineIndex : Start from line.
  • speed : Typing speed in ms.
"},{"location":"texttyping/#typing-more-text","title":"Typing more text","text":"
typing.appendText(text);\n
"},{"location":"texttyping/#stop-typing","title":"Stop typing","text":"
typing.stop();\n// typing.stop(true);;  // stop and show all text\n
"},{"location":"texttyping/#pauseresume-typing","title":"Pause/Resume typing","text":"
  • Pause typing
    typing.pause();\n
  • Resume typing
    typing.resume();\n
"},{"location":"texttyping/#set-typing-speed","title":"Set typing speed","text":"
typing.setTypingSpeed(speed);  // speed in ms\n// typing.speed = speed;\n

Set speed in typing event or setTextCallback to change typing speed of remaining text.

"},{"location":"texttyping/#set-typing-mode","title":"Set typing mode","text":"
typing.setTypeMode(mode);\n
  • typeMode :
    • 'left-to-right', or 0 : typing characters from left to right.
    • 'right-to-left', or 1 : typing characters from right to left.
    • 'middle-to-sides', or 2 : typing characters from middle to sides, optional.
    • 'sides-to-middle', or 3 : typing characters from sides to middle.
"},{"location":"texttyping/#events","title":"Events","text":"
  • On changing content of text game object :
    typing.on('type', function(){\n\n});\n
  • On typing a character
    typing.on('typechar', function(char){\n\n});\n
  • On typing completed :
    typing.on('complete', function(typing, txt){});\n
"},{"location":"texttyping/#status","title":"Status","text":"
  • Is typing
    var isTyping = typing.isTyping;\n
"},{"location":"textures/","title":"Textures","text":""},{"location":"textures/#introduction","title":"Introduction","text":"

Textures cache, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"textures/#usage","title":"Usage","text":""},{"location":"textures/#image-texture","title":"Image texture","text":"
  • Load image texture
    scene.load.image(key, url);\n
    Reference: Loader
  • Load image texture via base64 string
    scene.textures.addBase64(key, data)\n
  • Get image texture
    var texture = scene.textures.get(key);\nvar image = texture.getSourceImage();\n// var width = image.width;\n// var height = image.height;\n
  • Get image texture from frame object
    var texture = scene.textures.get(frameObject);\n
"},{"location":"textures/#get-pixel","title":"Get pixel","text":"
var color = scene.textures.getPixel(x, y, key);\n// var color = scene.textures.getPixel(x, y, key, frame);\n

Properties of color

  • r : 0 ~ 255
  • g : 0 ~ 255
  • b : 0 ~ 255
  • a : 0 ~ 255
  • color : color integer
var alpha = scene.textures.getPixelAlpha(x, y, key);\n// var alpha = scene.textures.getPixelAlpha(x, y, key, frame);\n

alpha : 0 ~ 255

Return null if the coordinates were out of bounds.

"},{"location":"textures/#generate-texture-from-array","title":"Generate texture from array","text":"
var config = {\ndata: data,\n// 3x3:\n// [ '...',\n//   '...',\n//   '...' ]\npixelWidth: 1,    // pixel width of each data\npixelHeight: 1,   // pixel height of each data\npreRender: null,  // callback, function(canvas, ctx) {}\npostRender: null, // callback, function(canvas, ctx) {}\n\ncanvas: null,  // create a canvas if null\nresizeCanvas: true,\nclearCanvas: true\n};\nvar texture = scene.textures.generate(key, config);\n
"},{"location":"textures/#has-key","title":"Has key","text":"
var hasKey = scene.textures.exists(key);\n
"},{"location":"textures/#remove-texture","title":"Remove texture","text":"

Remove texture stored in texture cache.

scene.textures.remove(key);\n
"},{"location":"textures/#get-base64","title":"Get base64","text":"
var s = scene.textures.getBase64(key);  // type= 'image/png', encoderOptions= 0.92\n// var s = scene.textures.getBase64(key, frame, type, encoderOptions);\n
"},{"location":"textures/#default-textures","title":"Default textures","text":"
  • Default : '__DEFAULT'
  • Missing : '__MISSING'
  • 4x4 white : '__WHITE'
"},{"location":"textures/#get-key-list-of-all-textures","title":"Get key list of all textures","text":"
var keys = scene.textures.getTextureKeys();\n
"},{"location":"textures/#texture","title":"Texture","text":""},{"location":"textures/#get-texture","title":"Get texture","text":"
var texture = scene.textures.get(key);\n
"},{"location":"textures/#has-frame","title":"Has frame","text":"
var hasFrame = texture.has(frameName);\n
"},{"location":"textures/#add-frame","title":"Add frame","text":"
var frame = texture.add(frameName, sourceIndex, x, y, width, height);\n
  • key : Texture key.
  • frameName : The name of this Frame. The name is unique within the Texture.
  • sourceIndex : The index of the TextureSource that this Frame is a part of.
  • x, y : The x/y coordinate of the top-left of this Frame.
  • width, height : The width/height of this Frame.
"},{"location":"textures/#remove-frame","title":"Remove frame","text":"
var removed = texture.remove(frameName);\n
"},{"location":"textures/#get-name-of-frames","title":"Get name of frames","text":"
var nameList = texture.getFrameNames();\n// nameList does not include `__BASE`\n

or

var nameList = texture.getFrameNames(true);\n// nameList includes `__BASE`\n
"},{"location":"textures/#frame-object","title":"Frame object","text":""},{"location":"textures/#get-frame","title":"Get frame","text":"
var frame = scene.textures.getFrame(key, frame);\n
"},{"location":"textures/#properties","title":"Properties","text":"
  • frame.source.image : Image of texture source.
  • frame.cutX : X position within the source image to cut from.
  • frame.cutY : Y position within the source image to cut from.
  • frame.cutWidth : The width of the area in the source image to cut.
  • frame.cutHeight : The height of the area in the source image to cut.
"},{"location":"textures/#add-atlas","title":"Add atlas","text":"
scene.textures.addAtlas(key, HTMLImageElement, data);\n// scene.textures.addAtlas(key, HTMLImageElement, data, dataSource);\n
  • key : The unique string-based key of the Texture.
  • HTMLImageElement : HTML Image element/s.
  • data : The Texture Atlas data/s.
    {\nframes: [\n{\n// Location of frame image\nframe: {\nx, y, w, h\n},\n\n// trimmed\ntrimmed:\nsourceSize: {\nw, h\n},\nspriteSourceSize: {\nx, y, w, h\n},\n\nrotated:\n\n// Custom origin\nanchor: pivot: {\nx, y\n},\n\n// Other custom properties of this frame ...\n}\n],\n\n// Other custom properties of this texture ...\n}\n
  • dataSource : An optional data Image element (normal map).

or

scene.textures.addAtlas(undefined, texture, data);\n// scene.textures.addAtlas(undefined, texture, data, dataSource);\n
  • texture : Phaser Texture.
"},{"location":"textures/#add-sprite-sheet","title":"Add sprite sheet","text":"
scene.textures.addSpriteSheet(key, HTMLImageElement, config);\n// scene.textures.addAtlas(key, HTMLImageElement, config, dataSource);\n
  • key : The unique string-based key of the Texture.
  • HTMLImageElement : HTML Image element/s.
  • config : The configuration object for this Sprite Sheet.
    {\nframeWidth: ,\nframeHeight: ,\nstartFrame: 0,\nendFrame: -1,\nmargin: 0,\nspacing: 0\n}\n
  • dataSource : An optional data Image element (normal map).

or

scene.textures.addSpriteSheet(undefined, texture, config);\n// scene.textures.addSpriteSheet(undefined, texture, config, dataSource);\n
  • texture : Phaser Texture.
"},{"location":"textures/#events","title":"Events","text":"
  • Texture manager is ready
    scene.textures.on('ready', function() {\n\n})\n
  • Add texture
    scene.textures.on('addtexture', function(key) {\n\n})\n
    or
    scene.textures.on('addtexture-' + key, function() {\n\n})\n
  • Error when adding texture
    scene.textures.on('onerror', function(key) {\n\n})\n
  • Remove texture
    scene.textures.on('removetexture', function(key) {\n\n})\n
    or
    scene.textures.on('removetexture-' + key, function() {\n\n})\n
"},{"location":"tiledmapdata/","title":"Tiled map data","text":""},{"location":"tiledmapdata/#introduction","title":"Introduction","text":"

Parses a Tiled JSON object into a new MapData object.

  • Author: Richard Davey
"},{"location":"tiledmapdata/#usage","title":"Usage","text":"
var mapData = Phaser.Tilemaps.Parsers.Tiled.ParseJSONTiled(name, json, insertNull);\n
  • name : The name of the tilemap, used to set the name on the MapData.
  • json : The Tiled JSON object.
  • insertNull : Controls how empty tiles, tiles with an index of -1.
    • true : Empty locations will get a value of null.
    • false : Empty location will get a Tile object with an index of -1.
"},{"location":"tiledmapdata/#map-data","title":"Map data","text":""},{"location":"tiledmapdata/#map-type","title":"Map type","text":"
var mapType = mapData.orientation;\n
  • mapType : orthogonal, isometric, hexagonal
"},{"location":"tiledmapdata/#map-size","title":"Map size","text":"
  • Grid size
    var mapWidth = mapData.width;\nvar mapHeight = mapData.height;\n
  • Pixel size
    var mapWidth = mapData.widthInPixels;\nvar mapHeight = mapData.heightInPixels;\n
"},{"location":"tiledmapdata/#tile-size","title":"Tile size","text":"
var tileWidth = mapData.tileWidth;\nvar tileHeight = mapData.tileHeight;\n
"},{"location":"tiledmapdata/#layer","title":"Layer","text":"
var layers = mapData.layers;\n
mapData.layers.forEach(function(layer){\nvar name = layer.name;\n\n\nvar alpha = layer.alpha;\nvar visible = layer.visible;\n\nvar x = layer.x;\nvar y = layer.y;\nvar width = layer.width;\nvar height = layer.height;\nvar data = layer.data;\n\nlayer.data.forEach(function(gid, index){\nvar tileX = index % width;\nvar tileY = Math.floor(index / width);\nif (gid === -1) { // Empty\n\n} else {\n\n}\n})\n})\n
"},{"location":"tilemap/","title":"Tile map","text":""},{"location":"tilemap/#introduction","title":"Introduction","text":"

Display of tiles map, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"tilemap/#usage","title":"Usage","text":""},{"location":"tilemap/#hierarchy","title":"Hierarchy","text":"
graph TB\n\ntilemap --> layerA[\"layerA<br>(Game object)\"]\ntilemap --> layerB\n\nlayerA --> tilesA[\"tiles<br>(layer.data[x][y])\"]\nlayerB --> tilesB[\"tiles\"]
  • map : A container for Tilemap data.
  • layer : A Game Object that renders LayerData from a map when used in combination with one or more tileset.
  • tiles : A 2d array of Tile object
    • Tile : A lightweight data representation, store position information without factoring in scroll, layer scale or layer position.
  • tileset : Image and tileData of some kind of tiles.
"},{"location":"tilemap/#load-tile-map","title":"Load tile map","text":"
scene.load.tilemapTiledJSON(key, url);   // JSON\nscene.load.tilemapCSV(key, url);         // CSV\n
"},{"location":"tilemap/#add-tile-map-object","title":"Add tile map object","text":"
  1. Create map
    • Create map from tiled
      var map = scene.add.tilemap(key);\n
      or
      var map = this.make.tilemap({ key: 'map', tileWidth: 16, tileHeight: 16\n});\n
      • Support ORTHOGONAL, ISOMETRIC, STAGGERED, HEXAGONAL map
    • Create map from 2d array
      var map = this.make.tilemap({\n// data: tileIdxArray,  // [ [], [], ... ]\ntileWidth: 32,\ntileHeight: 32,\nwidth: 10,\nheight: 10,\n});\n
      • Only support ORTHOGONAL map
    • Create map from csv
      var map = this.make.tilemap({\nkey: 'map',     // csv file\ntileWidth: 32,\ntileHeight: 32,\n});\n
      • Only support ORTHOGONAL map
  2. Add tileset image
    var tileset = map.addTilesetImage(tilesetName, key); // key: texture key\n// var tileset = map.addTilesetImage(tilesetName);  // key = tilesetName\n// var tileset = map.addTilesetImage(tilesetName, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid, tileOffset);\n
    • key : The key of the Phaser.Cache image used for this tileset.
      • undefined , null : Use tilesetName as default value.
    • tileWidth , tileHeight : The width/height of the tile (in pixels) in the Tileset Image.
      • undefined : Default to the map's tileWidth/tileHeight.
    • tileMargin : The margin around the tiles in the sheet (in pixels).
      • undefined : Default to 0
    • tileSpacing The spacing between each the tile in the sheet (in pixels).
      • undefined : Default to 0
    • gid : If adding multiple tilesets to a blank map, specify the starting GID this set will use here.
    • tileOffset : {x, y} Tile texture drawing offset.
  3. Create layer
    • Create existed layer
      var layer = map.createLayer(layerID, tileset);\n// var layer = map.createLayer(layerID, tileset, x, y);\n
      • tileset : The tileset, or an array of tilesets.
        • A string, or an array of string.
        • A tileset object, or an array of tileset objects.
      • x, y : Offset in pixels. Default is 0/0.
    • Create a new and empty layer
      var layer = map.createBlankLayer(layerID, tileset);\n// var layer = map.createBlankLayer(layerID, tileset, x, y, width, height, tileWidth, tileHeight); // x, y : offset in pixels\n
      • layerID : The name of this layer. Must be unique within the map.
      • tileset : The tileset, or an array of tilesets.
        • A string, or an array of string.
        • A tileset object, or an array of tileset objects.
      • x, y : Offset in pixels. Default is 0/0.
      • width, height : The width/height of the layer in tiles. Default is map.width/map.height.
      • tileWidth, tileHeight : The width/height of the tiles the layer uses for calculations. Default is map's tileWidth/tileHeight.
  4. Create game objects (optional)
    • Create game objects by Object-ID/Object-GID/Object-Name
      var sprites = map.createFromObjects(layerName, {\n// gid: 26,\n// name: 'bonus',\n// id: 9,\n\n// classType: Sprite,\n// ignoreTileset\n// scene,\n// container: null,\n// key: null,\n// frame: null\n}, useTileset);\n
      or
      var sprites = map.createFromObjects(layerName, configArray, useTileset);\n
      • One of filter
        • gid : Object GID.
        • id : Object ID.
        • name : Object Name.
      • classType : Class of game object, default is Sprite.
      • ignoreTileset :
      • scene : A Scene reference, passed to the Game Objects constructors. Default is map's scene.
      • container : Optional Container to which the Game Objects are added.
      • key, frame : Optional key of a Texture to be used.
    • Create game objects by tile
      var sprites = map.createFromTiles(indexes, replacements, spriteConfig);\n// var sprites = map.createFromTiles(indexes, replacements, spriteConfig, scene, camera, layer);\n
      • indexes : The tile index, or array of indexes
      • replacements :
        • null : Leave the tiles unchanged
        • Array of indexes : One-to-one mapping indexes to replacements.
      • spriteConfig : The config object to pass into the Sprite creator (i.e. scene.make.sprite).
        • useSpriteSheet : Set to true to load the tileset as a sprite sheet (not an image), map frame to tile index.
        • Copy rotation, flipX, flipY, alpha, visible and tint properties from Tile to sprites if these properties are not given.
      • scene : The Scene to create the Sprites within.
      • camera : The Camera to use when determining the world XY.
      • layer : The Tilemap Layer to act upon.
"},{"location":"tilemap/#map","title":"Map","text":""},{"location":"tilemap/#map-size","title":"Map size","text":"
var mapWidth = map.width;\nvar mapHeight = map.height;\n
"},{"location":"tilemap/#tile-size","title":"Tile size","text":"
  • Set
    map.setBaseTileSize(tileWidth, tileHeight);\n
  • Get
    var tileWidth = map.tileWidth;\nvar tileHeight = map.tileHeight;\n
"},{"location":"tilemap/#tileworld-position","title":"Tile/world position","text":"
  • World position -> Tile position
    var tileXY = map.worldToTileXY(worldX, worldY);\n// var out = map.worldToTileXY(worldX, worldY, snapToFloor, out, camera, layer);\n
  • Tile position -> World position
    var worldXY = map.tileToWorldXY(tileX, tileY);\n// var out = map.tileToWorldXY(tileX, tileY, out, camera, layer);\n
"},{"location":"tilemap/#tile-at-world-xy","title":"Tile at world XY","text":"
var hasTile = map.hasTileAtWorldXY(worldX, worldY);\n

or

var hasTile = map.hasTileAtWorldXY(worldX, worldY, camera, layer);\n
"},{"location":"tilemap/#draw-on-graphics","title":"Draw on graphics","text":"
map.renderDebug(graphics);\n

or

map.renderDebug(graphics, {\ntileColor: new Phaser.Display.Color(105, 210, 231, 150),         // null\ncollidingTileColor: new Phaser.Display.Color(243, 134, 48, 200), // null\nfaceColor: new Phaser.Display.Color(40, 39, 37, 150)             // null\n});\n

or

map.renderDebug(graphics, styleConfig, layer);\n
  • graphics : Graphics game object.
"},{"location":"tilemap/#layer","title":"Layer","text":"

A Game Object that renders LayerData from a map when used in combination with one or more tileset.

"},{"location":"tilemap/#get-layer","title":"Get layer","text":"
  • Get layer instance
    var layer = map.getLayer(name);\n
  • Set current layer of map
    map.setLayer(layer);  // layer name, layer index\n
    or
    map.layer = layer;\n
"},{"location":"tilemap/#render-pipeline","title":"Render pipeline","text":"
layer.setPipeline(pipelineName);\n
layer.setPostPipeline(pipelineName);\n

See Render pipeline section of Game object.

"},{"location":"tilemap/#render-order","title":"Render order","text":"
layer.setRenderOrder(renderOrder);\n
  • renderOrder
    • 0, or 'right-down'
    • 1, or 'left-down'
    • 2, or 'right-up'
    • 3, or 'left-up'
"},{"location":"tilemap/#fill-tiles","title":"Fill tiles","text":"
  • Fill current layer
    map.fill(index);  // Fill all grids\n
    or
    map.fill(index, tileX, tileY, width, height);\n
  • Fill layer
    layer.fill(index);  // Fill all grids\n
    or
    layer.fill(index, tileX, tileY, width, height);\n
"},{"location":"tilemap/#randomize","title":"Randomize","text":"
  • Randomize current layer
    map.randomize(); // Randomize all grids\n
    or
    map.randomize(tileX, tileY, width, height, indexes);\n
    • indexes An array of tile indexes.
      • -1 : Empty tile.
  • Weight randomize current layer
    map.weightedRandomize(\n{\n{ index: 0, weight: 4 },\n{ index: [0, 1], weight: 4 }\n},\ntileX, tileY, width, height);\n
  • Randomize layer
    layer.randomize();  // Randomize all grids\n
    or
    layer.randomize(tileX, tileY, width, height, indexes);\n
    • indexes An array of tile indexes.
  • Weight randomize layer
    layer.weightedRandomize(\n{\n{ index: 0, weight: 4 },\n{ index: [0, 1], weight: 4 }\n},\ntileX, tileY, width, height);\n
"},{"location":"tilemap/#copy-tiles","title":"Copy tiles","text":"
  • Copy current layer
    map.copy(srcTileX, srcTileY, width, height, destTileX, destTileY);\n
  • Copy layer
    map.copy(srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, layer);\n
    or
    layer.copy(srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces);\n
"},{"location":"tilemap/#put-tile-at","title":"Put tile at","text":"
  • Put on current layer
    map.putTileAt(tile, tileX, tileY);\n
    • tile :
      • Tile index
      • Tile object :
        var tile = map.getTileAt(tileX, tileY);\n
        or
        var tile = map.getTileAtWorldXY(worldX, worldY);\n
  • Put on layer
    map.putTileAt(tile, tileX, tileY, recalculateFaces, layer);\n
    or
    layer.putTileAt(tile, tileX, tileY, recalculateFaces);\n
    • tile : Tile index, or tile object.
"},{"location":"tilemap/#put-tiles-at","title":"Put tiles at","text":"
  • Put on current layer
    map.putTilesAt(tilesArray, tileX, tileY);  // tilesArray: 1d/2d array of Tile object or tile index\n
    • tilesArray : 1d/2d array of tile objects or tile indexes
  • Put on layer
    map.putTilesAt(tilesArray, tileX, tileY, recalculateFaces, layer);\n
    or
    layer.putTilesAt(tilesArray, tileX, tileY, recalculateFaces);\n
    • tilesArray : 1d/2d array of tile objects or tile indexes
"},{"location":"tilemap/#replace-tiles","title":"Replace tiles","text":"
  • Replace on current layer
    map.replaceByIndex(findIndex, newIndex); // Search on all grids\n
    or
    map.replaceByIndex(findIndex, newIndex, tileX, tileY, width, height);\n
  • Replace on layer
    map.replaceByIndex(findIndex, newIndex, tileX, tileY, width, height, layer);\n
    or
    layer.replaceByIndex(findIndex, newIndex, tileX, tileY, width, height);\n
"},{"location":"tilemap/#swap-tiles","title":"Swap tiles","text":"
  • Swap on current layer
    map.swapByIndex(indexA, indexB);\n
    or
    map.swapByIndex(indexA, indexB, tileX, tileY, width, height);\n
  • Swap on layer
    map.swapByIndex(indexA, indexB, tileX, tileY, width, height, layer);\n
    or
    layer.swapByIndex(indexA, indexB, tileX, tileY, width, height);\n
"},{"location":"tilemap/#shuffle-tiles","title":"Shuffle tiles","text":"
  • Shuffle on current layer
    map.shuffle();\n
    or
    map.shuffle(tileX, tileY, width, height);\n
  • Shuffle on layer
    map.shuffle(tileX, tileY, width, height, layer);\n
    or
    layer.shuffle(tileX, tileY, width, height);\n
"},{"location":"tilemap/#shader-effects","title":"Shader effects","text":"

`layer`` support postFX effects

Note

No preFX effect support

"},{"location":"tilemap/#tile","title":"Tile","text":""},{"location":"tilemap/#get-tile","title":"Get tile","text":"
var tile = map.getTileAt(tileX, tileY);\n// var tile = map.getTileAtWorldXY(worldX, worldY);\n

or

var tile = map.getTileAt(tileX, tileY, true, layer);  // Return a Tile object with an index of -1 for empty tile\n// var tile = map.getTileAtWorldXY(worldX, worldY, true, camera, layer);\n
  • layer : The tile layer to use. Default is current layer (map.setLayer(layer))
  • tile : A tile, or null if layer is invalid.
"},{"location":"tilemap/#get-tiles-within-a-rectangle-area","title":"Get tiles within a rectangle area","text":"
var tiles = map.getTilesWithin(tileX, tileY, width, height);\n

or

var tiles = map.getTilesWithin(tileX, tileY, width, height, {\n// isNotEmpty: false,\n// isColliding: false,\n// hasInterestingFace: false\n}, layer);\n
  • tileX , tileY : The left/top most tile index (in tile coordinates) to use as the origin of the area. Default is 0/0.
  • width , height : How many tiles wide/tall from the tileX/tileY index the area will be. Default is map.width/map.height.
  • filteringOptions : Optional filters to apply when getting the tiles.
    • isNotEmpty : If true, only return tiles that don't have -1 for an index.
    • isColliding : If true, only return tiles that collide on at least one side.
    • hasInterestingFace : If true, only return tiles that have at least one interesting face.
  • layer : The tile layer to use. Default is current layer (map.setLayer(layer))
  • tiles : An array of Tiles, or null if layer is invalid.
"},{"location":"tilemap/#get-tiles-within-world-xy","title":"Get tiles within world XY","text":"
var tiles = map.getTilesWithinWorldXY(worldX, worldY, width, height);\n

or

var tiles = map.getTilesWithinWorldXY(worldX, worldY, width, height,  {\n// isNotEmpty: false,\n// isColliding: false,\n// hasInterestingFace: false\n}, camera, layer);\n
  • worldX , worldY : The world x/y coordinate for the top-left of the area.
  • width , height : The width/height of the area. Default is map.width/map.height.
  • filteringOptions : Optional filters to apply when getting the tiles.
    • isNotEmpty : If true, only return tiles that don't have -1 for an index.
    • isColliding : If true, only return tiles that collide on at least one side.
    • hasInterestingFace : If true, only return tiles that have at least one interesting face.
  • camera : The Camera to use when factoring in which tiles to return. Default is main camera.
  • layer : The tile layer to use. Default is current layer (map.setLayer(layer))
  • tiles : An array of Tiles, or null if layer is invalid.
"},{"location":"tilemap/#get-tiles-within-shape","title":"Get tiles within shape","text":"
vat tiles = map.getTilesWithinShape(shape);\n

or

vat tiles = map.getTilesWithinShape(shape, {\n// isNotEmpty: false,\n// isColliding: false,\n// hasInterestingFace: false\n}, camera, layer);\n

Shape:

  • new Phaser.Geom.Rectangle(x0, y0, width, height)
  • new Phaser.Geom.Line(x0, y0, x1, y1)
  • new Phaser.Geom.Circle(x, y, radius)
  • new Phaser.Geom.Triangle(x0, y0, x1, y1, x2, y2)
"},{"location":"tilemap/#for-each-tile-in-layer","title":"For each tile in layer","text":"
map.forEachTile(function(tile, index, tileArray) { /* ... */ }, context);\n

or

map.forEachTile(function(tile, index, tileArray) { /* ... */ }, context,\ntileX, tileY, width, height, {\n// isNotEmpty: false,\n// isColliding: false,\n// hasInterestingFace: false\n}, layer);\n
  • tileX , tileY : The left/top most tile index (in tile coordinates) to use as the origin of the area to search.
  • width , height : How many tiles wide/tall from the tileX/tileY index the area will be. Default is map.width/map.height.
  • filteringOptions : Optional filters to apply when getting the tiles.
    • isNotEmpty : If true, only return tiles that don't have -1 for an index.
    • isColliding : If true, only return tiles that collide on at least one side.
    • hasInterestingFace : If true, only return tiles that have at least one interesting face.
  • layer : The tile layer to use. Default is current layer (map.setLayer(layer))
"},{"location":"tilemap/#tile-index","title":"Tile index","text":"
  • Get index
    var index = tile.index;\n
  • Copy index
    tile.index = index;\n
  • Copy
    tile.copy(tileSrc);\n
    Copies the tile data & properties from the given tile to this tile. This copies everything except for position and interesting faces.
"},{"location":"tilemap/#tile-position","title":"Tile position","text":"
var x = tile.x;\nvar y = tile.y;\n
"},{"location":"tilemap/#tile-corners","title":"Tile corners","text":"
var points = map.getTileCorners(tileX, tileY, camera, layer);\n
  • points : Array of vector2 corresponding to the world XY location of each tile corner.
"},{"location":"tilemap/#alpha","title":"Alpha","text":"
  • Set
    tile.setAlpha(value);\n
    or
    tile.alpha = value;\n
  • Get
    var alpha = tile.alpha;\n
"},{"location":"tilemap/#visible","title":"Visible","text":"
  • Set
    tile.setVisible(visible);\n
    or
    tile.visible = visible;\n
  • Get
    var visible = visible;\n
"},{"location":"tilemap/#flip","title":"Flip","text":"
  • Set
    tile.setFlipX(flipX);\ntile.setFlipY(flipY);\n
    or
    tile.flipX = flipX;\ntile.flipY = flipY;\n
  • Toggle
    tile.toggleFlipX();\ntile.toggleFlipY();\n
    or
    tile.flipX = !tile.flipX;\ntile.flipY = !tile.flipY;\n
  • Reset
    tile.resetFlip();\n
    or
    tile.flipX = false;\ntile.flipY = false;\n
  • Get
    var flipX = tile.flipX;\nvar flipY = tile.flipY;\n
"},{"location":"tilemap/#bounds","title":"Bounds","text":"
  • Bounds rectangle
    var bounds = tile.getBounds();\n// var out = tile.getBounds(camera, out);\n
  • Left
    var left = tile.getLeft();\n// var left = tile.getLeft(camera);\n
  • Right
    var right = tile.getRight();\n// var right = tile.getRight(camera);\n
  • CenterX
    var centerX = tile.getCenterX();\n// var centerX = tile.getCenterX(camera);\n
  • Top
    var top = tile.getTop();\n// var top = tile.getTop(camera);\n
  • Bottom
    var bottom = tile.getBottom();\n// var bottom = tile.getBottom(camera);\n
  • CenterY
    var centerY = tile.getCenterY();\n// var centerY = tile.getCenterY(camera);\n
"},{"location":"tilemap/#properties","title":"Properties","text":"
var properties = tile.properties;  // object or null\nvar value = properties[key];\n
tile.properties[key] = value;\n
"},{"location":"tilemap/#collision","title":"Collision","text":""},{"location":"tilemap/#enable-collision","title":"Enable collision","text":"
  • Enable collision by tile index
    map.setCollision(index);\n// map.setCollision(index, true, recalculateFaces, updateLayer);\n
    • index : Tile index, or an array of tile indexes.
  • Enable collision by tile index in a range
    map.setCollisionBetween(start, stop);\n// map.setCollisionBetween(start, stop, true, recalculateFaces, layer);\n
    • start , stop : The first/last index of the tile.
  • Enable collision excluded tile indexes
    map.setCollisionByExclusion(indexes);\n// map.setCollisionByExclusion(indexes, true, recalculateFaces, layer);\n
    • index : An array of tile indexes.
  • Enable collision by properties matching
    • Enable collision if value of tile property 'key' is equal to 'value'
      map.setCollisionByProperty({key:value});\n// map.setCollisionByProperty({key:value}, true, recalculateFaces, layer);\n
    • Enable collision if value of tile property 'key' is equal to 'value0', or 'value1'
      map.setCollisionByProperty({key:[value0, value1]});\n// map.setCollisionByProperty({key:[value0, value1]}, true, recalculateFaces, layer);\n
  • Enable collision by collision group
    map.setCollisionFromCollisionGroup();\n// map.setCollisionFromCollisionGroup(true, recalculateFaces, layer);\n
"},{"location":"tilemap/#disable-collision","title":"Disable collision","text":"
  • Disable collision by tile index
    map.setCollision(index, false);\n// map.setCollision(index, false, recalculateFaces, layer);\n
    • index : Tile index, or an array of tile indexes.
  • Disable collision by tile index in a range
    map.setCollisionBetween(start, stop, false);\n// map.setCollisionBetween(start, stop, false, recalculateFaces, layer);\n
    • start , stop : The first/last index of the tile.
  • Disable collision by properties matching
    • Disable collision if value of tile property 'key' is equal to 'value'
      map.setCollisionByProperty({key:value}, false);\n// map.setCollisionByProperty({key:value}, false, recalculateFaces, layer);\n
    • Disable collision if value of tile property 'key' is equal to 'value0', or 'value1'
      map.setCollisionByProperty({key:[value0, value1]}, false);\n// map.setCollisionByProperty({key:[value0, value1]}, false, recalculateFaces, layer);\n
  • Disable collision by collision group
    map.setCollisionFromCollisionGroup(false);\n// map.setCollisionFromCollisionGroup(false, recalculateFaces, layer);\n
"},{"location":"tilemap/#get-collision-group","title":"Get collision group","text":"
var collisionGroup = tile.getCollisionGroup();\n

or

var collisionGroup = tileset.getTileCollisionGroup(tile.index); // array of collision shapes, or null\n

Types of collision shape (collisionGroup.objects[i])

  • object.rectangle :
    {\nrectangle: true,\nx, y,\nwidth, height\n}\n
    • x, y : Offset position related top-left of tile.
      var worldX = tile.getLeft() + object.x;\nvar worldY = tile.getTop() + object.y;\n
    • width, height : Width/height of rectangle area in pixels.
  • object.ellipse :
    {\nellipse: true,\nx, y,\nwidth, height\n}\n
    • x, y : Offset position related top-left of tile.
      var centerX = tile.getLeft() + object.x + (object.width / 2);\nvar centerY = tile.getTop() + object.y + (object.height / 2);\n
    • width, height : Width/height of ellipse area in pixels.
  • object.polygon :
    {\nx, y,\npolygon: [{x,y}, {x,y}, ...]\n}\n
    • Each point :
      {\nx: tile.getLeft() + object.x + polygon[i].x,\ny: tile.getTop() + object.y + polygon[i].y\n}\n
  • object.polyline :
    {\nx, y,\npolyline: [{x,y}, {x,y}, ...]\n}\n
    • Each point :
      {\nx: tile.getLeft() + object.x + polyline[i].x,\ny: tile.getTop() + object.y + polyline[i].y\n}\n
"},{"location":"tilemap/#arcade-collision","title":"Arcade collision","text":"
scene.physics.add.collider(arcadeGO, layer);\n

or, in update stage:

scene.physics.world.collide(arcadeGO, layer);\n

See Collision section of Arcade-world.

"},{"location":"tilemap/#matter-collision","title":"Matter collision","text":"
  • Any colliding tiles will be given a Matter body.
    scene.matter.world.convertTilemapLayer(layer);\n
"},{"location":"tilemap/#tileset","title":"Tileset","text":""},{"location":"tilemap/#get-tileset","title":"Get tileset","text":"
var tileset = map.getTileset(name);\n
"},{"location":"tilemap/#change-texture-of-tileset","title":"Change texture of tileset","text":"
var texture = scene.sys.textures.get(key);\ntileset.setImage(texture);\n
"},{"location":"tilesprite/","title":"Tile sprite","text":""},{"location":"tilesprite/#introduction","title":"Introduction","text":"

Display of repeating texture, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"tilesprite/#usage","title":"Usage","text":""},{"location":"tilesprite/#load-texture","title":"Load texture","text":"
scene.load.image(key, url);\n

Reference: load image

"},{"location":"tilesprite/#add-tile-sprite-object","title":"Add tile sprite object","text":"
var image = scene.add.tileSprite(x, y, width, height, textureKey);\n

Add tile sprite from JSON

var image = scene.make.tileSprite({\nx: 0,\ny: 0,\nwidth: 512,\nheight: 512,\nkey: '',\n\n// angle: 0,\n// alpha: 1\n// flipX: true,\n// flipY: true,\n// scale : {\n//    x: 1,\n//    y: 1\n//},\n// origin: {x: 0.5, y: 0.5},\n\nadd: true\n});\n
"},{"location":"tilesprite/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTileSprite extends Phaser.GameObjects.TileSprite {\nconstructor(scene, x, y, width, height, texture, frame) {\nsuper(scene, x, y, width, height, texture, frame);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var image = new MyTileSprite(scene, x, y, key);\n
"},{"location":"tilesprite/#properties-of-tiles","title":"Properties of tiles","text":"
  • Position
    image.setTilePosition(x, y);\n
    or
    image.tilePositionX = x;\nimage.tilePositionY = y;\n
  • Scale
    image.setTileScale(scaleX, scaleY);\n
    or
    image.tileScaleX = scaleX;\nimage.tileScaleY = scaleY;\n
"},{"location":"tilesprite/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"tilesprite/#create-mask","title":"Create mask","text":"
var mask = image.createBitmapMask();\n

See mask

"},{"location":"tilesprite/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"timeline/","title":"Timeline","text":""},{"location":"timeline/#introduction","title":"Introduction","text":"

Schedule commands to happen at specific times in the future, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"timeline/#usage","title":"Usage","text":""},{"location":"timeline/#create-timeline","title":"Create timeline","text":"
var timeline = scene.add.timeline([    {\n// Time condition\nat: 0,\nin:\nfrom:\n\n// Enable condition\nif(event) {\n// this: target parameter\nreturn true;  // false\n},\n\nset: {\nkey: value,\n},\n\ntween: {\ntargets: gameObject,\nalpha: 1,\nease: 'Linear',       // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\nrepeat: 0,            // -1: infinity\nyoyo: false\n},\n\nrun(){ // this: target parameter\n},\n\nloop() {\n\n},\n\nsound: '',\n\nevent: '',\n\n// target: this,\n\n// once: false,\n// stop: false,\n},\n\n// ...\n])\n
  • Time :
    • at : Absolute delay time after starting in ms.
    • in : Absolute delay time after current time in ms.
    • from : Relative delay time after previous event in ms
  • Enable :
    • if : A function. Invoking every tick, run actions when it returns true.
  • Actions :
    • set : A key-value object of properties to set on the target.
    • tween : tween config
    • run : A function which will be called when the Event fires.
      function() {\n// this: target parameter\n}\n
    • loop : A function which will be called when the Event sequence repeat again.
      function() {\n// this: target parameter\n}\n
    • sound :
      • A string : A key from the Sound Manager to play
      • A config object for a sound to play when the Event fires.
        {\nkey,\nconfig\n}\n
        • key : The key of the sound to play
        • config : config of playing sound
    • event : String-based event name to emit when the Event fires. The event is emitted from the Timeline instance.
      timeline.on(eventName);\n
    • target : The scope (this object) with which to invoke the run.
  • Control
    • once : If set, the Event will be removed from the Timeline when it fires.
    • stop : If set, the Timeline will stop and enter a complete state when this Event fires, even if there are other events after it.

The Timeline always starts paused.

"},{"location":"timeline/#steps-of-commands","title":"Steps of commands","text":"

For each tick, for each command :

  1. Test time (at, in, from)
  2. Test enable (if)
  3. Run actions (set, tween, run, sound, event)
  4. Control (once, stop)
"},{"location":"timeline/#start","title":"Start","text":"
timeline.play();\n
"},{"location":"timeline/#restart","title":"Restart","text":"
timeline.play(true);\n
"},{"location":"timeline/#start-with-repeat","title":"Start with repeat","text":"
  • Repeat infinite
    timeline.repeat().play();\n// timeline.repeat(true).play();\n// timeline.repeat(-1).play();\n
  • Amount of times to repeat
    timeline.repeat(amount).play();\n
    • amount : A positive number
  • No repeat
    timeline.repeat(false);\n
  • Current loop counter
    var loopCounter = timeline.iteration;\n
"},{"location":"timeline/#stop","title":"Stop","text":"
timeline.stop();\n
"},{"location":"timeline/#pause-resume","title":"Pause / Resume","text":"
timeline.pause();\n// timeline.paused = true;\n
timeline.resume();\n// timeline.paused = false;\n

Will also pause/resume currently active Tweens.

"},{"location":"timeline/#reset","title":"Reset","text":"

Resets this Timeline back to the start, include loop counter.

If the Timeline had any events that were set to once that have already been removed, they will not be present again after calling this method.

timeline.reset();\n

If the Timeline isn't currently running (i.e. it's paused or complete) then calling this method resets those states, the same as calling Timeline.play(true) (restart).

"},{"location":"timeline/#add-command","title":"Add command","text":"
timeline.add(config);\n

or

timeline.add([config0, config1, ...]);\n
"},{"location":"timeline/#clear-all-commands","title":"Clear all commands","text":"
timeline.clear();\n

Will also destroy currently active Tweens.

"},{"location":"timeline/#events","title":"Events","text":"
  • On all commands are completed
    timeline.on('complete', function(){\n\n});\n
"},{"location":"timeline/#other-properties","title":"Other properties","text":"
  • Timeline is currently playing, not paused or not complete.
    var isPlaying = timeline.isPlaying()\n
  • Is paused
    var isPaused = timeline.paused;\n
  • All commands are complete
    var isCompleted = timeline.complete;\n
"},{"location":"timeline/#destroy","title":"Destroy","text":"

Also remove updating.

timeline.destroy();\n

Will also destroy currently active Tweens.

"},{"location":"timer/","title":"Timer","text":""},{"location":"timer/#introduction","title":"Introduction","text":"

Execute callback when time-out, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"timer/#usage","title":"Usage","text":""},{"location":"timer/#start-timer","title":"Start timer","text":"
  • Looped timer
    var timer = scene.time.addEvent({\ndelay: 500,                // ms\ncallback: callback,\n//args: [],\ncallbackScope: thisArg,\nloop: true\n});\n
  • Repeat timer
    var timer = scene.time.addEvent({\ndelay: 500,                // ms\ncallback: callback,\n//args: [],\ncallbackScope: thisArg,\nrepeat: 4\n});\n
  • Oneshot timer
    var timer = scene.time.delayedCall(delay, callback, args, scope);  // delay in ms\n
  • All properties of timer
    var timer = scene.time.addEvent({\ndelay: 500,                // ms\ncallback: callback,\nargs: [],\ncallbackScope: thisArg,\nloop: false,\nrepeat: 0,\nstartAt: 0,\ntimeScale: 1,\npaused: false\n});\n
  • Reuse timer
    timer.reset({\ndelay: 500,                // ms\ncallback: callback,\nargs: [],\ncallbackScope: thisArg,\nloop: false,\nrepeat: 0,\nstartAt: 0,\ntimeScale: 1,\npaused: false\n})\nscene.time.addEvent(timer);\n

Note

Throw error message if delay : 0 with (repeat > 0 or loop: true)

"},{"location":"timer/#pauseresume","title":"Pause/resume","text":"
  • Pause timer
    timer.paused = true;\n
  • Resume timer
    timer.paused = false;\n
  • Is paused
    var isPaused = timer.paused;\n
"},{"location":"timer/#stop","title":"Stop","text":"
  • Stop a running timer
    timer.remove();\n
  • Remove from timeline's all internal lists, for timer re-using
    scene.time.removeEvent(timer);\n
"},{"location":"timer/#time-scale","title":"Time scale","text":"
  • Set
    timer.timeScale = 2;\n
  • Get
    var timeScale = timer.timeScale;\n
"},{"location":"timer/#other-properties","title":"Other properties","text":"
  • Get elapsed time
    var elapsed = timer.getElapsed();   // ms\nvar elapsed = timer.getElapsedSeconds(); // sec\n// var elapsed = timer.elapsed;  // ms\n
  • Get remaining time
    var remaining = timer.getRemaining();   // ms\nvar remaining = timer.getRemainingSeconds(); // sec\n// var remaining = timer.getOverallRemaining();   // ms\n// var remaining = timer.getOverallRemainingSeconds(); // sec\n
  • Get repeat count
    var repeat = timer.getRepeatCount();\n
  • Gets the progress of the current iteration
    var progress = timer.getProgress();  // elapsed / delay\n
  • Gets the progress of the timer overall, factoring in repeats.
    var progress = timer.getOverallProgress();  // totalElapsed / totalDuration\n
  • Get delay time
    var delay = timer.delay;   // ms\n
"},{"location":"tintrgb/","title":"TintRGB","text":""},{"location":"tintrgb/#introduction","title":"Introduction","text":"

Attach tintR, tintG, tintB, and tintGray properties to a game object.

Note

This behavior will override default tint property

  • Author: Rex
  • Method only
"},{"location":"tintrgb/#live-demos","title":"Live demos","text":"
  • Fade
  • Yellow to green
"},{"location":"tintrgb/#usage","title":"Usage","text":"

Sample code

"},{"location":"tintrgb/#install-plugin","title":"Install plugin","text":""},{"location":"tintrgb/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextintrgbplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextintrgbplugin.min.js', true);\n
  • Attach tintR, tintG, tintB, and tintGray properties.
    scene.plugins.get('rextintrgbplugin').add(gameObject, tintRGB);\ngameObject.tintGray = 128;\n
"},{"location":"tintrgb/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TintRGBPlugin from 'phaser3-rex-plugins/plugins/tintrgb-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTintRGB',\nplugin: TintRGBPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Attach tintR, tintG, tintB, and tintGray properties.
    scene.plugins.get('rexTintRGB').add(gameObject, tintRGB);\ngameObject.tintGray = 128;\n
"},{"location":"tintrgb/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import AddTintRGBProperties from 'phaser3-rex-plugins/plugins/tintrgb.js';\n
  • Attach tintR, tintG, tintB, and tintGray properties.
    AddTintRGBProperties(gameObject, tintRGB);\ngameObject.tintGray = 128;\n
"},{"location":"tintrgb/#attach-properties","title":"Attach properties","text":"
scene.plugins.get('rexTintRGB').add(gameObject, tintRGB);\ngameObject.tintGray = 128;\n// gameObject.tintR = 128;\n// gameObject.tintG = 128;\n// gameObject.tintB = 128;\n
  • tintRGB : Initial tintRGB value in 0xRRGGBB.
  • tintR : color R of tint, 0~255. Default is 255.
  • tintG : color G of tint, 0~255. Default is 255.
  • tintB : color B of tint, 0~255. Default is 255.
  • tintGray :\u3000Gray tint, 0~255. Default is 255.
    • Set gameObject.tintGray is equal to set tintR, tintG, tintB with the same value.
"},{"location":"tintrgb/#fade","title":"Fade","text":"
scene.tweens.add({\ntargets: gameObject,\ntintR: 0,\ntintG: 0,\ntintB: 0,\n// tintGray: 0,\nduration: 3000\n})\n
"},{"location":"tools/","title":"Tools","text":""},{"location":"tools/#texture-atlas","title":"Texture atlas","text":""},{"location":"tools/#texture-packer","title":"Texture-packer","text":"

Texture-packer

"},{"location":"tools/#free-texture-packer","title":"Free texture packer","text":"

Free texture packer, Web app

"},{"location":"tools/#leshy-spritesheet-tool","title":"Leshy SpriteSheet Tool","text":"

Leshy SpriteSheet Tool

Export to JSON-TP-Hash

"},{"location":"tools/#aseprite","title":"Aseprite","text":"

Aseprite

  1. Go to \"File - Export Sprite Sheet\"
  2. On the Layout tab:
  3. Set the \"Sheet type\" to \"Packed\"
  4. Set the \"Constraints\" to \"None\"
  5. Check the \"Merge Duplicates\" checkbox
  6. On the Sprite tab:
    1. Set \"Layers\" to \"Visible layers\"
    2. Set \"Frames\" to \"All frames\", unless you only wish to export a sub-set of tags
  7. On the Borders tab:
    1. Check the \"Trim Sprite\" and \"Trim Cells\" options
    2. Ensure \"Border Padding\", \"Spacing\" and \"Inner Padding\" are all > 0 (1 is usually enough)
  8. On the Output tab:
    1. Check \"Output File\", give your image a name and make sure you choose \"png files\" as the file type
    2. Check \"JSON Data\" and give your json file a name
    3. The JSON Data type can be either a Hash or Array, Phaser doesn't mind.
    4. Make sure \"Tags\" is checked in the Meta options
    5. In the \"Item Filename\" input box, make sure it says just \"{frame}\" and nothing more.
  9. Click export

Tested with Aseprite 1.2.25

"},{"location":"tools/#atlas-packer","title":"Atlas-packer","text":"
  • gammafp/Atlas-packer
"},{"location":"tools/#animation","title":"Animation","text":"
  • gammafp/Animator
"},{"location":"tools/#bitmap-font","title":"Bitmap font","text":"
  • SnowB BMF
  • 71squared-glyphdesigner
  • Bitmap Font Generator
  • TTF to PNG
"},{"location":"touchevents/","title":"Touch events","text":""},{"location":"touchevents/#introduction","title":"Introduction","text":"

Built-in touch/mouse events of phaser.

  • Author: Richard Davey

Note

No touch input event fired in preload stage.

"},{"location":"touchevents/#usage","title":"Usage","text":""},{"location":"touchevents/#quick-start","title":"Quick start","text":"
  • Is touching
    var pointer = scene.input.activePointer;\nif (pointer.isDown) {\nvar touchX = pointer.x;\nvar touchY = pointer.y;\n// ...\n}\n
  • On any touching start
    scene.input.on('pointerdown', function(pointer){\nvar touchX = pointer.x;\nvar touchY = pointer.y;\n// ...\n}, scope);\n
  • On any touching end
    scene.input.on('pointerup', function(pointer){\nvar touchX = pointer.x;\nvar touchY = pointer.y;\n// ...\n}, scope);\n
  • On touch game object start
    gameObject.setInteractive().on('pointerdown', function(pointer, localX, localY, event){\n// ...\n}, scope);\n
  • On touch game object end
    gameObject.setInteractive().on('pointerup', function(pointer, localX, localY, event){\n// ...\n}, scope);\n
  • Drag game object
    gameObject\n.setInteractive({ draggable: true })\n.on('dragstart', function(pointer, dragX, dragY){\n// ...\n}, scope);\n.on('drag', function(pointer, dragX, dragY){\ngameObject.setPosition(dragX, dragY);\n}, scope);\n.on('dragend', function(pointer, dragX, dragY, dropped){\n// ...\n}, scope);\n

Reference : Properties of point

"},{"location":"touchevents/#register-interactive","title":"Register interactive","text":"

Call gameObject.setInteractive(...) to register touch input of Game Object before listening touching events.

  • Set hit area from width & height (rectangle) of the texture
    gameObject.setInteractive();\n
  • Set hit area from game object
    gameObject.setInteractive(shape, callback);\n
    • Circle
      • shape : new Phaser.Geom.Circle(x, y, radius)
      • callback : Phaser.Geom.Circle.Contains
    • Ellipse
      • shape : new Phaser.Geom.Ellipse(x, y, width, height)
      • callback : Phaser.Geom.Ellipse.Contains
    • Rectangle
      • shape : new Phaser.Geom.Rectangle(x, y, width, height)
      • callback : Phaser.Geom.Rectangle.Contains
    • Triangle
      • shape : new Phaser.Geom.Triangle(x1, y1, x2, y2, x3, y3)
      • callback : Phaser.Geom.Triangle.Contains
    • Polygon
      • shape : new Phaser.Geom.Polygon(points)
      • callback : Phaser.Geom.Polygon.Contains
    • Hexagon
      • shape : new Phaser.Geom.rexHexagon(x, y, size, type)
      • callback : Phaser.Geom.Polygon.Contains
    • Rhombus
      • shape : new Phaser.Geom.rexRhombus(x, y, width, height)
      • callback : Phaser.Geom.Polygon.Contains
    • Note: x, y relate to the top-left of the gameObject.
  • Set hit area from input plugin
    scene.input.setHitArea(gameObjects, shape, callback);\n
    • Circle
      scene.input.setHitAreaCircle(gameObjects, x, y, radius);\n// scene.input.setHitAreaCircle(gameObjects, x, y, radius, callback); // callback = Circle.Contains\n
    • Ellipse
      scene.input.setHitAreaEllipse(gameObjects, x, y, width, height);\n// scene.input.setHitAreaEllipse(gameObjects, x, y, width, height, callback); // callback = Ellipse.Contains\n
    • Rectangle
      scene.input.setHitAreaRectangle(gameObjects, x, y, width, height);\n// scene.input.setHitAreaRectangle(gameObjects, x, y, width, height, callback); // callback = Rectangle.Contains\n
    • Triangle
      scene.input.setHitAreaTriangle(gameObjects, x1, y1, x2, y2, x3, y3);\n// scene.input.setHitAreaTriangle(gameObjects, x1, y1, x2, y2, x3, y3, callback); // callback = Triangle.Contains\n
    • Note: x, y relate to the top-left of the gameObject.
  • Set interactive configuration
    gameObject.setInteractive({\nhitArea: shape,\nhitAreaCallback: callback,\nhitAreaDebug: shape,\ndraggable: false,\ndropZone: false,\nuseHandCursor: false,\ncursor: CSSString,\npixelPerfect: false,\nalphaTolerance: 1\n});\n
    • Hit area
      • shape
      • Pixel alpha
        • pixelPerfect : true
        • alphaTolerance : 1 (0-255)
      • Custom hit-testing function
        • hitAreaCallback
          function(shape, x, y, gameObject) {\nreturn hit;  // true/false\n}\n
          • shape : Hit area object
          • x, y : Local position of texture.
          • gameObject : Game object.
      • hitAreaDebug : Debug shape.
    • Dragging
      • draggable : true
    • Drop zone
      • dropZone : true
    • Cursor
      • cursor : CSS string
      • useHandCursor : true

Pixel perfect hit-testing

This is an expensive process, should only be enabled on Game Objects that really need it.

"},{"location":"touchevents/#disable-interactive","title":"Disable interactive","text":"
  • Disable temporary
    gameObject.disableInteractive();\n// gameObject.disableInteractive(resetCursor);\n
    • resetCursor : Should the currently active Input cursor, if any, be reset to the default cursor?
  • Remove interaction
    gameObject.removeInteractive();\n// gameObject.removeInteractive(resetCursor);\n
    • resetCursor : Should the currently active Input cursor, if any, be reset to the default cursor?
"},{"location":"touchevents/#top-only","title":"Top only","text":"

When set to true this Input Plugin will emulate DOM behavior by only emitting events from the top-most Game Objects in the Display List. If set to false it will emit events from all Game Objects below a Pointer, not just the top one.

  • Get
    var topOnly = scene.input.topOnly;\n
  • Set
    scene.input.topOnly = topOnly;\nscene.input.setTopOnly(topOnly);\n

Each scene can has its own scene.input.topOnly setting.

"},{"location":"touchevents/#touch-events","title":"Touch events","text":"

Trigger these events from top scene to bottom scene.

  1. Events on touched Game object
    gameObject.on('pointerdown', function(pointer, localX, localY, event){ /* ... */ }, scope);\ngameObject.on('pointerup', function(pointer, localX, localY, event){ /* ... */ }, scope);\ngameObject.on('pointermove', function(pointer, localX, localY, event){ /* ... */ }, scope);\ngameObject.on('pointerover', function(pointer, localX, localY, event){ /* ... */ }, scope);\ngameObject.on('pointerout', function(pointer, event){ /* ... */ }, scope);\n
    • Cancel remaining touched events
      function(pointer, localX, localY, event) {\nevent.stopPropagation();\n}\n
  2. Event on input plugin for each touched Game object
    scene.input.on('gameobjectdown', function(pointer, gameObject, event){ /* ... */ }, scope);\nscene.input.on('gameobjectup', function(pointer, gameObject, event){ /* ... */ }, scope);\nscene.input.on('gameobjectmove', function(pointer, gameObject, event){ /* ... */ }, scope);\nscene.input.on('gameobjectover', function(pointer, gameObject, event){ /* ... */ }, scope);\nscene.input.on('gameobjectout', function(pointer, gameObject, event){ /* ... */ }, scope);\n
    • Cancel remaining touched events
      function(pointer, gameObject, event) {\nevent.stopPropagation();\n}\n
  3. Events to get all touched Game Objects
    scene.input.on('pointerdown', function(pointer, currentlyOver){ /* ... */ }, scope);\nscene.input.on('pointerdownoutside', function(pointer){ /* ... */ }, scope);\nscene.input.on('pointerup', function(pointer, currentlyOver){ /* ... */ }, scope);\nscene.input.on('pointerupoutside', function(pointer){ /* ... */ }, scope);\nscene.input.on('pointermove', function(pointer, currentlyOver){ /* ... */ }, scope);\nscene.input.on('pointerover', function(pointer, justOver){ /* ... */ }, scope);\nscene.input.on('pointerout', function(pointer, justOut){ /* ... */ }, scope);\nscene.input.on('gameout', function(timeStamp, domEvent){ /* ... */ }, scope);\nscene.input.on('gameover', function(timeStamp, domEvent){ /* ... */ }, scope);\n
    • Check pointer.camera in multiple-cameras scene.
"},{"location":"touchevents/#game-canvas","title":"Game canvas","text":"
scene.input.on('gameout', function(timeStamp, event){ /* ... */ }, scope);\nscene.input.on('gameover', function(timeStamp, event){ /* ... */ }, scope);\n
"},{"location":"touchevents/#dragging","title":"Dragging","text":""},{"location":"touchevents/#enable-dragging","title":"Enable dragging","text":"
  • Enable dragging when registering interactive
    gameObject.setInteractive({ draggable: true });\n
  • Enable dragging and add it to dragging detecting list after registered interactive
    scene.input.setDraggable(gameObject);\n
  • Enable dragging
    gameObject.input.draggable = true;\n
"},{"location":"touchevents/#disable-dragging","title":"Disable dragging","text":"
  • Remove Game Object from dragging detecting list
    scene.input.setDraggable(gameObject, false);\n
  • Disable dragging but keep it in dragging detecting list
    gameObject.input.draggable = false;\n
"},{"location":"touchevents/#dragging-events","title":"Dragging events","text":"
gameObject.on('dragstart', function(pointer, dragX, dragY){ /* ... */ }, scope);\ngameObject.on('drag', function(pointer, dragX, dragY){ /* ... */ }, scope);\ngameObject.on('dragend', function(pointer, dragX, dragY, dropped){ /* ... */ }, scope);\n
scene.input.on('dragstart', function(pointer, gameObject){ /* ... */ }, scope);\nscene.input.on('drag', function(pointer, gameObject, dragX, dragY){ /* ... */ }, scope);\nscene.input.on('dragend', function(pointer, gameObject, dropped){ /* ... */ }, scope);\n
  • dropped : 'dragend' and also 'drop'.
"},{"location":"touchevents/#dragging-properties","title":"Dragging properties","text":"
scene.input.dragDistanceThreshold = 16;\nscene.input.dragTimeThreshold = 500;\n
"},{"location":"touchevents/#drop-zone","title":"Drop zone","text":""},{"location":"touchevents/#enable-drop-zone","title":"Enable drop zone","text":"
  • Enable dropping when registering interactive
    gameObject.setInteractive({ dropZone: true });\n
  • Enable dropping after registered interactive
    gameObject.input.dropZone = true;\n
"},{"location":"touchevents/#disable-drop-zone","title":"Disable drop zone","text":"
gameObject.input.dropZone = false;\n
"},{"location":"touchevents/#dropping-events","title":"Dropping events","text":"
gameObject.on('drop', function(pointer, target){ /* ... */ }, scope);\n\ngameObject.on('dragenter', function(pointer, target){ /* ... */ }, scope);\ngameObject.on('dragover', function(pointer, target){ /* ... */ }, scope);\ngameObject.on('dragleave', function(pointer, target){ /* ... */ }, scope);\n
scene.input.on('drop', function(pointer, gameObject, target){ /* ... */ }, scope);\n\nscene.input.on('dragenter', function(pointer, gameObject, target){ /* ... */ }, scope);\nscene.input.on('dragover', function(pointer, gameObject, target){ /* ... */ }, scope);\nscene.input.on('dragleave', function(pointer, gameObject, target){ /* ... */ }, scope);\n
"},{"location":"touchevents/#force-state-of-pointer","title":"Force state of pointer","text":"
  • Down state
    scene.input.forceDownState(pointer, gameObject);\n
    • Emit 'pointerdown' event from game object.
    • Emit 'gameobjectdown' event from scene.input.
  • Up state
    scene.input.forceUpState(pointer, gameObject);\n
    • Emit 'pointerup' event from game object.
    • Emit 'gameobjectup' event from scene.input.
  • Over state
    scene.input.forceOverState(pointer, gameObject);\n
    • Emit 'pointerover' event from game object.
    • Emit 'gameobjectover' event from scene.input.
  • Out state
    scene.input.forceOutState(pointer, gameObject);\n
    • Emit 'pointeroutr' event from game object.
    • Emit 'gameobjectout' event from scene.input.
"},{"location":"touchevents/#first-event-of-all","title":"First event of all","text":"
scene.input.on('preupdate', function() { /* ... */ }, scope);\n
"},{"location":"touchevents/#single-touch","title":"Single touch","text":""},{"location":"touchevents/#pointer","title":"Pointer","text":"
var pointer = scene.input.activePointer;\n
"},{"location":"touchevents/#multi-touch","title":"Multi-touch","text":""},{"location":"touchevents/#amount-of-active-pointers","title":"Amount of active pointers","text":"

Set amount of active pointers in game configuration

var config = {\n// ...\ninput: {\nactivePointers: 1,\n// ...\n}\n};\nvar game = new Phaser.Game(config);\n

Or add pointers in run-time.

scene.input.addPointer(num);  // total points = num + 1\n
"},{"location":"touchevents/#pointers","title":"Pointers","text":"
  • pointer 1 ~ 10
    var pointer = scene.input.pointer1;\n// ...\nvar pointer = scene.input.pointer10;\n
  • pointer n
    var pointer = scene.input.manager.pointers[n];\n
  • Amount of total pointers
    var amount = scene.input.manager.pointersTotal;\n
    • 1 in desktop
    • 2 in touch device. (0 for mouse, 1 for 1 touch pointer)
"},{"location":"touchevents/#pointer_1","title":"Pointer","text":"
  • Position
    • Current touching
      • Position in screen : pointer.x , pointer.y
      • Position in camera :
        • Single camera :
          var worldX = pointer.worldX;\nvar worldY = pointer.worldY;\n
        • Multiple cameras :
          var worldXY = pointer.positionToCamera(camera);  // worldXY: {x, y}\n// var worldXY = pointer.positionToCamera(camera, worldXY);\nvar worldX = worldXY.x;\nvar worldY = worldXY.y;\n
        • Camera
          var camera = pointer.camera;\n
      • Position of previous moving : pointer.prevPosition.x , pointer.prevPosition.y
        • Updating when pointer-down, potiner-move, or pointer-up.
      • Interpolated position :
        var points = pointer.getInterpolatedPosition(step);\n// var out = pointer.getInterpolatedPosition(step, out);\n
    • Drag
      • Touching start : pointer.downX, pointer.downY
      • Touching end : pointer.upX, pointer.upY
      • Drag distance between pointer-down to latest pointer : pointer.getDistance()
        • Horizontal drag distance : pointer.getDistanceX()
        • Vertical drag distance : pointer.getDistanceY()
      • Drag angle : pointer.getAngle()
  • Time
    • Touching start : pointer.downTime
    • Touching end : pointer.upTime
    • Drag : pointer.getDuration()
  • Touch state
    • Is touching/any button down : pointer.isDown
    • Is primary button down : pointer.primaryDown
  • Button state : pointer.button
    • On Touch devices the value is always 0.
  • Button down
    • No button down : pointer.noButtonDown()
    • Is primary (left) button down : pointer.leftButtonDown()
    • Is secondary (right) button down : pointer.rightButtonDown()
    • Is middle (mouse wheel) button down : pointer.middleButtonDown()
    • Is back button down : pointer.backButtonDown()
    • Is forward button down : pointer.forwardButtonDown()
  • Button released
    • Is primary (left) button released : pointer.leftButtonReleased()
    • Is secondary (right) button released : pointer.rightButtonReleased()
    • Is middle (mouse wheel) button released : pointer.middleButtonReleased()
    • Is back button released : pointer.backButtonReleased()
    • Is forward button released : pointer.forwardButtonReleased()
  • Index in scene.input.manager.pointers : pointer.id
  • Motion
    • Angle: pointer.angle
    • Distance: pointer.distance
    • Velocity: pointer.velocity
      • pointer.velocity.x, `pointer.velocity.y
"},{"location":"touchevents/#input-object","title":"Input object","text":"
  • gameObject.input : Game object's input object.
  • gameObject.input.localX, gameObject.input.localY : Pointer to local position of texture.
  • gameObject.input.dragStartX, gameObject.input.dragStartY : The x/y coordinate of the Game Object that owns this Interactive Object when the drag started.
  • gameObject.input.dragStartXGlobal, gameObject.input.dragStartYGlobal : The x/y coordinate that the Pointer started dragging this Interactive Object from.
  • gameObject.input.dragX, gameObject.input.dragY : The x/y coordinate that this Interactive Object is currently being dragged to.
"},{"location":"touchevents/#smooth","title":"Smooth","text":"

Get touch position from interpolation of previous touch position and current touch position.

Touch-position = (current-touch-position * smooth-factor) + (previous-touch-position * (1 - smooth-factor))\n
  1. Set smooth factor. In game configuration
    var config = {\n// ....\ninput: {\nsmoothFactor: 0\n}\n}\n
  2. Get touch position
    var x = pointer.x;\nvar y = pointer.y;\nvar worldX = pointer.worldX;\nvar worldY = pointer.worldY;\n
"},{"location":"touchevents/#debug","title":"Debug","text":"
  • Enable, draw shape of (shape) hit area.
    scene.input.enableDebug(gameObject);\n// scene.input.enableDebug(gameObject, color);\n
  • Disable
    scene.input.removeDebug(gameObject);\n
  • Get debug shape game object
    var shape = gameObject.input.hitAreaDebug;\n
"},{"location":"touchevents/#poll-rate","title":"Poll rate","text":"
  • Poll when touches moved, or updated. Default behavior.
    scene.input.setPollOnMove();\n
  • Poll every tick.
    scene.input.setPollAlways();\n
  • Set poll rate.
    scene.input.setPollRate(rate);\n
"},{"location":"toucheventstop/","title":"Touch event stop","text":""},{"location":"toucheventstop/#introduction","title":"Introduction","text":"

Stop touch events propagation.

  • Author: Rex
  • Behavior of game object
"},{"location":"toucheventstop/#live-demos","title":"Live demos","text":"
  • Stop touch events
"},{"location":"toucheventstop/#usage","title":"Usage","text":"

Sample code

"},{"location":"toucheventstop/#install-plugin","title":"Install plugin","text":""},{"location":"toucheventstop/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextoucheventstopplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextoucheventstopplugin.min.js', true);\n
  • Add touch-event-stop behavior
    var touchEventStop = scene.plugins.get('rextoucheventstopplugin').add(gameObject, config);\n
"},{"location":"toucheventstop/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TouchEventStopPlugin from 'phaser3-rex-plugins/plugins/toucheventstop-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTouchEventStop',\nplugin: TouchEventStopPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add touch-event-stop behavior
    var touchEventStop = scene.plugins.get('rexTouchEventStop').add(gameObject, config);\n
"},{"location":"toucheventstop/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import TouchEventStop from 'phaser3-rex-plugins/plugins/toucheventstop.js';\n
  • Add touch-event-stop behavior
    var touchEventStop = newe TouchEventStop(gameObject, config);\n
"},{"location":"toucheventstop/#create-instance","title":"Create instance","text":"
var touchEventStop = scene.plugins.get('rexTouchEventStop').add(gameObject, {\n// hitAreaMode: 0,    // 0|1|'default'|'fullWindow'\n// enable: true\n});\n
  • hitAreaMode : Mode of hit-area
    • 0, or 'default' : Set hit-area to size of game object, only touch events on this game object will be stopped..
    • 1, or 'fullWindow' : Set hit-area to whole window, all touch events will be stopped.
  • enable : Set false to disable touch-event-stop behavior.
"},{"location":"toucheventstop/#enable","title":"Enable","text":"
  • Get
    var enable = touchEventStop.enable;  // enable: true, or false\n
  • Set
    touchEventStop.setEnable(enable);  // enable: true, or false\n// touchEventStop.enable = enable;\n
  • Toggle
    touchEventStop.toggleEnable();\n
"},{"location":"touchstate/","title":"Touch state","text":""},{"location":"touchstate/#introduction","title":"Introduction","text":"

Store current touch input properties.

  • Author: Rex
  • Behavior of game object
"},{"location":"touchstate/#usage","title":"Usage","text":"

Sample code

"},{"location":"touchstate/#install-plugin","title":"Install plugin","text":""},{"location":"touchstate/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextouchstateplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextouchstateplugin.min.js', true);\n
  • Add touch-state behavior
    var touchState = scene.plugins.get('rextouchstateplugin').add(gameObject, config);\n
"},{"location":"touchstate/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TouchStatePlugin from 'phaser3-rex-plugins/plugins/touchstate-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTouchState',\nplugin: TouchStatePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add touch-state behavior
    var touchState = scene.plugins.get('rexTouchState').add(gameObject, config);\n
"},{"location":"touchstate/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TouchState from 'phaser3-rex-plugins/plugins/touchstate.js';\n
  • Add touch-state behavior
    var touchState = new TouchState(gameObject, config);\n
"},{"location":"touchstate/#create-instance","title":"Create instance","text":"
var touchState = scene.plugins.get('rexTouchState').add(gameObject, {\n// enable: true,\n});\n
  • enable : Can touch.
"},{"location":"touchstate/#properties","title":"Properties","text":"
  • Is pointer down, is pointer up
    var isDown = touchState.isDown;\nvar isUp = touchState.isUp;\n
  • Is in touching
    var isInTouching = touchState.isInTouching;\n
  • Pointer in local position
    var localX = touchState.localX;\nvar localY = touchState.localY;\n
  • Drag speed
    var speed = touchState.speed;\nvar speedX =  touchState.speedX;\nvar speedY =  touchState.speedY;\n
    var dx = touchState.dx;\nvar dy = touchState.dy;\nvar dt = touchState.dt;    
"},{"location":"touchstate/#events","title":"Events","text":"
  • Touch start (pointer down)
    touchState.on('touchstart', function (touchState, gameObject, pointer, localX, localY, event) {\n// ...\n}, scope);\n
  • Touch end (pointer up)
    touchState.on('touchend', function (touchState, gameObject, pointer) {\n// ...\n}, scope);\n
  • Touch move (pointer move)
    touchState.on('touchmove', function (touchState, gameObject, pointer, localX, localY, event) {\n// ...\n}, scope);\n
"},{"location":"touchstate/#enable","title":"Enable","text":"
  • Get
    var enabled = touchState.enable;  // enabled: true, or false\n
  • Set
    touchState.setEnable(enabled);  // enabled: true, or false\n// touchState.enable = enabled;\n
  • Toggle
    touchState.toggleEnable();\n
"},{"location":"transitionimage/","title":"Transition image","text":""},{"location":"transitionimage/#introduction","title":"Introduction","text":"

Transit texture to another one. A containerLite game object with 2 image game objects.

  • Author: Rex
  • Game object
"},{"location":"transitionimage/#live-demos","title":"Live demos","text":"
  • Ease property of current/next image
    • Cross-fade
    • Scale
    • Slide
  • Apply shader effect to current/next image, then ease property this shader effect.
    • Split
    • Dissolve
  • Grid cut current/next image to cell images, then ease property of cell images
    • Grid cut
    • 3 columns
  • Morph custom mask game object
    • Pie mask
  • Transition modes
"},{"location":"transitionimage/#usage","title":"Usage","text":"

Sample code

"},{"location":"transitionimage/#install-plugin","title":"Install plugin","text":""},{"location":"transitionimage/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextransitionimageplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextransitionimageplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexTransitionImage(x, y, texture, frame, config);\n
"},{"location":"transitionimage/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TransitionImagePlugin from 'phaser3-rex-plugins/plugins/transitionimage-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTransitionImagePlugin',\nplugin: TransitionImagePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexTransitionImage(x, y, texture, frame, config);\n
"},{"location":"transitionimage/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TransitionImage from 'phaser3-rex-plugins/plugins/transitionimage.js';\n
  • Add image object
    var image = new TransitionImage(scene, x, y, texture, frame, config);\nscene.add.existing(image);\n
"},{"location":"transitionimage/#create-instance","title":"Create instance","text":"

var image = scene.add.rexTransitionImage(x, y, texture, frame, {\n// dir: 0,\n// onStart: function(parent, currentImage, nextImage, t) { },\n// onStartScope: undefined,\n// onProgress: function(parent, currentImage, nextImage, t) { },\n// onProgressScope: undefined,\n// onComplete: function(parent, currentImage, nextImage, t) { },\n// onCompleteScope: undefined,    \n// duration: 1000,\n// ease: 'Linear',\n// mask: undefined,\n\n// width: undefined, height: undefined,\n});\n
or

var image = scene.add.rexTransitionImage(x, y, texture, frame, {\n// x: 0,\n// y: 0,\n// key: \n// frame: \n// dir: 0,\n// onStart: function(parent, currentImage, nextImage, t) { },\n// onStartScope: undefined,\n// onProgress: function(parent, currentImage, nextImage, t) { },\n// onProgressScope: undefined,\n// onComplete: function(parent, currentImage, nextImage, t) { },\n// onCompleteScope: undefined,    \n// duration: 1000,\n// ease: 'Linear',\n// mask: undefined,\n\n// width: undefined, height: undefined,\n});\n
  • dir : Transition direction.
    • 0, or 'out' : Transit current texture/image out.
    • 1, or 'in' : Transit next texture/image in.
  • onStart, onStartScope : Callback and scope of transition-start. See Set transition callbacks
  • onProgress, onProgressScope : Callback and scope of transition-progress. See Set transition callbacks
  • onComplete, onCompleteScope : Callback and scope of transition-complete. See Set transition callbacks
  • duration : Duration of transition.
  • ease : Ease function of transition-progress.
  • mask : Mask game object.
    • true : Default graphics game object.
    • Any shape game object, or custom shape, custom progress game object.
  • width, height : Scale images to fit this size (widthxheight).
    • undefined : Don't scale images.

If onStart, onProgress and onComplete are all undefined, it will use cross-fade as default transition callbacks.

Add transitionimage from JSON

var image = scene.make.rexTransitionImage({\nx: 0,\ny: 0,\nkey: null,\nframe: null,\n\n// dir: 0,\n// onStart: function(parent, currentImage, nextImage, t) { },\n// onStartScope: undefined,\n// onProgress: function(parent, currentImage, nextImage, t) { },\n// onProgressScope: undefined,\n// onComplete: function(parent, currentImage, nextImage, t) { },\n// onCompleteScope: undefined,\n// duration: 1000,\n// ease: 'Linear',\n// mask: undefined,\n\n// width: undefined, height: undefined,\n\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
"},{"location":"transitionimage/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTransitionImage extends TransitionImage {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var transitionimage = new MyTransitionImage(scene, x, y, texture, frame, config);\n
"},{"location":"transitionimage/#transit","title":"Transit","text":"
image\n// .setTransitionDirection(dir)\n// .setTransitionStartCallback(onStart, onStartScope)\n// .setTransitionProgressCallback(onProgress, onProgressScope)\n// .setTransitionCompleteCallback(onComplete, onCompleteScope)\n// .setDuration(duration)\n// .setEaseFunction(ease)\n// .setMaskEnable(enable)\n.transit(texture, frame)\n

or

image.transit({\nkey: undefined,\n// frame: undefined,\n// dir: 0,\n// onStart: function(parent, currentImage, nextImage, t) { },\n// onStartScope: undefined,\n// onProgress: function(parent, currentImage, nextImage, t) { },\n// onProgressScope: undefined,\n// onComplete: function(parent, currentImage, nextImage, t) { },\n// onCompleteScope: undefined,\n// duration: 1000,\n// ease: 'Linear',\n// mask: undefined,\n})\n
  • mask : Mask game object.
    • true : Default graphics game object. Also apply this mask to current and next textures/images
    • Any shape game object, or custom shape, custom progress game object.
      • Apply mask to current texture :
        image.setCurrentImageMaskEnable();\n// image.setCurrentImageMaskEnable(enable, invertAlpha);\n
      • Apply mask to next texture :
        image.setNextImageMaskEnable();\n// image.setNextImageMaskEnable(enable, invertAlpha);\n
      • Apply mask to both current and next trextures :
        image.setMaskEnable();\n// image.setMaskEnable(enable, invertAlpha);\n

Fire 'complete' event when transition completed.

"},{"location":"transitionimage/#register-transtion-mode","title":"Register transtion mode","text":"
  • Register transtion mode
    image.addTransitionMode(modeName, {\n// dir: 0,\n// onStart: function(parent, currentImage, nextImage, t) { },\n// onStartScope: undefined,\n// onProgress: function(parent, currentImage, nextImage, t) { },\n// onProgressScope: undefined,\n// onComplete: function(parent, currentImage, nextImage, t) { },\n// onCompleteScope: undefined,\n// duration: 1000,\n// ease: 'Linear',\n// mask: undefined,\n});\n
  • Trnasit by transition mode
    image.transit(texture, frame, modeName);\n// image.transit(texture, frame, modeNames);\n
    or
    image.transit({\nkey: undefined,\n// frame: undefined,\n\nmode: modeName, // or modeName\n// dir: 0,\n// onStart: function(parent, currentImage, nextImage, t) { },\n// onStartScope: undefined,\n// onProgress: function(parent, currentImage, nextImage, t) { },\n// onProgressScope: undefined,\n// onComplete: function(parent, currentImage, nextImage, t) { },\n// onCompleteScope: undefined,\n// duration: 1000,\n// ease: 'Linear',\n// mask: undefined,\n})\n
    • Can override configuration of transition mode
    • modeName : A string, or an array of string to pick a random mode.
  • Current transition mode
    var modeName = image.currentTransitionMode;\n
"},{"location":"transitionimage/#current-texture","title":"Current texture","text":"
var textureKey = image.texture.key;\nvar frameName = image.frame.name;\n
"},{"location":"transitionimage/#transition-callbacks","title":"Transition callbacks","text":"
  • Set transition direction
    image.setTransitionDirection(dir);\n
    • 0, or 'out' : Transit current texture out.
    • 1, or 'in' : Transit next texture in.
  • Set transition-start callback
    image.setTransitionStartCallback(onStart, onStartScope)\n
    • onStart
      function(parent, currentImage, nextImage, t) { }\n
      • parent : Transition image game object, extends from ContainerLite
      • currentImage : Image game object to display current texture.
      • nextImage : Image game object to display next texture.
      • t : Progress percentage. It is 0 in this case.
  • Set transition-progress callback
    image.setTransitionProgressCallback(onProgress, onProgressScope)\n
    • onProgress
      function(parent, currentImage, nextImage, t) { // parent.setChildLocalAlpha(currentImage, 1 - t);\n// parent.setChildLocalScale(currentImage, 1 - t);\n// parent.setChildLocalPosition(currentImage, x, 0);\n}\n
      • parent : Transition image game object, extends from ContainerLite
      • currentImage : Image game object to display current texture.
        • Set alpha of currentImage, or nextImage by parent.setChildLocalAlpha(currentImage, alpha).
        • Set scale of currentImage, or nextImage by parent.setChildLocalScale(currentImage, scale).
        • Set position of currentImage, or nextImage by parent.setChildLocalScale(currentImage, x, y).
      • nextImage : Image game object to display next texture.
      • t : Progress percentage. 0~1.
  • Set transition-complete callback
    image.setTransitionCompleteCallback(onComplete, onCompleteScope)\n
    • onComplete
      function(parent, currentImage, nextImage, t) { }\n
      • parent : Transition image game object, extends from ContainerLite
      • currentImage : Image game object to display current texture.
      • nextImage : Image game object to display next texture.
      • t : Progress percentage. It is 1 in this case.
"},{"location":"transitionimage/#transition-duration","title":"Transition duration","text":"
  • Set
    image.setDuration(duration);\n
  • Get
    var duration = image.duration;\n
"},{"location":"transitionimage/#ease-function","title":"Ease function","text":"
  • Set
    image.setEaseFunction(ease);\n
    • ease : Ease function of transition-progress.
  • Get
    var ease = image.easeFunction;\n
"},{"location":"transitionimage/#mask","title":"Mask","text":"
  • Apply mask to current texture :
    image.setCurrentImageMaskEnable();\n// image.setCurrentImageMaskEnable(enable, invertAlpha);\n
  • Apply mask to next texture :
    image.setNextImageMaskEnable();\n// image.setNextImageMaskEnable(enable, invertAlpha);\n
  • Apply mask to both current and next trextures :
    image.setMaskEnable();\n// image.setMaskEnable(enable, invertAlpha);\n
  • Assign default mask game object
    image.setMaskGameObject(true);\n
  • Assign custom mask game object
    image.setMaskGameObject(maskGameObject);\n
    • maskGameObject : A graphics game object, or any shape game objects, custom-progress shape game object
"},{"location":"transitionimage/#grid-cut","title":"Grid cut","text":"

Grid cut texture to cells.

  • Grid cut current texture :
    var cellImageGameObjects = image.gridCutCurrentImage(columns, rows);\n
    • cellImageGameObjects : Array of cell game objects.
  • Grid cut next texture :
    var cellImageGameObjects = image.gridCutNextImage(columns, rows);\n
    • cellImageGameObjects : Array of cell game objects.
  • Get cut cell image game objects, after cutting.
    var cellImageGameObjects = image.getCellImages();\n
  • Apply mask to cell images
    image.setCellImagesMaskEnable();\n// image.setCellImagesMaskEnable(enable, invertAlpha);\n

Cut cell image game objects will be set to invisible after transition complete.

"},{"location":"transitionimage/#pauseresume","title":"Pause/Resume","text":"
image.pause();\n
image.resume();\n
"},{"location":"transitionimage/#stop","title":"Stop","text":"
image.stop();\n

Also will fire 'complete' event.

"},{"location":"transitionimage/#events","title":"Events","text":"
  • On complete
    image.on('complete', function(){\n})\n
"},{"location":"transitionimage/#flip","title":"Flip","text":"

Apply flipX, flipY to both current and next trextures.

  • Flip
    image.flipX(value);\nimage.flipY(value);\nimage.flip(x, y);\n
  • Toggle
    image.toggleFlipX();\nimage.toggleFlipY();\n
"},{"location":"transitionimage/#tint","title":"Tint","text":"

Apply tint to both current and next trextures.

image.setTint(value);\n
"},{"location":"transitionimage/#use-cases","title":"Use cases","text":"
  • Ease property of current/next image.
    • Scale
    • Slide, apply mask to current/next image.
  • Apply shader effect to current/next image, then ease property this shader effect.
    • Dissolve
    • Split
  • Grid cut current/next image to cell images, then ease property of cell images
    • Grid cut
    • Three-columns, apply mask to cell images.
  • Morph custom mask game object
    • Pie-mask, mask current/next image by a custom-progress game object.
"},{"location":"transitionimage/#internal-image-game-object","title":"Internal image game object","text":"
  • Current, next image game object
    var curentImageGO = image.currentImage;\nvar nextImageGO = image.nextImage;\n
  • Front, back image game object
    var frontImageGO = image.frontImage;\nvar backImageGO = image.backImage;\n
"},{"location":"transitionimage/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"transitionimage/#shader-effects","title":"Shader effects","text":"

Internal image game objects (image.currentImage, image.nextImage) support preFX and postFX effects

"},{"location":"transitionimagepack/","title":"Transition image pack","text":""},{"location":"transitionimagepack/#introduction","title":"Introduction","text":"

Transit texture to another one, with some pre-build effects, extended from TransitionImage

  • Author: Rex
  • Game object
"},{"location":"transitionimagepack/#live-demos","title":"Live demos","text":"
  • Effect list
  • Slide modes
  • Fade modes
  • Mask modes
  • Shader effect modes
"},{"location":"transitionimagepack/#usage","title":"Usage","text":"

Sample code

"},{"location":"transitionimagepack/#install-plugin","title":"Install plugin","text":""},{"location":"transitionimagepack/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rextransitionimagepackplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rextransitionimagepackplugin.min.js', true);\n
  • Add image object
    var image = scene.add.rexTransitionImagePack(x, y, texture, frame, config);\n
"},{"location":"transitionimagepack/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import TransitionImagePackPlugin from 'phaser3-rex-plugins/templates/transitionimagepack/transitionimagepack-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexTransitionImagePackPlugin',\nplugin: TransitionImagePackPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add image object
    var image = scene.add.rexTransitionImagePack(x, y, texture, frame, config);\n
"},{"location":"transitionimagepack/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import TransitionImagePack from 'phaser3-rex-plugins/templates/transitionimagepack/TransitionImagePack.js';\n
  • Add image object
    var image = new TransitionImagePack(scene, x, y, texture, frame, config);\nscene.add.existing(image);\n
"},{"location":"transitionimagepack/#create-instance","title":"Create instance","text":"

var image = scene.add.rexTransitionImagePack(x, y, texture, frame, {   // duration: 1000,\n// width: undefined, height: undefined,\n});\n
or

var image = scene.add.rexTransitionImagePack(x, y, texture, frame, {\n// x: 0,\n// y: 0,\n// key: \n// frame: \n// duration: 1000,\n// width: undefined, height: undefined,\n});\n
  • duration : Duration of transition.
  • width, height : Scale images to fit this size (widthxheight).
    • undefined : Don't scale images.

Add transitionimage from JSON

var image = scene.make.rexTransitionImagePack({\nx: 0,\ny: 0,\nkey: null,\nframe: null,\n\n// duration: 1000,\n// width: undefined, height: undefined,\n\n// origin: {x: 0.5, y: 0.5},\nadd: true\n});\n
"},{"location":"transitionimagepack/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTransitionImagePack extends TransitionImagePack {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var transitionimage = new MyTransitionImagePack(scene, x, y, texture, frame, config);\n
"},{"location":"transitionimagepack/#transit","title":"Transit","text":"
image\n// .setDuration(duration)\n// .setEaseFunction(ease)\n.transit(texture, frame, modeName)\n

or

image.transit({\nkey: undefined,\n// frame: undefined,\n// duration: 1000,\n// ease: 'Linear',\nmode: modeName\n})\n
  • duration : Override default duration setting.
  • ease : Override default ease setting.
  • mode : Pre-build effects
    • Fade effects :
      • 'fade' : Tint old image to black, then tint new image from black to origin color.
      • 'crossFade' : Ease alpha of old image from 1 to 0, and ease alpha of new image from 0 to 1 at the same time.
    • Slide effects : 'slideLeft', 'slideRight', 'slideUp', 'slideDown', 'slideAwayLeft', 'slideAwayRight', 'slideAwayUp', 'slideAwayDown', 'pushLeft', 'pushRight', 'pushUp', 'pushDown'.
    • Zoom(scale) effects : 'zoomOut', 'zoomIn', 'zoomInOut'.
    • Mask effects : 'wipeLeft', 'wipeRight', 'wipeUp', 'wipeDown', 'irisOut', 'irisIn', 'irisInOut', 'pieOut', 'pieIn', 'pieInOut', 'blinds', 'squares', 'diamonds', 'circles', 'curtain'.
    • Shader effects : 'pixellate', 'dissolve', 'revealLeft', 'revealRight', 'revealUp', 'revealDown'
"},{"location":"transitionimagepack/#current-texture","title":"Current texture","text":"
var textureKey = image.texture.key;\nvar frameName = image.frame.name;\n
"},{"location":"transitionimagepack/#transition-duration","title":"Transition duration","text":"
  • Set
    image.setDuration(duration);\n
  • Get
    var duration = image.duration;\n
"},{"location":"transitionimagepack/#ease-function","title":"Ease function","text":"
  • Set
    image.setEaseFunction(ease);\n
    • ease : Ease function of transition-progress.
  • Get
    var ease = image.easeFunction;\n
"},{"location":"transitionimagepack/#pauseresume","title":"Pause/Resume","text":"
image.pause();\n
image.resume();\n
"},{"location":"transitionimagepack/#stop","title":"Stop","text":"
image.stop();\n

Also will fire 'complete' event.

"},{"location":"transitionimagepack/#events","title":"Events","text":"
  • On complete
    image.on('complete', function(){\n})\n
"},{"location":"transitionimagepack/#flip","title":"Flip","text":"
  • Flip
    image.flipX(value);\nimage.flipY(value);\nimage.flip(x, y);\n
  • Toggle
    image.toggleFlipX();\nimage.toggleFlipY();\n
"},{"location":"transitionimagepack/#other-properties","title":"Other properties","text":"

See transition image object, game object

"},{"location":"tween/","title":"Tween","text":""},{"location":"tween/#introduction","title":"Introduction","text":"

Change properties by tween equations, built-in object of phaser.

  • Author: Richard Davey
"},{"location":"tween/#usage","title":"Usage","text":""},{"location":"tween/#create-tween-task","title":"Create tween task","text":"
var tween = scene.tweens.add({\ntargets: gameObject,\nx: 1,\n// x: '+=1',\n// x: '-=1',\n// x: '*=1',\n// x: '/=1',\n// x: 'random(0.25, 0.75)',\n// x: 'int(10, 100)',\n// x: [100, 300, 200, 600],\n// x: { from: 0, to: 1 },\n// x: { start: 0, to: 1 },  \n// x: { start: value0, from: value1, to: value2 },  \n// x: {\n//      getActive: function (target, key, value, targetIndex, totalTargets, tween) { return newValue; },\n//      getStart: function (target, key, value, targetIndex, totalTargets, tween) { return newValue; },\n//      getEnd: function (target, key, value, targetIndex, totalTargets, tween) { return newValue; }\n// },\nease: 'Linear',       // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\nrepeat: 0,            // -1: infinity\nyoyo: false,\n\n// interpolation: null,\n});\n
  • key: value2 : Tween to value2.
  • key: '+=deltaValue' : Tween to current value + deltaValue
    • Support these expressions : key: '+=deltaValue', key: '-=deltaValue', key: '*=deltaValue', key: '/=deltaValue'
  • key: 'random(10, 100)' : Tween to a random float value.
  • key: 'int(10, 100)' : Tween to a random int value.
  • key: [100, 300, 200, 600] : Use interpolation to determine the value.
  • key: { from: value1, to: value2 } : Set the property to value11 when tween started after delay, then tween to value2.
  • value1, value2 : A number, string, or callback(function(target, key, value, targetIndex, totalTargets, tween) { return newValue; })
  • key: { start: value0, to: value2 } : Set the property to value0 immediately, then tween to value2.
    • value1, value2 : A number, string, or callback(function(target, key, value, targetIndex, totalTargets, tween) { return newValue; })
  • key: { start: value0, from: value1, to: value2 } : Set the property to value0 immediately, then set to value1 when tween started after delay, then tween to value2.
    • value0, value1, value2 : A number, string, or callback(function(target, key, value, targetIndex, totalTargets, tween) { return newValue; })
  • key: function(target, key, value, targetIndex, totalTargets, tween) { return newValue; }
    • target :\u3000The tween target.
    • key : The target property.
    • value : The current value of the target property.
    • targetIndex : The index of the target within the Tween.
    • totalTargets : The total number of targets in this Tween.
    • tween : The Tween that invoked this callback.
  • key: { getActive:callback, getStart:callback, getEnd:callback}
    • callback : function(target, key, value, targetIndex, totalTargets, tween) { return newValue; }

or

var tween = scene.tweens.add({\ntargets: gameObject,\npaused: false,\ncallbackScope: tween,\n\n// timming/callback of each state\nonStart: function () {},\nonStartParams: [],\n\n// initial delay\ndelay: 0,  // function(target, targetKey, value, targetIndex, totalTargets, tween) { },\n\n// tween duration\nduration: 1000,\nease: 'Linear',\neaseParams: null,\n\nonActive: function () {},\nonUpdate: function (tween, target, key, current, previous, param) {},\nonUpdateParams: [],\n\n// delay between tween and yoyo\nhold: 0,\nyoyo: false,  // true to tween backward\nflipX: false,\nflipY: false,\nonYoyo: function (tween, target, key, current, previous, param) {},\nonYoyoParams: [],\n\n// repeat count (-1: infinite)\nrepeat: 0,\nonRepeat: function (tween, target, key, current, previous, param) {},\nonRepeatParams: [],\n// delay to next pass\nrepeatDelay: 0,\n\n// loop count (-1: infinite)\nloop: 0,\nonLoop: function () {},\nonLoopParams: [],\n// delay to next loop\nloopDelay: 0,\n\n// delay to onComplete callback\ncompleteDelay: 0,\nonComplete: function () {},\nonCompleteParams: [],\n// timming/callback of each state\n\nonStop: function () {}, onPause: function () {}, onResume: function () {}, // properties:\nx: '+=600',        // start from current value\ny: 500,\nrotation: ...\nangle: ...\nalpha: ...\n// ...\n\n// or\nprops: {\nx: { value: '+=600', duration: 3000, ease: 'Power2' },\ny: { value: '500', duration: 1500, ease: 'Bounce.easeOut' }\n},\n\n// or\nprops: {\nx: {\nduration: 400,\nyoyo: true,\nrepeat: 8,\nease: 'Sine.easeInOut',\nvalue: {\ngetActive: function (target, key, value, targetIndex, totalTargets, tween)\n{\nreturn value;\n},\ngetStart: function (target, key, value, targetIndex, totalTargets, tween)\n{\nreturn value + 30;\n},\ngetEnd: function (target, key, value, targetIndex, totalTargets, tween)\n{\ndestX -= 30;\nreturn destX;\n}\n}\n},\n....\n},\n\npersist: false,\n\ninterpolation: null,\ninterpolationData: null,\n\n});\n
  • targets : The targets the tween is updating.
  • delay : The time the tween will wait before it first starts
    • A number, for all targets
    • A callback function, built via stagger builder :
      • From 0 to endValue :
        • scene.tweens.stagger(endValue)
      • From startValue to endValue :
        • scene.tweens.stagger([startValue, endValue])
      • From 0 to endValue, with specific ease function :
        • scene.tweens.stagger(endValue, {ease: 'cubic.inout'})
      • From startValue to endValue, with specific ease function :
        • scene.tweens.stagger([startValue, endValue], {ease: 'cubic.inout'})
      • From 0 to endValue, with specific start index :
        • scene.tweens.stagger(endValue, {from: 'last'})
        • scene.tweens.stagger(endValue, {from: 'center'})
        • scene.tweens.stagger(endValue, {from: index})
      • From startValue to endValue, , with specific start index :
        • scene.tweens.stagger([startValue, endValue], {from: 'last'})
        • scene.tweens.stagger([startValue, endValue], {from: 'center'})
        • scene.tweens.stagger([startValue, endValue], {from: index})
      • From 0 to endValue, with specific ease function, with specific start index :
        • scene.tweens.stagger(endValue, {from: 'last', ease: 'cubic.inout'})
      • From startValue to endValue, with specific ease function , with specific start index :
        • scene.tweens.stagger([startValue, endValue], {from: 'last', ease: 'cubic.inout'})
      • Grid mode. From 0 to endValue.
        • scene.tweens.stagger(endValue, {grid: [gridWidth, gridHeight], })
        • scene.tweens.stagger(endValue, {grid: [gridWidth, gridHeight], from: 'center'})
        • scene.tweens.stagger(endValue, {grid: [gridWidth, gridHeight], from: 'center', ease: 'cubic.inout'})
      • Grid mode. From startValue to endValue.
        • scene.tweens.stagger([startValue, endValue], {grid: [gridWidth, gridHeight], })
        • scene.tweens.stagger([startValue, endValue], {grid: [gridWidth, gridHeight], from: 'center'})
        • scene.tweens.stagger([startValue, endValue], {grid: [gridWidth, gridHeight], from: 'center', ease: 'cubic.inout'})
  • duration : The duration of the tween
  • ease : The ease function used by the tween
  • easeParams : The parameters to go with the ease function (if any)
  • hold : The time the tween will pause before running a yoyo
  • repeat : The number of times the tween will repeat itself (a value of 1 means the tween will play twice, as it repeated once)
  • repeatDelay : The time the tween will pause for before starting a repeat. The tween holds in the start state.
  • yoyo : boolean - Does the tween reverse itself (yoyo) when it reaches the end?
  • flipX : flip X the GameObject on tween end
  • flipY : flip Y the GameObject on tween end
  • completeDelay : The time the tween will wait before the onComplete event is dispatched once it has completed
  • loop : -1 for an infinite loop
  • loopDelay
  • paused : Does the tween start in a paused state, or playing?
  • props : The properties being tweened by the tween
  • onActive : Tween becomes active within the Tween Manager.
    function(tween, target) { }\n
  • onStart : A tween starts.
    function(tween, targets) { }\n
  • onUpdate : Callback which fired when tween task updated
    function(tween, target, key, current, previous, param) { }\n
  • onComplete : Tween completes or is stopped.
    function(tween, targets) { }\n
  • onYoyo : A function to call each time the tween yoyos. Called once per property per target.
    function(tween, target, key, current, previous, param) { }\n
  • onLoop : A function to call each time the tween loops.
    function(tween, targets) { }\n
  • onRepeat : A function to call each time the tween repeats. Called once per property per target.
    function(tween, target, key, current, previous, param) { }\n
  • onStop : A function to call when the tween is stopped.
    function(tween, targets) { }\n
  • onPause : A function to call when the tween is paused.
    function(tween, targets) { }\n
  • onResume : A function to call when the tween is resumed after being paused.
    function(tween, targets) { }\n
  • persist : Will the Tween be automatically destroyed on completion, or retained for future playback?
  • interpolation : The interpolation function to use if the value given is an array of numbers.
    • 'linear', 'bezier', 'catmull' (or 'catmullrom')

Note

Tween task will not manipulate any property that begins with an underscore.

"},{"location":"tween/#ease-equations","title":"Ease equations","text":"
  • Power0 : Linear
  • Power1 : Quadratic.Out
  • Power2 : Cubic.Out
  • Power3 : Quartic.Out
  • Power4 : Quintic.Out
  • Linear
  • Quad : Quadratic.Out
  • Cubic : Cubic.Out
  • Quart : Quartic.Out
  • Quint : Quintic.Out
  • Sine : Sine.Out
  • Expo : Expo.Out
  • Circ : Circular.Out
  • Elastic : Elastic.Out
  • Back : Back.Out
  • Bounce : Bounce.Out
  • Stepped
  • Quad.easeIn
  • Cubic.easeIn
  • Quart.easeIn
  • Quint.easeIn
  • Sine.easeIn
  • Expo.easeIn
  • Circ.easeIn
  • Back.easeIn
  • Bounce.easeIn
  • Quad.easeOut
  • Cubic.easeOut
  • Quart.easeOut
  • Quint.easeOut
  • Sine.easeOut
  • Expo.easeOut
  • Circ.easeOut
  • Back.easeOut
  • Bounce.easeOut
  • Quad.easeInOut
  • Cubic.easeInOut
  • Quart.easeInOut
  • Quint.easeInOut
  • Sine.easeInOut
  • Expo.easeInOut
  • Circ.easeInOut
  • Back.easeInOut
  • Bounce.easeInOut

Demo

"},{"location":"tween/#pause-resume-task","title":"Pause / Resume task","text":"
tween.pause();\n
tween.resume();\n
"},{"location":"tween/#stop-task","title":"Stop task","text":"
tween.complete();\n
tween.stop();\n

Won't invoke onComplete callback ('complete' event)

"},{"location":"tween/#play-task","title":"Play task","text":"
tween.play();\n
"},{"location":"tween/#restart-task","title":"Restart task","text":"
tween.restart();\n
"},{"location":"tween/#seek","title":"Seek","text":"
tween.seek(amount);\n// tween.seek(amount, delta, emit);\n
  • amount : The number of milliseconds to seek into the Tween from the beginning.
  • delta : The size of each step when seeking through the Tween. Default value is 16.6 (1000/60)
  • emit : While seeking, should the Tween emit any of its events or callbacks? The default is false.
"},{"location":"tween/#remove-task","title":"Remove task","text":"

Removes this Tween from the TweenManager

tween.remove();\n
"},{"location":"tween/#destroy-task","title":"Destroy task","text":"

Free tween task from memory

tween.destroy();\n

Note

A Tween that has been destroyed cannot ever be played or used again.

"},{"location":"tween/#get-tweens","title":"Get tweens","text":"
  • Tweens of a target
    var tweens = scene.tweens.getTweensOf(target);\n// var tweens = scene.tweens.getTweensOf(target, includePending);\n
    • tweens : Array of tweens, or timelines.
    • includePending : Set true to search pending tweens.
  • All tweens
    var tweens = scene.tweens.getTweens();\n
"},{"location":"tween/#destroy-task-of-a-target","title":"Destroy task of a target","text":"
scene.tweens.killTweensOf(target);\n
  • target : The target to kill the tweens of. Provide an array to use multiple targets.
"},{"location":"tween/#time-scale","title":"Time-scale","text":"
tween.setTimeScale(v);\n// tween.timeScale = timescale;\n
var timeScale = tween.getTimeScale();\n// var timeScale = tween.timeScale;\n
"},{"location":"tween/#global-time-scale","title":"Global time-scale","text":"
var timeScale = scene.tweens.timeScale;\n
scene.tweens.timeScale = timescale;\n
"},{"location":"tween/#events","title":"Events","text":"
  • Tween becomes active within the Tween Manager.
    tween.on('active', function(tween, targets){\n\n}, scope);\n
  • Tween completes or is stopped.
    tween.on('complete', function(tween, targets){\n\n}, scope);\n
  • A tween loops, after any loop delay expires.
    tween.on('loop', function(tween, targets){\n\n}, scope);\n
  • A tween property repeats, after any repeat delay expires.
    tween.on('repeat', function(tween, key, target){\n\n}, scope);\n
  • A tween starts.
    tween.on('start', function(tween, targets){\n\n}, scope);\n
  • A tween property updates.
    tween.on('update', function(tween, key, target, current, previous){\n\n}, scope);\n
    • tween : A reference to the Tween instance that emitted the event.
    • key : The property that was updated, i.e. x or scale.
    • target : The target object that was updated. Usually a Game Object, but can be of any type.
    • current : The current value of the property that was tweened.
    • previous : The previous value of the property that was tweened, prior to this update.
  • A tween property pause.
    tween.on('pause', function(tween, key, target){\n\n}, scope);\n
  • A tween property resume.
    tween.on('resume', function(tween, key, target){\n\n}, scope);\n
  • A tween property yoyos.
    tween.on('yoyo', function(tween, key, target){\n\n}, scope);\n
  • A tween stopped.
    tween.on('stop', function(tween, targets){\n\n}, scope);\n
"},{"location":"tween/#set-callbacks","title":"Set callbacks","text":"
tween.setCallback(type, callback, param);\n
  • type :
    • 'onActive' : When the Tween is first created it moves to an 'active' state when added to the Tween Manager. 'Active' does not mean 'playing'.
    • 'onStart' : When the Tween starts playing after a delayed or paused state. This will happen at the same time as onActive if the tween has no delay and isn't paused.
    • 'onLoop' : When a Tween loops, if it has been set to do so. This happens after the loopDelay expires, if set.
    • 'onComplete' : When the Tween finishes playback fully. Never invoked if the Tween is set to repeat infinitely.
    • 'onStop' : Invoked only if the Tween.stop method is called.
    • 'onPause' : Invoked only if the Tween.pause method is called. Not invoked if the Tween Manager is paused.
    • 'onResume' : Invoked only if the Tween.resume method is called. Not invoked if the Tween Manager is resumed.
    • 'onYoyo' : When a TweenData starts a yoyo. This happens after the hold delay expires, if set.
    • 'onRepeat' : When a TweenData repeats playback. This happens after the repeatDelay expires, if set.
    • 'onUpdate' : When a TweenData updates a property on a source target during playback.
  • callback :
    • 'onRepeat', 'onUpdate', 'onYoyo'
      function(tween, targets, key, current, previous, param) {\n\n}\n
    • 'onActive', 'onLoop', 'onPause', 'onResume', 'onComplete', 'onStart', 'onStop',
      function(tween, targets, param) {\n\n}\n
"},{"location":"tween/#state","title":"State","text":"
  • Is playing
    var isPlaying = tween.isPlaying();\n
  • Is paused
    var isPaused = tween.isPaused();\n
  • Is actively and not just in a delayed state
    var hasStarted = tween.hasStarted;\n
"},{"location":"tween/#custom-ease-function","title":"Custom ease function","text":"
var tween = scene.tweens.add({\ntargets: gameObject,\n// ...\nease: function (t) {  // t: 0~1\nreturn value;     // value: 0~1\n},\n// ...\n});\n
"},{"location":"tween/#has-target","title":"Has target","text":"
var hasTarget = tween.hasTarget(gameObject);\n
"},{"location":"tween/#tween-value","title":"Tween value","text":"
  • Create tween task
    var tween = scene.tweens.addCounter({\nfrom: 0,\nto: 1,\nease: 'Linear',       // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\nrepeat: 0,            // -1: infinity\nyoyo: false,\nonUpdate(tween, targets, key, current, previous, param) {\n// var value = current;\n// var value = tween.getValue();\n}\n});\n
    • More config parameters...
  • Get value
    var value = tween.getValue();\n
"},{"location":"tween/#chain","title":"Chain","text":""},{"location":"tween/#create-chain","title":"Create chain","text":"
var chain = scene.tweens.chain({\ntargets: null,\ntweens: [\n{\n// targets: gameObject,\nalpha: 1,            ease: 'Linear',       // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\nrepeat: 0,            // -1: infinity\nyoyo: false\n},        // ...\n],\n\ndelay: 0,\ncompleteDelay: 0,\nloop: 0,  // repeat: 0,\nrepeatDelay: 0,\npaused: false,\npersist: true,\n// callbackScope: this,\n})\n
  • targets, or tweenConfig.targets
  • tweens : Array of tween config
"},{"location":"tween/#pause-resume-chain","title":"Pause / Resume chain","text":"
chain.pause();\n
chain.resume();\n
"},{"location":"tween/#restart-chain","title":"Restart chain","text":"
chain.restart();\n
"},{"location":"tween/#add-tween-task","title":"Add tween task","text":"
chain.add({\ntargets: gameObject,\nalpha: 1,\nease: 'Linear',       // 'Cubic', 'Elastic', 'Bounce', 'Back'\nduration: 1000,\nrepeat: 0,            // -1: infinity\nyoyo: false\n})\n

or

chain.add([tweenConfig0, tweenConfig1, ...]);\n
"},{"location":"tween/#remove-tween-task","title":"Remove tween task","text":"
chain.remove(tweenTask);\n
"},{"location":"tween/#has-target_1","title":"Has target","text":"
var hasTarget = chain.hasTarget(gameObject);\n
"},{"location":"tween/#flow-chart","title":"Flow chart","text":"
graph TB\n\nStart((Start)) --> CallbackOnStart\nCallbackOnStart>\"Callback: onStart\"] --> ActiveDelay((\"delay\"))\nActiveDelay --> DurationForward\n\nDurationForward((\"Tween forward<br>Callback: onUpdate<br>(duration)\")) --> Hold[\"hold\"]\nHold((hold)) --> IsYoyo{Is yoyo}\nIsYoyo --> |Yes| CallbackOnYoyo>\"Callback: onYoyo\"]\nCallbackOnYoyo --> DurationBackward((\"Tween backword<br>Callback: onUpdate<br>(duration)\"))\nDurationBackward --> IsRepeat{\"Repeat count > 0\"}\nIsYoyo --> |No| IsRepeat\nIsRepeat --> |Yes| CallbackOnRepeat>\"Callback: onRepeat\"]\nCallbackOnRepeat --> RepeatDelay((\"repeatDelay\"))\nRepeatDelay --> DurationForward\n\nIsRepeat --> |No| IsLoop{\"Loop count > 0\"}\n\nIsLoop --> |Yes| CallbackOnLoop\nCallbackOnLoop>\"Callback: onLoop\"] --> LoopDelay((\"loopDelay\"))\nLoopDelay --> DurationForward\n\nIsLoop --> |No| CompleteDelay\nCompleteDelay((\"completeDelay\")) --> CallbackOnComplete>\"Callback: onComplete\"]\nCallbackOnComplete --> End((End))
"},{"location":"tween/#tween-data","title":"Tween data","text":"
  • tween.data : An array of TweenData objects, each containing a unique property and target being tweened.
    • tween.data[i].key : The property of the target to tween.
    • tween.data[i].start, tween.data[i].end, tween.data[i].current : Ease Value Data.
"},{"location":"ui-badgelabel/","title":"Badge label","text":""},{"location":"ui-badgelabel/#introduction","title":"Introduction","text":"

A container with badges above a main item.

  • Author: Rex
  • Game object
"},{"location":"ui-badgelabel/#live-demos","title":"Live demos","text":"
  • Badge
"},{"location":"ui-badgelabel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-badgelabel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-badgelabel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add badge-label object
    var badgeLabel = scene.rexUI.add.badgeLabel(config);\n
"},{"location":"ui-badgelabel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add badge-label object
    var badgeLabel = scene.rexUI.add.badgeLabel(config);\n
"},{"location":"ui-badgelabel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { BadgeLabel } from 'phaser3-rex-plugins/templates/ui/uiComponents.js';\n
  • Add badge-label object
    var badgeLabel = new BadgeLabel(scene, config);\nscene.add.existing(badgeLabel);\n
"},{"location":"ui-badgelabel/#add-badgelabel-object","title":"Add badgeLabel object","text":"
var badgeLabel = scene.rexUI.add.badgeLabel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\nmain: mainItemGameObject,\n\nleftTop: leftTopBadgeGameObject,\ncenterTop: centerTopBadgeGameObject,\nrightTop: rightTopBadgeGameObject,\nleftCenter: leftCenterBadgeGameObject,\ncenter: centerBadgeGameObject,\nrightCenter: rightCenterBadgeGameObject,\nleftBottom: leftBottomBadgeGameObject,\ncenterBottom: centerBottomBadgeGameObject,\nrightBottom: rightBottomBadgeGameObject,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of badgeLabel.
  • main : Game object of main item, optional.
  • leftTop : Badge game object at leftTop side, optional.
  • centerTop : Badge game object at centerTop side, optional.
  • rightTop : Badge game object at rightTop side, optional.
  • leftCenter : Badge game object at leftCenter side, optional.
  • center : Badge game object at center side, optional.
  • rightCenter : Badge game object at rightCenter side, optional.
  • leftBottom : Badge game object at leftBottom side, optional.
  • centerBottom : Badge game object at centerBottom side, optional.
  • rightBottom : Badge game object at rightBottom side, optional.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
      • Positive number : Indent badge game objects inside background.
      • Negative number : Exceed badge game objects out of background.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-badgelabel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyBadgeLabel extends RexPlugins.UI.BadgeLabel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var badgeLabel = new MyBadgeLabel(scene, config);\n
"},{"location":"ui-badgelabel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

badgeLabel.layout();\n

See also - dirty

"},{"location":"ui-badgelabel/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = badgeLabel.getElement('background');\n
    • Main item game object
      var item = badgeLabel.getElement('main');\n
    • LeftTop badge game object
      var badge = badgeLabel.getElement('leftTop');\n
    • CenterTop badge game object
      var badge = badgeLabel.getElement('centerTop');\n
    • RightTop badge game object
      var badge = badgeLabel.getElement('rightTop');\n
    • LeftCenter badge game object
      var badge = badgeLabel.getElement('leftCenter');\n
    • Center badge game object
      var badge = badgeLabel.getElement('center');\n
    • RightCenter badge game object
      var badge = badgeLabel.getElement('rightCenter');\n
    • LeftBottom badge game object
      var badge = badgeLabel.getElement('leftBottom');\n
    • CenterBottom badge game object
      var badge = badgeLabel.getElement('centerBottom');\n
    • RightBottom badge game object
      var badge = badgeLabel.getElement('rightBottom');\n
  • Get by name
    var gameObject = badgeLabel.getElement('#' + name);\n// var gameObject = badgeLabel.getElement('#' + name, recursive);\n
    or
    var gameObject = badgeLabel.getByName(name);\n// var gameObject = badgeLabel.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-badgelabel/#other-properties","title":"Other properties","text":"

See overlap sizer object, base sizer object, container-lite.

"},{"location":"ui-basesizer/","title":"Base sizer","text":""},{"location":"ui-basesizer/#introduction","title":"Introduction","text":"

Base class of all ui plugins.

  • Author: Rex
"},{"location":"ui-basesizer/#usage","title":"Usage","text":""},{"location":"ui-basesizer/#background","title":"Background","text":"
sizer.addBackground(gameObject);\n// sizer.addBackground(gameObject, key);\n// sizer.addBackground(gameObject, paddingConfig, key);\n
  • gameObject : Background game object will be resized after sizer.layout() method.
    • Round rectangle game object
      var gameObject = scene.rexUI.add.roundRectangle(x, y, width, height, radius, fillColor);\n
    • Nine-slice game object
      var gameObject = scene.add.nineslice(x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight);\n
      or
      var gameObject = scene.make.nineslice({\nkey: key, frame: frameName,\nleftWidth: 0, rightWidth: 0,\ntopHeight: 0, bottomHeight: 0\n});\n
    • Nine-patch game object
      var gameObject = scene.rexUI.add.ninePatch(x, y, width, height, key, columns, rows, config);\n
    • Custom game object which has resize(width, height) method.
      • Display width, display height will be changed if this background game object does not have resize method.
  • paddingConfig : Add space between bounds. Default is 0.
    • A number for left/right/top/bottom bounds,
    • Or a plain object.
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • key : A string key. Get background game object back via
    var child = sizer.getElement(key);\n

A sizer can have more than one background. i.e. user can invoke sizer.addBackground(gameObject) many times.

"},{"location":"ui-basesizer/#remove-background","title":"Remove background","text":"
  • Remove background child
    sizer.removeBackground(gameObject);\n
  • Remove background child and destroy it
    sizer.removeBackground(gameObject, true);\n
  • Remove all background children
    sizer.removeAllBackgrounds();\n
  • Remove all background children and destroy them
    sizer.removeAllBackgrounds(true);\n
"},{"location":"ui-basesizer/#depth-of-background","title":"Depth of background","text":"

Send this background child to bottom of sizer.

sizer.sendChildToBack(gameObject);\n
"},{"location":"ui-basesizer/#minimum-size","title":"Minimum size","text":"
  • Get
    var minWidth = sizer.minWidth;\nvar minHeight = sizer.minHeight;\n
  • Set
    sizer.setMinSize(width, height);\n
    or
    sizer.setMinWidth(width);\nsizer.setMinHeight(height);\n

Resize top-most sizer

sizer.setMinSize(width, height).layout()\n
"},{"location":"ui-basesizer/#dirty","title":"Dirty","text":"

Don't layout this sizer if sizer.dirty is false. i.e. Size of this sizer won't be changed, but won't layout children neither.

Default value is true.

  • Get
    var dirty = sizer.dirty;\n
  • Set
    sizer.setDirty();\n// sizer.setDirty(true);\n
    or
    sizer.dirty = true;\n
  • Clear
    sizer.setDirty(false);\n
    or
    sizer.dirty = false;\n
"},{"location":"ui-basesizer/#bounds-of-sizer","title":"Bounds of sizer","text":"
  • Get
    var leftBound = sizer.left;\nvar rightBound = sizer.right;\nvar topBound = sizer.top;\nvar bottomBound = sizer.bottom;\nvar centerX = sizer.centerX;\nvar centerY = sizer.centerY;\n
  • Set
    sizer.left = leftBound;\nsizer.right = rightBound;\nsizer.top = topBound;\nsizer.bottom = bottomBound;\nsizer.centerX = centerXBound;\nsizer.centerY = centerYBound;\n
    or
    sizer.alignLeft(leftBound);\nsizer.alignRight(rightBound);\nsizer.alignTop(topBound);\nsizer.alignBottom(bottomBound);\nsizer.alignCenterX(centerXBound);\nsizer.alignCenterY(centerYBound);\n
"},{"location":"ui-basesizer/#size-of-sizer","title":"Size of sizer","text":"
  • Size
    var width = sizer.width;\nvar height = sizer.height;\n
  • Display size
    var displayWidth = sizer.displayWidth;\nvar displayHeight = sizer.displayHeight;\n
  • Inner size
    var innerWidth = sizer.innerWidth;\nvar innerHeight = sizer.innerHeight;\n
  • Minimum size
    var minWidth = sizer.minWidth;\nvar minHeight = sizer.minHeight;\n
  • Minimum inner size
    var minInnerWidth = sizer.minInnerWidth;\nvar minInnerHeight = sizer.minInnerHeight;\n
"},{"location":"ui-basesizer/#push-into-bounds","title":"Push into bounds","text":"

Align sizer to bound if overlapping it.

sizer.pushIntoBounds();\n

or

sizer.pushIntoBounds(bounds);\n
  • bounds : Bounds in rectangle object.
"},{"location":"ui-basesizer/#scale","title":"Scale","text":"
  • Scale up from 0 to current scale of game object.
    • Pop-up width and height
      sizer\n//.setScale(scaleX, scaleY)\n.popUp(duration);\n\n// sizer.popUp(duration, undefined, ease);\n
      or
      sizer\n//.setScale(scaleX, scaleY)\n.popUpPromise(duration)\n.then(function() {\n// ....\n})\n
      • ease : Ease function, default is 'Cubic'.
    • Pop-up width only
      sizer\n//.setScaleX(scaleX)\n.popUp(duration, 'x');\n\n// sizer.popUp(duration, 'x', ease);\n
      or
      sizer\n//.setScaleX(scaleX)\n.popUpPromise(duration, 'x')\n.then(function() {\n// ....\n})\n
    • Pop-up height only
      sizer\n//.setScaleY(scaleY)\n.popUp(duration, 'y');\n\n// sizer.popUp(duration, 'y', ease);\n
      or
      sizer\n//.setScaleY(scaleY)\n.popUpPromise(duration, 'y')\n.then(function() {\n// ....\n})\n
    • Pop-up via config
      sizer\n//.setScale(scaleX, scaleY)\n.popUp({\nduration: undefined,\norientation: undefined,\nease: undefined,\n})\n
      or
      sizer\n//.setScale(scaleX, scaleY)\n.popUpPromise(config)\n.then(function() {\n// ....\n})\n
      • orientation : undefined, x, or y
  • Scale-down destroy
    • Scale-down width and height
      sizer.scaleDownDestroy(duration);\n// sizer.scaleDownDestroy(duration, undefined, ease);\n
      or
      sizer.scaleDownDestroyPromise(duration)\n.then(function() {\n// ....\n})\n
      • ease : Ease function, default is 'Linear'.
    • Scale-down width only
      sizer.scaleDownDestroy(duration, 'x');\n// sizer.scaleDownDestroy(duration, 'x', ease);\n
      or
      sizer.scaleDownDestroyPromise(duration, 'x');\n.then(function() {\n// ....\n})\n
    • Scale-down height only
      sizer.scaleDownDestroy(duration, 'y');\n// sizer.scaleDownDestroy(duration, 'y', ease);\n
      or
      sizer.scaleDownDestroyPromise(duration, 'y')\n.then(function() {\n// ....\n})\n
  • Scale-down without destroy
    • Scale-down width and height
      sizer.scaleDown(duration);\n// sizer.scaleDown(duration, undefined, ease);\n
      or
      sizer.scaleDownPromise(duration, undefined, ease)\n.then(function() {\n// ....\n})\n
    • Scale-down width only
      sizer.scaleDowny(duration, 'x');\n// sizer.scaleDowny(duration, 'x', ease);\n
      or
      sizer.scaleDownPromise(duration, 'x', ease)\n.then(function() {\n// ....\n})\n
    • Scale-down height only
      sizer.scaleDown(duration, 'y');\n// sizer.scaleDown(duration, 'y', ease);\n
      or
      sizer.scaleDownPromise(duration, 'y', ease)\n.then(function() {\n// ....\n})\n
  • Scale up/down, then scale back (yoyo)
    • Scale up/down, then scale back width and height
      sizer\n//.setScale(scaleX, scaleY)\n.scaleYoyo(duration, peakValue);\n\n// sizer.scaleYoyo(duration, peakValue, repeat, undefined, ease);\n
      or
      sizer\n//.setScale(scaleX, scaleY)\n.scaleYoyoPromise(duration, peakValue, repeat)\n.then(function() {\n// ....\n})\n
      • peakValue : Scale to this peak value, then scale back
      • repeat : Yoyo repeat, default value is 0.
      • ease : Ease function, default is 'Cubic'.
    • Scale up/down, then scale back width only
      sizer\n//.setScaleX(scaleX)\n.scaleYoyo(duration, peakValue, 0, 'x');\n\n// sizer.popUp(duration, peakValue, repeat, 'x', ease);\n
      or
      sizer\n//.setScaleX(scaleX)\n.scaleYoyoPromise(duration, peakValue, repeat, 'x')\n.then(function() {\n// ....\n})\n
    • Scale up/down, then scale back height only
      sizer\n//.setScaleY(scaleY)\n.scaleYoyo(duration, peakValue, 0, 'y');\n\n// sizer.popUp(duration, peakValue, repeat, 'y', ease);\n
      or
      sizer\n//.setScaleY(scaleY)\n.scaleYoyoPromise(duration, peakValue, repeat, 'y')\n.then(function() {\n// ....\n})\n
    • Scale up/down via config
      sizer\n//.setScale(scaleX, scaleY)\n.scaleYoyo({\nduration: undefined,\npeakValue: 1.2,\nrepeat: 0,\norientation: undefined,\nease: undefined,\n})\n
      or
      sizer\n//.setScale(scaleX, scaleY)\n.scaleYoyoPromise(config)\n.then(function() {\n// ....\n})\n
      • orientation : undefined, x, or y
  • Events
    • Pop-up complete
      sizer.on('popup.complete', function(sizer) { });\n
    • Scale-down, scale-down destroy complete
      sizer.on('scaledown.complete', function(sizer) { });\n
    • Scale up/down, then scale back (yoyo)
      sizer.on('scaleyoyo.complete', function(sizer) { });\n
"},{"location":"ui-basesizer/#fade","title":"Fade","text":"
  • Fade-in
    sizer.fadeIn(duration);\n
    or
    sizer.fadeIn(duration, endAlpha);\n
    or
    sizer.fadeIn(duration, {start:0, end:1});\n
    or
    sizer.fadeInPromise(duration, endAlpha)\n.then(function(){\n// ...\n})\n
    or
    sizer.fadeInPromise(duration, {start:0, end:1})\n.then(function(){\n// ...\n})\n
  • Fade-out destroy
    sizer.fadeOutDestroy(duration);\n
    or
    sizer.fadeOutDestroyPromise(duration)\n.then(function(){\n// ...\n})\n
  • Fade-out without destroy
    sizer.fadeOut(duration);\n
    or
    sizer.fadeOutPromise(duration)\n.then(function(){\n// ...\n})\n
  • Events
    • Fade-in complete
      sizer.on('fadein.complete', function(sizer) { });\n
    • Fade-out, fade-out destroy complete
      sizer.on('fadeout.complete', function(sizer) { });\n
"},{"location":"ui-basesizer/#ease-move","title":"Ease move","text":"
  • Move from
    sizer.moveFrom(duration, x, y);\n// sizer.moveFrom(duration, x, y, ease);\n// sizer.moveFrom({x, y, duration, ease});\n// sizer.moveFrom({x, y, speed, ease});\n
    or
    sizer\n.moveFromPromise(duration, x, y, ease)\n// .moveFromPromise({x, y, duration, ease})\n// .moveFromPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
    • x, y : Start position.
      • Number : Start position x/y.
      • String(+=300) : Related position of current position x/y.
      • undefined : Current position x/y.
    • speed : Get duration according to speed and distance between current sizer position to {x, y}
    • ease : 'Linear', 'Cubic', 'Elastic', 'Bounce', 'Back' ...
  • Move-from destroy
    sizer.moveFromDestroy(duration, x, y);\n// sizer.moveFrom(duration, x, y, ease);\n// sizer.moveFrom({x, y, duration, ease});\n// sizer.moveFrom({x, y, speed, ease});\n
    or
    sizer\n.moveFromDestroyPromise(duration, x, y, ease)\n// .moveFromDestroyPromise({x, y, duration, ease})\n// .moveFromDestroyPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
  • Move to
    sizer.moveTo(duration, x, y);\n// sizer.moveTo(duration, x, y, ease);\n// sizer.moveTo({x, y, duration, ease});\n// sizer.moveTo({x, y, speed, ease});\n
    or
    sizer\n.moveToPromise(duration, x, y, ease)\n// .moveToPromise({x, y, duration, ease})\n// .moveToPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
    • x, y : End position.
      • Number : End position x/y.
      • String(+=300) : Related position of current position x/y.
      • undefined : Current position x/y.
    • speed : Get duration according to speed and distance between current sizer position to {x, y}
    • ease : 'Linear', 'Cubic', 'Elastic', 'Bounce', 'Back' ...
  • Move-to destroy
    sizer.moveToDestroy(duration, x, y);\n// sizer.moveTo(duration, x, y, ease);\n// sizer.moveTo({x, y, duration, ease});\n// sizer.moveTo({x, y, speed, ease});\n
    or
    sizer\n.moveToDestroyPromise(duration, x, y, ease)\n// .moveToDestroyPromise({x, y, duration, ease})\n// .moveToDestroyPromise({x, y, speed, ease})\n.then(function(){\n// ...\n})    
  • Move-stop
    sizer.moveStop();\n// sizer.moveStop(true);  // Set to end position\n
  • Events
    • Move-from complete
      sizer.on('movefrom.complete', function(sizer) { });\n
    • Move-to complete
      sizer.on('moveto.complete', function(sizer) { });\n
"},{"location":"ui-basesizer/#shake","title":"Shake","text":"
  • Start
    sizer.shake(duration);\n// sizer.shake(duration, magnitude);\n
    or
    sizer.shakePromise(duration, magnitude)\n.then(function(){\n// ...\n})\n
  • Events
    • Shake complete
      sizer.on('shake.complete', function(sizer) { });\n
"},{"location":"ui-basesizer/#ease-data","title":"Ease data","text":"
  • Start
    sizer.easeDataTo(key, value, duration);\n// sizer.easeDataTo(key, value, duration, ease);\n// sizer.easeDataTo({ key, value, duration, ease });\n// sizer.easeDataTo({ key, value, speed, ease });\n
    or
    sizer.easeDataToPromise(key, value, duration, ease)\n.then(function(){\n// ...\n})\n
  • Stop
    sizer.stopEaseData(key);           // Set to end value\n// sizer.stopEaseData(key, false); // Stop at current value\n
    or
    sizer.stopAllEaseData();           // Set to end value\n// sizer.stopAllEaseData(false);   // Stop at current value\n
  • Events
    • Easing complete
      sizer.on('easedata.' + key + '.complete', function(sizer) { });\n
      sizer.on('easedata.complete', function(key, sizer) { });\n
"},{"location":"ui-basesizer/#delay-call","title":"Delay call","text":"
sizer.delayCall(delay, callback, scope);\n

Timer will be removed when destroying game object.

"},{"location":"ui-basesizer/#modal","title":"Modal","text":"
  1. Assign sizer.onCreateModalBehavior callback, or register events to close modal sizer directly.
    • onCreateModalBehavior :
      sizer.onCreateModalBehavior = function(sizer, config) {\n// ...\nsizer.modalClose(data);\n}\n
      • config : Passed from sizer.modal(config)
    • Close modal sizer
      sizer.modalClose(data);\n
  2. Pop this modal sizer
    sizer.modal(onClose);  // Use default modal config\n
    or
    sizer.modal({\n// cover: {\n//     color: 0x0,\n//     alpha: 0.8,\n//     transitIn: function(gameObject, duration) { },\n//     transitOut: function(gameObject, duration) { },\n// },\n// cover: false, \n\n// When to close modal dialog?\n// touchOutsideClose: false,\n// anyTouchClose: false,\n// timeOutClose: false,\n// manualClose: false,\n\n// duration: {\n//     in: 200,\n//     hold: 2000,\n//     out: 200\n// }\n\n// transitIn: 0,\n// transitOut: 0,\n\n// destroy: true\n}, onClose);\n
    or
    sizer\n.modalPromise(config)\n.then(function(data){\n\n})\n
    • config : See Modal behavior
    • onClose : Callback when closing modal dialog
      function(data) {      }\n
      • data : Object passed from sizer.modalClose(data).
"},{"location":"ui-basesizer/#set-properties-of-child","title":"Set properties of child","text":"
sizer.setChildPosition(child, x, y);\nsizer.setChildRotation(child, rotation);\nsizer.setChildScale(child, scaleX, scaleY);\nsizer.setChildDisplaySize(child, width, height);\nsizer.setChildVisible(child, visible);\nsizer.setChildAlpha(child, alpha);\n
"},{"location":"ui-basesizer/#depth","title":"Depth","text":"
  • Get depth of sizer
    var depth = sizer.depth;\n
  • Set depth of sizer
    sizer.setDepth(value, true);\n// sizer.depth = depth;\n
  • Set depth of sizer and all children
    sizer.setDepth(value);\n
  • Bring this sizer and its children to top
    sizer.bringToTop();\n
  • Swap depth with another sizer
    sizerA.swapDepth(sizerB);\n
  • Increase of sizer and all children
    sizer.incDepth(value);\n
  • Move game object below this sizer and all children
    sizer.moveDepthBelow(gameObject);\n
  • Move game object above this sizer and all children
    sizer.moveDepthAbove(gameObject);\n
  • Bring a child of this sizer to top
    sizer.bringChildToTop(gameObject);\n
  • Send a child of this sizer to bottom
    sizer.sendChildToBack(gameObject);\n
"},{"location":"ui-basesizer/#scroll-factor","title":"Scroll factor","text":"
  • Set scroll factor to children
    sizer.setScrollFactor(x, y);\n
"},{"location":"ui-basesizer/#change-origin","title":"Change origin","text":"
sizer.changeOrigin(originX, originY);\n

This method also will reset all local state of children.

"},{"location":"ui-basesizer/#destroy","title":"Destroy","text":"
sizer.destroy();\n
"},{"location":"ui-basesizer/#drag-sizer","title":"Drag sizer","text":"
  • Drag top-most sizer by child
    • Enable
      sizer.setDraggable(child);\n// sizer.setDraggable(child, true);\n
      or
      sizer.setDraggable(elementName);\n// sizer.setDraggable(elementName, true);\n
    • Disable
      sizer.setDraggable(child, false);\n
      or
      sizer.setDraggable(elementName, false);\n
  • Drag top-most sizer by this sizer
    • Enable
      sizer.setDraggable();\n// sizer.setDraggable(true);\n
    • Disalbe
      sizer.setDraggable(false);\n
  • Drag target sizer by child
    • Enable
      sizer.setDraggable(child, targetSizer);\n// sizer.setDraggable(child, true, targetSizer);\n
      or
      sizer.setDraggable(elementName);\n// sizer.setDraggable(elementName, true, targetSizer);\n
    • Disable
      sizer.setDraggable(child, false);\n
      or
      sizer.setDraggable(elementName, false);\n
  • Drag target config
    sizer.setDraggable({\nsensor: child, // or elementName\ntarget: undefined, // or a parentSizer\ndraggable: true\n})\n
    • sensor : A game object or a string
    • target
      • undefined : Top-most sizer
      • A game object : A parent sizer
"},{"location":"ui-basesizer/#events","title":"Events","text":"
  • Fire 'sizer.drag' on target sizer when dragging
    targetSizer.on('sizer.drag', function(pointer, dragX, dragY) {\n\n})\n
  • Fire 'sizer.dragstart' on target sizer when dragging
    targetSizer.on('sizer.dragstart', function(pointer, dragX, dragY) {\n\n})\n
  • Fire 'sizer.dragend' on target sizer when dragging
    targetSizer.on('sizer.dragend', function(pointer, dragX, dragY, dropped) {\n\n})\n
  • Fire 'sizer.drop' on target sizer when dropped
    targetSizer.on('sizer.drop', function(pointer, dropZone) {\n\n})\n
"},{"location":"ui-basesizer/#click","title":"Click","text":"
  • Add click event
    sizer.onClick(callback, scope);\n// sizer.onClick(callback, scope, config);\n
    • config : See Button
    • callback :
      function(button, gameObject, pointer, event) {\n\n}\n
      • button : Button behavior.
  • Turn off click event
    sizer.offClick(callback, scope);\n
  • Enable click event
    sizer.enableClick();\n
  • Disable click event
    sizer.disableClick();\n

Equal to

var click = scene.rexUI.add.click(sizer, config);\nclick.on('click', callback, scope);\n
"},{"location":"ui-basesizer/#click-child","title":"Click child","text":"
  • Add click event
    sizer.onClick(child, callback, scope);\n// sizer.onClick(child, callback, scope, config);\n
  • Turn off click event
    sizer.offClick(child, callback, scope);\n
  • Enable click event
    sizer.enableClick(child);\n
  • Disable click event
    sizer.disableClick(child);\n
"},{"location":"ui-basesizer/#click-outside","title":"Click outside","text":"
  • Add click-outside event
    sizer.onClickOutside(callback, scope);\n// sizer.onClickOutside(callback, scope, config);\n
    • config : See ClickOutside
    • callback :
      function(clickOutside, gameObject, pointer) {\n\n}\n
      • clickOutside : ClickOutside behavior.
  • Turn off click-outside event
    sizer.offClickOutside(callback, scope);\n
  • Enable click-outside event
    sizer.enableClickOutside();\n
  • Disable click-outside event
    sizer.disableClickOutside();\n

Equal to

var clickOutside = scene.rexUI.add.clickOutside(sizer, config);\nclickOutside.on('clickoutside', callback, scope);\n
"},{"location":"ui-basesizer/#click-outside-of-child","title":"Click outside of child","text":"
  • Add click-outside event
    sizer.onClickOutside(child, callback, scope);\n// sizer.onClickOutside(child, callback, scope, config);\n
    • config : See ClickOutside
    • callback :
      function(clickOutside, gameObject, pointer) {\n\n}\n
      • clickOutside : ClickOutside behavior.
  • Turn off click-outside event
    sizer.offClickOutside(child, callback, scope);\n
  • Enable click-outside event
    sizer.enableClickOutside(child);\n
  • Disable click-outside event
    sizer.disableClickOutside(child);\n
"},{"location":"ui-basesizer/#is-pointer-in-bounds","title":"Is pointer in bounds","text":"
  • Is current sizer clicking
    var isClicked = sizer.isPointerInBounds();\n
  • Is a child clicking
    var isClicked = sizer.isPointerInBounds(child);\n
    or
    var isClicked = sizer.isPointerInBounds(elementName);\n
    • child : Game object of child
    • elementName : Element name for retrieveing child game object.
"},{"location":"ui-basesizer/#in-touching","title":"In touching","text":"

Invoke callbeack if pointer is inside hitarea every tick.

  • Add in-touching event
    sizer.onTouching(callback, scope);\n// sizer.onTouching(callback, scope, config);\n
  • Turn off in-touching event
    sizer.offTouching(callback, scope);\n
  • Add touching-end event
    sizer.onTouchingEnd(callback, scope);\n// sizer.onTouchingEnd(callback, scope, config);\n
  • Turn off touching-end event
    sizer.offTouchingEnd(callback, scope);\n
  • Enable in-touching event
    sizer.enableTouching();\n
  • Disable in-touching event
    sizer.disableTouching();\n

Equal to

var inTouching = scene.rexUI.add.inTouching(sizer, config);\ninTouching.on('intouch', callback, scope);\n
"},{"location":"ui-basesizer/#in-touching-child","title":"In touching child","text":"
  • Add in-touching event
    sizer.onTouching(child, callback, scope);\n// sizer.onClick(child, callback, scope, config);\n
  • Turn off in-touching event
    sizer.offTouching(child, callback, scope);\n
  • Enable in-touching event
    sizer.enableTouching(child);\n
  • Disable in-touching event
    sizer.disableTouching(child);\n
"},{"location":"ui-basesizer/#set-children-interactive","title":"Set children interactive","text":"

Applies click, tap, press, swipe behaviors on this sizer, to detect input events of children.

sizer.setChildrenInteractive({\n// dropZone: false,\n\n// down: undefined,\n// up: undefined,\n// over: undefined,\n\n// click: {mode: 'release', clickInterval: 100},\n\n// press: {time: 251, threshold: 9},\n\n// tap: {time: 250, tapInterval: 200, threshold: 9, tapOffset: 10, \n//       taps: undefined, minTaps: undefined, maxTaps: undefined,},\n\n// swipe: {threshold: 10, velocityThreshold: 1000, dir: '8dir'},\n\n// inputEventPrefix: 'child.',\n})\n
  • dropZone :
    • true : Enable drop Zone on this sizer.
    • false : Do nothing.
  • down :
    • false : Don't fire (pointer-) down events
  • up :
    • false : Don't fire (pointer-) up events
  • over :
    • false : Don't fire (pointer-) over/out events
  • click : Configuration of Button behavior.
    • false : Don't install Button behavior.
  • press : Configuration of Press behavior.
    • false : Don't install Press behavior.
  • tap : Configuration of Tap behavior.
    • false : Don't install Tap behavior.
  • swipe : Configuration of Swipe behavior.
    • false : Don't install Swipe behavior.
  • inputEventPrefix : Prefix string of each event, default is 'child.'.

Note

Input behaviors are installed to this Sizer game object, not each child. And it assumes that all children are not overlapped. Use Button if user needs to enable/disable input behaviors of each child individually.

"},{"location":"ui-basesizer/#events_1","title":"Events","text":"
  • Pointer-down
    sizer.on('child.down', function(child, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-up
    sizer.on('child.up', function(child, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-over
    sizer.on('child.over', function(child, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-out
    sizer.on('child.out', function(child, pointer, event) {\n// ...\n}, scope);\n
  • Click
    sizer.on('child.click', function(child, pointer, event) {\n// ...\n}, scope);\n
    • child : Triggered child game object.
    • pointer : Pointer object.
  • Press
    sizer.on('child.pressstart', function(child, pointer) { // ...\n}, scope);\n
    sizer.on('child.pressend', function(child, pointer) { // ...\n}, scope);\n
  • Tap
    sizer.on(tapEventName, function(child, pointer) { // ...\n}, scope);\n
    • tapEventName : 'child.1tap', 'child.2tap', 'child.3tap', etc ...
  • Swipe
    sizer.on(swipeEventName, function(child, pointer) { // ...\n}, scope);\n
    • swipeEventName : 'child.swipeleft', 'child.swiperight', 'child.swipeup', 'child.swipedown'.
"},{"location":"ui-basesizer/#bind-event","title":"Bind event","text":"
  • Bind event
    sizer.bindEvent(eventEmitter, eventName, callback, scope);\n
  • Bind scene's 'preupdate' event
    sizer.bindScenePreupdateEvent(callback, scope);\n
  • Bind scene's 'update' event
    sizer.bindSceneUpdateEvent(callback, scope);\n
  • Bind scene's 'postupdate' event
    sizer.bindScenePostupdateEvent(callback, scope);\n
  • Bind scene's 'render' event
    sizer.bindSceneRenderEvent(callback, scope);\n
  • Bind scene's 'pause' event
    sizer.bindScenePauseEvent(callback, scope);\n
  • Bind scene's 'resume' event
    sizer.bindSceneResumeEvent(callback, scope);\n
  • Bind scene's 'sleep' event
    sizer.bindSceneSleepEvent(callback, scope);\n
  • Bind scene's 'wake' event
    sizer.bindSceneWakeEvent(callback, scope);\n
  • Bind scene's 'shutdown' event
    sizer.bindSceneShutdownEvent(callback, scope);\n

Will remove this event from eventEmitter when destroying sizer.

"},{"location":"ui-basesizer/#pin-game-object","title":"Pin game object","text":"
sizer.pin(gameObject);\n

or

sizer.pinLocal(gameObject);\n

Note

Method sizer.add is override in each sizer class usually.

"},{"location":"ui-basesizer/#un-pin-game-object","title":"Un-pin game object","text":"
sizer.unpin(child);\n// sizer.unpin(child, destroyChild);\n
  • destroyChild : Set true to destroy child. Default is false.

Note

Method sizer.remove is override in each sizer class usually.

"},{"location":"ui-basesizer/#draw-bounds","title":"Draw bounds","text":"
  • Draw bounds of shown game object on a graphics game object
    sizer.drawBounds(graphics);\n// sizer.drawBounds(graphics, color);\n
    • graphics : Graphics game object
    • color : Default value is 0xffffff
  • Draw bounds of shown game object, and display name of child
    sizer.drawBounds(graphics, {\n// color: 0xffffff,\n// lineWidth: 2,\n\n// name: false, \n// name: true, \n// name: {\n//     createTextCallback: function(scene) {\n//         return scene.add.text(0, 0, '');\n//     },\n//     createTextCallbackScope: undefined,\n//     align: 'left-top'\n// }\n});\n
    • graphics : Graphics game object
    • color : Default value is 0xffffff.
    • lineWidth : Default value is 1.
    • name :
      • false : Don't display child name, default value
      • true : Display child name with default text game object, aligned at left-top of child bounds.
      • Plain object :
        • name.createTextCallback : Callback of creating customized text game object for child name
          function(scene, child, childBoundsRect) {\n// return scene.add.text(0, 0, ''); \n}\n
        • name.createTextCallbackScope : Callback scope of name.createTextCallback, default is undefined
        • name.align :
          • 'left-top', or Phaser.Display.Align.TOP_LEFT : Align text game object at left-top. Default value
          • 'center', or Phaser.Display.Align.CENTER : Align text game object at center
          • 'left', or Phaser.Display.Align.LEFT_CENTER : Align text game object at left-center
          • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align text game object at right-center
          • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game text object at top-center
          • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game text object at bottom-center
          • 'left-bottom', or Phaser.Display.Align.BOTTOM_LEFT : Align text game object at left-bottom
          • 'right-top', or Phaser.Display.Align.TOP_RIGHT : Align text game object at right-top
          • 'right-bottom', or Phaser.Display.Align.BOTTOM_RIGHT : Align text game object at right-bottom
    • Text game objects of these children's name will be attached on graphics game object, graphics.clear(), or graphics.destroy() will also destroy these text game objects
"},{"location":"ui-basesizer/#hide","title":"Hide","text":"
  • Set invisible, won't layout it
    sizer.hide();\n
    or
    sizer.hide(gameObject);\n
  • Set visible, will layout it
    sizer.show();\n
    or
    sizer.show(gameObject);\n
"},{"location":"ui-basesizer/#padding","title":"Padding","text":"
  • Set inner padding, will indent children position.
    • Set inner padding via config
      sizer.setInnerPadding({\nleft: leftPadding, right: rightPadding,\ntop: topPadding,\nbottom: bottomPadding\n});\n
    • Set inner padding via single number
      sizer.setInnerPadding(value);\n
    • Set specific inner padding
      sizer.setInnerPadding(key, value);\n
      • key : 'left', 'right', 'top', 'bottom'
  • Get inner padding
    • Get inner padding values
      var innerPadding = sizer.getInnerPadding();\n
    • Get specific inner padding
      var value = sizer.getInnerPadding(key);\n
      • key : 'left', 'right', 'top', 'bottom'
  • Set outer padding, which is equal to padding parameter when adding this sizer to parent sizer.
    • Set outer padding via config
      sizer.setOuterPadding({\nleft: leftPadding, right: rightPadding,\ntop: topPadding,\nbottom: bottomPadding\n});\n
    • Set outer padding via single number
      sizer.setOuterPadding(value);\n
    • Set specific outer padding
      sizer.setOuterPadding(key, value);\n
      • key : 'left', 'right', 'top', 'bottom'
  • Get outer padding
    • Get outer padding values
      var outerPadding = sizer.getOuterPadding();\n
    • Get specific outer padding
      var value = sizer.getOuterPadding(key);\n
      • key : 'left', 'right', 'top', 'bottom'
  • Set outer padding of child, which is equal to padding parameter when adding this sizer to parent sizer.
    • Set outer padding via config
      sizer.setChildOuterPadding(\nchild,\n{\nleft: leftPadding, right: rightPadding,\ntop: topPadding,\nbottom: bottomPadding\n}\n);\n
      • child : A string key or game object.
    • Set outer padding via single number
      sizer.setChildOuterPadding(child, value);\n
      • child : A string key or game object.
    • Set specific outer padding
      sizer.setChildOuterPadding(child, key, value);\n
      • child : A string key or game object.
      • key : 'left', 'right', 'top', 'bottom'
  • Get outer padding of child
    • Get outer padding values
      var outerPadding = sizer.getChildOuterPadding(child);\n
      • child : A string key or game object.
    • Get specific outer padding
      var value = sizer.getChildOuterPadding(child, key);\n
      • child : A string key or game object.
      • key : 'left', 'right', 'top', 'bottom'
"},{"location":"ui-basesizer/#anchor","title":"Anchor","text":"
sizer.setAnchor({\n// left: '0%+0',\n// right: '0%+0',\n// centerX: '0%+0',\n// x: '0%+0',\n\n// top: '0%+0',\n// bottom: '0%+0',\n// centerY: '0%+0',\n// y: '0%+0'\n})\n
  • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
    • Percentage of visible width/height : 'p%', p: 0~100
      • 'left'(=0%), 'center'(=50%), 'right'(=100%)
      • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
    • Offset : '+n', or '-n'

For example, anchor game object's left bound to viewport's left+10, and centerY to viewport's center :

{\nleft: 'left+10',\ncenterY: 'center'\n}\n
"},{"location":"ui-basesizer/#get-child","title":"Get child","text":"
  • Get child by specific key
    1. Add child
      sizer.addChildrenMap(key, child);\n
      • Remove children map :
        sizer.removeChildrenMap(key);\n
        or
        sizer.removeChildrenMap(child);\n
    2. Get child
      var child = sizer.getElement(key);\n
  • Get child by name
    var child = sizer.getByName(name);\n// var child = sizer.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-basesizer/#get-parent","title":"Get parent","text":"
  • Get parent sizer
    var parentSizer = sizer.getParentSizer();\n
  • Get ancestor sizer matched given name
    var parentSizer = sizer.getParentSizer(name);\n
  • Get topmost sizer
    var topmostSizer = sizer.getTopmostSizer();\n
"},{"location":"ui-basesizer/#has-parentchild","title":"Has parent/child","text":"
  • Has parent
    var hasParent = sizer.hasParentSizer(parentGameObject);\n
  • Has child
    var hasChild = sizer.hasParentSizer(childGameObject);\n
"},{"location":"ui-basesizer/#is-in-touching","title":"Is in touching","text":"
  • Is this sizer in touching?
    var isTouching = sizer.isInTouching();\n
  • Is child of this sizer in touching?
    var isTouching = sizer.isInTouching(child);\n
    or
    var isTouching = sizer.isInTouching(childKey);\n
    • child : Child game object.
    • childKey : Get child game object back via sizer.getElement(childKey). See also sizer.addChildrenMap(key, child)
"},{"location":"ui-basesizer/#change-properties-of-child","title":"Change properties of child","text":"
  • Set property of child from sizer
  • Set property of child, then reset local state of child
  • Tween local state of child
"},{"location":"ui-basesizer/#add-to-container","title":"Add to container","text":"
  • Add to built-in container
    p3Container.add(sizer);\n
    or
    sizer.addToContainer(p3Container);\n
    • container : Container game object.
  • Add to Layer
    sizer.addToLayer(layer);\n
    • layer : Layer game object.

Note

container.add(sizer), or layer.add(sizer) won't add children of sizer.

"},{"location":"ui-basesizer/#layer","title":"Layer","text":"

A sizer can have a layer. Current children and new children will draw on this layer, instead of display list of scene.

  • Enable layer. Do nothing if layer is existed.
    sizer.enableLayer();\n
  • Get layer game object. Will enable layer if layer is not existed.
    var layer = sizer.getLayer();\n
"},{"location":"ui-basesizer/#shader-effects","title":"Shader effects","text":"

Apply post-fx pipeline on layer of sizer.

"},{"location":"ui-basesizer/#snapshot","title":"Snapshot","text":"
  • Draw all visible children on a render-texture.
    var renderTexture = container.snapshot({\nrenderTexture: undefined,\npadding: 0\n});\n
    • renderTexture : Draw on this render-texture
      • undefined : Create a new render-texture
    • padding :
      • 0 : No extra padding space. Default value.
      • A number : Add extra padding space around this render-texture.
  • Draw all visible children on a texture
    container.snapshot({\npadding: 0,\nsaveTexture: textureKey\n});\n
    • saveTexture : Save render result to texture manager.
"},{"location":"ui-basesizer/#layout-children","title":"Layout children","text":"

Note

Enable sizer events by set sizerEvents to true in config.

  • Fire 'sizer.postlayout' event to all children after layout.
    child.on('sizer.postlayout', function(child, sizer){\nvar prevState = sizer.getChildPrevState(child);\n})\n
    • prevState : Properties before layout.
      • prevState.x, prevState.y : Child position before layout.
      • prevState.width, prevState.height, prevState.displayWidth, prevState.displayHeight, prevState.scaleX, prevState.scaleY : Child size before layout.
  • Fire 'postlayout' event.
    sizer.on('postlayout', function(children, sizer) {\nfor(var i=0, cnt=children.length; i<cnt; i++) {\nvar prevState = sizer.getChildPrevState(children[i]);\n// ...\n}\n})\n
"},{"location":"ui-basesizer/#remove-child","title":"Remove child","text":"

Note

Enable sizer events by set sizerEvents to true in config.

  • Fire 'sizer.remove' event to removed without destroyed child.
    child.on('sizer.remove', function(child, sizer){\n\n})\n
  • Fire 'remove' event.
    sizer.on('remove', function(child, sizer){\n\n})\n
"},{"location":"ui-basesizer/#add-child","title":"Add child","text":"

Note

Enable sizer events by set sizerEvents to true in config.

  • Fire 'sizer.add' event to added child.
    child.on('sizer.add', function(child, sizer){\n\n})\n
  • Fire 'add' event.
    sizer.on('add', function(child, sizer){\n\n})\n
"},{"location":"ui-basesizer/#broadcast-event","title":"Broadcast event","text":"

Fire event to sizer itself and all children

sizer.broadcastEvent(eventName, parameter0, parameter1, ...);\n

Receive event

child.on(eventName, function(parameter0, parameter1, ...) {\n\n}, scope);\n
"},{"location":"ui-basesizer/#other-properties","title":"Other properties","text":"

This game object inherits from ContainerLite.

"},{"location":"ui-buttons/","title":"Buttons","text":""},{"location":"ui-buttons/#introduction","title":"Introduction","text":"

A container with a group of buttons.

  • Author: Rex
  • Game object
"},{"location":"ui-buttons/#live-demos","title":"Live demos","text":"
  • Buttons with header and footer
  • Expand
  • Space
  • Checkboxes/radio
  • CustomProgress background
  • Popup each button
"},{"location":"ui-buttons/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-buttons/#install-plugin","title":"Install plugin","text":""},{"location":"ui-buttons/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add buttons object
    var buttons = scene.rexUI.add.buttons(config);\n
"},{"location":"ui-buttons/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add buttons object
    var buttons = scene.rexUI.add.buttons(config);\n
"},{"location":"ui-buttons/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Buttons } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add buttons object
    var buttons = new Buttons(scene, config);\nscene.add.existing(buttons);\n
"},{"location":"ui-buttons/#add-buttons-object","title":"Add Buttons object","text":"
var buttons = scene.rexUI.add.buttons({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n// buttonsType: undefined,\n\n// Elements\n// background: backgroundGameObject,\n\nbuttons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\nexpand: false,\nalign: undefined,\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n},\n\n// space: 0,   // deprecated \n// space: { left: 0, right:0, top:0, bottom:0, item:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n// eventEmitter: this,\n// groupName: undefined,\n\n// setValueCallback: undefined,  // or setButtonStateCallback: undefined\n// setValueCallbackScope: undefined  // or setButtonStateCallbackScope: undefined\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation : Main orientation of button game objects.
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Arrange button game objects from left ot right.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Arrange button game objects from top to bottom.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • buttonsType : Type/behavior of these buttons.
    • undefined : No extra behavior, default value.
    • 'checkboxes' : Set these buttons to checkboxes.
    • 'radio' : Set these buttons to radio.
  • background : Game object of background, optional. This background game object will be resized to fit the size of grid table.
  • buttons : Array of button game objects, or Space (scene.rexUI.add.space()).
  • expand : Set true to expand width, or height of buton game objects.
  • align : Note: Add Space (scene.rexUI.add.space()) into buttons parameter to have more flexible alignment style. Alignment of these button game objects. Only valid when expand is false.
    • undefined, or 'left', or 'top' : Align game objects at left, or top.
    • 'center' : Align game objects at center.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
  • click: Configuration of button clicking.
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
  • space :
    • An object: Padding of button game objects.
      • space.top, space.bottom, space.left, space.right : Padding around bottons.
      • space.item : Space between 2 button game objects.
    • A number: Deprecated, space between 2 button game objects.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • eventEmitter : Dispatch buttons' touch events to other game object, default is this buttons game object.
  • groupName : Optional group name for argument of touch events.
  • setValueCallback, or setButtonStateCallback : Callback to set value of a button.
    • undefined : No callback, default value.
    • A function object.
      function(button, value, previousValue) {\n// ...\n}\n
      • button : Button game object.
      • value: true, or false.
      • previousValue : true, or false.
"},{"location":"ui-buttons/#custom-class","title":"Custom class","text":"
  • Define class
    class MyButtons extends RexPlugins.UI.Buttons {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var buttons = new MyButtons(scene, config);\n
"},{"location":"ui-buttons/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

buttons.layout();\n

See also - dirty

"},{"location":"ui-buttons/#other-properties","title":"Other properties","text":"

See sizer object

"},{"location":"ui-buttons/#events","title":"Events","text":"
  • Click button
    buttons.on('button.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.click', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
    • groupName : Optional group name.
    • button : Triggered button game object.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-over button
    buttons.on('button.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.over', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-out button
    buttons.on('button.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.out', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-down button
    buttons.on('button.down', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.down', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-up button
    buttons.on('button.up', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.up', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Enable button's input
    buttons.on('button.enable', function(button, index) {\n// ...\n}, scope);\n
    or
    buttons.on('button.enable', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Disable button's input
    buttons.on('button.disable', function(button, index) {\n// ...\n}, scope);\n
    or
    buttons.on('button.disable', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
"},{"location":"ui-buttons/#emit-button-click-event","title":"Emit button click event","text":"
buttons.emitButtonClick(index);\n
  • index : Index of triggered button game object, or a button game object.
"},{"location":"ui-buttons/#enabledisable-input-of-button","title":"Enable/disable input of button","text":"
  • Enable a button's input
    buttons.setButtonEnable(index);\n// buttons.setButtonEnable(index, true);\n
    • index : Index of triggered button game object, or a button game object.
  • Enable all buttons' input
    buttons.setButtonEnable();\n// buttons.setButtonEnable(true);\n
  • Disable
    buttons.setButtonEnable(index, true);\n
    • index : Index of triggered button game object, or a button game object.
  • Disable all buttons' input
    buttons.setButtonEnable(false);\n
  • Toggle
    buttons.toggleButtonEnable(index);\n
  • Toggle all buttons's input
    buttons.toggleButtonEnable();\n
  • Get button's input enable
    var enabled = bottons.getButtonEnable(index);\n
"},{"location":"ui-buttons/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = buttons.getElement('background');\n
    • Button game objects
      var buttonObjects = buttons.getElement('buttons');\n
      or
      var buttonObject = buttons.getButton(index);\n
      or
      var buttonObjects = buttons.getElement('buttons[0]'); // First button\n
  • Get by name
    var gameObject = buttons.getElement('#' + name);\n// var gameObject = buttons.getElement('#' + name, recursive);\n
    or
    var gameObject = buttons.getByName(name);\n// var gameObject = buttons.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-buttons/#add-child","title":"Add child","text":"
  • Add button child
    buttons.addButton(gameObject)\n
    • gameObject : A game object, or an array of game objects.
  • Add non-button child, see sizer.add() method.
    buttons.add(gameObject,\n{\nproportion: 0,\nalign: 'center',\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nexpand: false,\nkey: undefined,\nindex: undefined,\nminWidth: undefined,\nminHeight: undefined\n}\n)\n
"},{"location":"ui-buttons/#remove-child","title":"Remove child","text":"
  • Remove button child
    buttons.removeButton(gameObject, destroyChild);\n
    • gameObject :
      • Game object, or array of game objects : Button game object.
      • A number, or array of numbers : Index of button game object.
      • A string, or array of strings : Name of button game object.
    • destroyChild : Set true to destroy button game object.
  • Remove all buttton children
    buttons.clearButtons(destroyChild);\n
    • destroyChild : Set true to destroy button game objects.
  • Remove a button or non-button child, see sizer.remove() method.
    buttons.remove(gameObject, destroyChild);\n
  • Remove all button or non-button children, see sizer.remove() method.
    buttons.removeAll(destroyChild);\n
"},{"location":"ui-buttons/#showhide-button","title":"Show/hide button","text":"

Hidden elements won't be counted when layouting. Call buttons.layout(), or topSizer.layout() after show/hide any button.

  • Show button
    buttons.showButton(index);\n
    • index : A number index, or a button game object.
  • Hide button.
    buttons.hideButton(index);\n
    • index : A number index, or a button game object.
"},{"location":"ui-buttons/#for-each-button","title":"For each button","text":"
buttons.forEachButtton(callback, scope);\n
  • callback :
    function(button, index, buttonArray) {\n// ...\n}\n
"},{"location":"ui-buttons/#checkboxesradio","title":"Checkboxes/radio","text":"
  • Configure buttons to checkboxes/radio
    var buttons = scene.rexUI.add.buttons({\nbuttons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\n\nbuttonsType: 'checkboxes', // or 'radio'\nsetValueCallback: function(button, value, previousValue) {\n// ...\n}, // or setButtonStateCallback\n});\n
    • buttons : Array of button game objects.
      • Property name of each button game object will be used as a key in buttons.data
    • buttonsType : Set type to 'checkboxes', or 'radio'.
    • setValueCallback or setButtonStateCallback : Callback to set value of a button.
      function(button, value) {\n// ...\n}\n
      • button : Button game object.
      • value: true, or false.
      • previousValue : true, or false.
      • Also trigger 'button.statechange' event.
    • State of a button : Stored in buttons.data
    • Get states of all buttons :
      var states = buttons.getAllButtonsState();  // { key: boolean }\n
    • Clear states of all button :
      buttons.clearAllButtonsState();\n
      • Will trigger setValueCallback and 'button.statechange' event.
"},{"location":"ui-buttons/#checkboxes","title":"Checkboxes","text":"
  • Read state
    var state = buttons.getButtonState(key);\n
    • key : name property of a button game object. (i.e. button.name)
    • state : true, or false
  • Set state
    buttons.setButtonState(key, state);\n
    • key : name property of a button game object. (i.e. button.name)
    • state : true, or false
"},{"location":"ui-buttons/#radio","title":"Radio","text":"
  • Read state
    var value = buttons.getSelectedButtonName();\n
    or
    var value = buttons.value;\n
    • value : name property of a button game object. (i.e. button.name)
  • Set state
    buttons.setSelectedButtonName(key);\n
    or
    buttons.value = key;\n
    • key : name property of a button game object. (i.e. button.name)
"},{"location":"ui-buttons/#events_1","title":"Events","text":"
  • On button state changed. For Checkboxes/radio
    buttons.on('button.statechange', function(button, index, value, previousValue) {\n// ...\n}, scope);\n
    or
    buttons.on('button.statechange', function(button, groupName, index, value, previousValue) {\n// ...\n}, scope);\n
    • Can be used to replace setValueCallback.
"},{"location":"ui-chart/","title":"Chart","text":""},{"location":"ui-chart/#introduction","title":"Introduction","text":"

Draw chart on canvas.

  • Author: Rex
  • Game object
"},{"location":"ui-chart/#live-demos","title":"Live demos","text":"
  • Radar chart
"},{"location":"ui-chart/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-chart/#install-plugin","title":"Install plugin","text":""},{"location":"ui-chart/#install-chartjs","title":"Install chart.js","text":"

Chart.js is not included in rexUI, installs it before creating any chart.

scene.load.script('chartjs', 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js');\n
or
scene.load.script('chartjs', 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js');\n

"},{"location":"ui-chart/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.script('chartjs', 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/Chart.min.js');\nscene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add chart object
    var chart = scene.rexUI.add.chart(config);\n
"},{"location":"ui-chart/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add chart object
    var chart = scene.rexUI.add.chart(config);\n
"},{"location":"ui-chart/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Chart } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add chart object
    var chart = new Chart(scene, config);\nscene.add.existing(chart);\n
"},{"location":"ui-chart/#add-chart-object","title":"Add chart object","text":"
var chart = scene.rexUI.add.chart(x, y, width, height, config);\n
  • x, y : Position of this object.
  • width, height : Canvas size.
  • config : Configuration for creating chart.
    • Set undefined to not create chart at beginning.
"},{"location":"ui-chart/#custom-class","title":"Custom class","text":"
  • Define class
    class MyChart extends RexPlugins.UI.Chart {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var chart = new MyChart(scene, x, y, width, height, config);\n
"},{"location":"ui-chart/#create-chart","title":"Create chart","text":"

Create chart (if not creating at beginning).

chart.setChart(config);\n
  • config : Configuration for creating chart.
"},{"location":"ui-chart/#chart-data","title":"Chart data","text":"
  • Get dataset
    var dataset = chart.getChartDataset(datasetIndex);\n
    • datasetIndex : Index number or label string.
  • Get data
    var data = chart.getChartData(datasetIndex, dataIndex);\n
    • datasetIndex : Index number or label string.
    • dataIndex : Index number or label string.
  • Set
    chart.setChartData(datasetIndex, dataIndex, value).updateChart();\n
    • datasetIndex : Index number or label string.
    • dataIndex : Index number or label string.
"},{"location":"ui-chart/#manipulate-chart-object","title":"Manipulate chart object","text":"
  1. Get chart object
    var chart = chart.chart;\n
  2. Set properties of chart
    • Array of dataset
      var datasets = chart.data.datasets;\n
      • Label of dataset
        var label = chart.data.datasets[i].label;\n
    • Labels
      var labels = chart.data.labels;\n
    • Set chart data
      chart.data.datasets[datasetIndex].data[dataIndex] = value;\n
  3. Update chart
    chart.update();\n
"},{"location":"ui-colorcomponents/","title":"Color components","text":""},{"location":"ui-colorcomponents/#introduction","title":"Introduction","text":"

Edit color value by RGB, or HSV input fields. Clicking fist label can switch color format between RGB and HSV

  • Author: Rex
  • Game object
"},{"location":"ui-colorcomponents/#live-demos","title":"Live demos","text":"
  • Color components
"},{"location":"ui-colorcomponents/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-colorcomponents/#install-plugin","title":"Install plugin","text":""},{"location":"ui-colorcomponents/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add color-components object
    var colorComponents = scene.rexUI.add.colorComponents(config);\n
"},{"location":"ui-colorcomponents/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add color-components object
    var colorComponents = scene.rexUI.add.colorComponents(config);\n
"},{"location":"ui-colorcomponents/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ColorComponents } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add color-components object
    var colorComponents = new ColorComponents(scene, config);\nscene.add.existing(colorComponents);\n
"},{"location":"ui-colorcomponents/#add-colorcomponents-object","title":"Add colorComponents object","text":"
var colorComponents = scene.rexUI.add.colorComponents({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\n\nformatLabel: {\nbackground: {\nradius: 0,\ncolor: undefined, alpha: undefined,\nstrokeColor: undefined, strokeAlpha: undefined, strokeWidth: 2\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},\nalign: 'left',  // 'left'|'center'|'right'|'justify'\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n},\n\nspace: {left: 0, right: 0, top: 0, bottom: 0}\n},\n\n// formatLabel: labelGameObject,\n\ninputText: {\nwidth: undefined, height: undefined,\n\npadding: 0,  // {left: 0, right: 0, top: 0, bottom: 0}\n\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null,\n\n// Style when focus\n// 'focus.color': ...\n// 'focus.color2': ...\n// 'focus.stroke': ...\n},\nfocusStyle: undefined,\n\ninnerBounds: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBY: undefined,\noffsetX: 0,\noffsetY: 0,\n\n// Style when cursor move on\n// 'cursor.color': ...\n// 'cursor.backgroundColor': ...\n// 'cursor.xxx': ...\n},\ncursorStyle: undefined,\n\nwrap: {\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n},\nlineHeight: undefined,\nmaxLines: undefined,\nwrapWidth: undefined,\nletterSpacing: 0,\nhAlign: 0,\nvAlign: 'center',  // For single line text input\ncharWrap: true,    // For single line text input\n},\n\n// enterClose: true,\n// readOnly: false,\n\n// Callbacks\n// onOpen: function (textObject, hiddenInputText) {\n// },\n\n// onClose: function (textObject, hiddenInputText) {\n// },\n\n// onUpdate: function (text, textObject, hiddenInputText) {\n//     return text;\n// },   \n\n// onAddChar: function(child, index, canvasInput) {\n//    child.modifyStyle({...})\n// },\n\n// onCursorOut: function(child, cursorIndex, canvasInput) {\n//     child.modifyStyle({\n//         \n//     });\n// },\n\n// onCursorIn: function(child, cursorIndex, canvasInput) {\n//     child.modifyStyle({\n//         \n//     });\n// },\n},\n\n// inputText0: canvasInputGameObject,\n// inputText1: canvasInputGameObject,\n// inputText2: canvasInputGameObject,\n\n// proportion: { formatLabel: 0 },\n\nvaluechangeCallback: function(newValue, oldValue, knob) {\n},\nvaluechangeCallbackScope: undefined,\n\nvalue: 0xffffff,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\nitem: 0\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,    \n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of colorComponents.
  • formatLabel : Clicking this label can switch color format between RGB and HSV
    • A label game object, or a text game object.
    • A plain object
      {\nbackground: {\nradius: 0,\ncolor: undefined, alpha: undefined,\nstrokeColor: undefined, strokeAlpha: undefined, strokeWidth: 2\n},\n\ntext: textStyle,\n\nspace: {left: 0, right: 0, top: 0, bottom: 0}\n}\n
      • formatLable.background : Parameters to create round rectangle game object.
      • formatLable.text : Text style to create [text.md] game object.
      • formatLabel.space : Padding space around format label.
  • inputText : Configuration of canvasInput
  • inputText0, inputText1, inputText2 : 3 canvas input game objects if parameter inputText is not given.
  • proportion :
    • proportion.formatLabel : Default value is 0.
  • valuechangeCallback : callback function when value changed.
  • value : Initial color value (0 ~ 0xffffff).
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between swatch and inputText.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-colorcomponents/#custom-class","title":"Custom class","text":"
  • Define class
    class MyColorComponents extends RexPlugins.UI.ColorComponents {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var colorComponents = new MyColorComponents(scene, config);\n
"},{"location":"ui-colorcomponents/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

colorComponents.layout();\n

See also - dirty

"},{"location":"ui-colorcomponents/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = colorComponents.getElement('background');\n
    • Format-label game object
      var icon = colorComponents.getElement('formatLabel');\n
    • Color component input text game objects
      var textObjects = colorComponents.getElement('components');\n
      • textObjects : An arrray with 3 canvas input game objects.
  • Get by name
    var gameObject = colorComponents.getElement('#' + name);\n// var gameObject = colorComponents.getElement('#' + name, recursive);\n
    or
    var gameObject = colorComponents.getByName(name);\n// var gameObject = colorComponents.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-colorcomponents/#value","title":"Value","text":"

Change value will also change the position of marker on H-palette and SV-palette

  • Get color value
    var value = colorComponents.value;\n// var value = colorComponents.color;\n
  • Set color value
    colorComponents.setValue(value);\n// colorComponents.setColor(value);\n
    or
    colorComponents.value = value;\ncolorComponents.color = value;\n
"},{"location":"ui-colorcomponents/#events","title":"Events","text":"
  • On value changed
    colorComponents.on('valuechange', function(newValue, oldValue, colorComponents){\n//\n}, scope);\n
"},{"location":"ui-colorcomponents/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-colorinput/","title":"Color input","text":""},{"location":"ui-colorinput/#introduction","title":"Introduction","text":"

Color number (0x0~0xffffff) or color string ('#000000'~'#ffffff', or 'red') input field.

  • Author: Rex
  • Game object
"},{"location":"ui-colorinput/#live-demos","title":"Live demos","text":"
  • Color input
"},{"location":"ui-colorinput/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-colorinput/#install-plugin","title":"Install plugin","text":""},{"location":"ui-colorinput/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add color-input object
    var colorInput = scene.rexUI.add.colorInput(config);\n
"},{"location":"ui-colorinput/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add color-input object
    var colorInput = scene.rexUI.add.colorInput(config);\n
"},{"location":"ui-colorinput/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ColorInput } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add color-input object
    var colorInput = new ColorInput(scene, config);\nscene.add.existing(colorInput);\n
"},{"location":"ui-colorinput/#add-colorinput-object","title":"Add colorInput object","text":"
var colorInput = scene.rexUI.add.colorInput({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\n\nswatch: undefined,\n// swatch: { shape: 'circle' },\n// swatch: { size: 30 },\n// swatch: swatchGameObject,\n// swatch: false,\n\n// swatchSize: undefined,  // or swatch: { size }\n// squareExpandSwatch: true,\n\ninputText: inputTextConfig,\n// inputText: false,\n\ncolorPicker : {\nwidth: 160, height: 170,\n\nbackground: {\nradius: 0,\ncolor: undefined, alpha: undefined,\nstrokeColor: undefined, strokeAlpha: undefined, strokeWidth: 2\n},\n// createBackgroundCallback: function(scene) {\n//     return gameObject;\n// }\n\n// hPalettePosition: 'bottom',\n\n// space: { left: 10, right: 10, top: 10, bottom: 10, item: 8 }\n},\n\ncolorComponents: {\n// height: undefined,\n\n// formatLabel: undefined,\n\n// inputText: undefined,\n\n// space: { item: 8 }\n},\n// colorComponents: false,\n\nvaluechangeCallback: function(newValue, oldValue, colorInput) {\n},\nvaluechangeCallbackScope: undefined,\n\nvalue: 0xffffff,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0,\ntext: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,    \n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of colorInput.
  • swatch : Display color value on a square, circle shape, or an image game object with tint.
    • undefein : A square swatch. Default game object.
    • A plain object : A circle, or a round square swatch.
      { shape: 'circle' }\n
      or
      { radius: 10 }\n
      or
      { radius: 10, size: 30 }\n
      • shape : (Round-) Rectangle or circle
        • 0, or 'rectangle' : (Round-) Rectangle shape.
        • 1, or 'circle' : Circle shape.
      • radius : Radius of round rectangle.
      • size : Size of swatch. Equal to swatchSize parameter.
    • An Image or Sprite game object : Tint this game object for displaying color value.
    • false : No swatch game object.
  • swatchSize :
    • A number : Size of swatch.
    • undefined : Expand size to fit inner height of color input. Default behavior.
  • squareExpandSwatch
    • true : Expand size to fit inner height of color input. Default behavior if swatchSize is set to undefined, or not given
    • false : Keep current size of swatch.
  • inputText : Configuration of canvasInput
  • colorPicker : Configuration of a drop-down color picker, triggered by clicking swatch.
    • colorPicker.width, colorPicker.height : Sizer of color picker. Default value is 180x170
    • colorPicker.background : Parameters to create round rectangle game object, optional.
    • colorPicker.createBackgroundCallback : Callback to create background game object, optional.
      function(scene) {\nreturn gameObject;\n}\n
    • colorPicker.hPalettePosition : Position of h-palette.
      • 'bottom' or 0 : Place h-palette at bottom side of sv-palette.
      • 'left' or 1 : Place h-palette at left side of sv-palette.
      • 'top' or 2 : Place h-palette at top side of sv-palette.
      • 'right' or 3 : Place h-palette at right side of sv-palette.
    • colorPicker.space : Padding space around color picker. Default value is
      { left: 10, right: 10, top: 10, bottom: 10, item: 8 }\n
    • false : No color picker.
  • colorComponents : Configuration of color components inside the drop down color picker.
    • colorComponents.height : Height of color components.
    • colorComponents.formatLabel : Clicking this label can switch color format between RGB and HSV
      • undefined : Will create a label with default text game object.
      • A plain object
        {\nbackground: {\nradius: 0,\ncolor: undefined, alpha: undefined,\nstrokeColor: undefined, strokeAlpha: undefined, strokeWidth: 2\n},\n\ntext: textStyle,\n\nspace: {left: 0, right: 0, top: 0, bottom: 0}\n}            
    • colorComponents.inputText : Configuration of canvasInput used in this color components. Will use inputText of color input if this parameter is not given.
    • colorComponents.space : Padding space around color components. Default value is
      { item: 8 }\n
    • false : No color components.
  • valuechangeCallback : callback function when value changed.
  • value : Initial color value (0 ~ 0xffffff).
    • Number : 0 ~ 0xffffff
    • String :
      • 0x0~0xffffff
      • '#000000'~'#ffffff'
      • 'red'
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between swatch and inputText.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-colorinput/#custom-class","title":"Custom class","text":"
  • Define class
    class MyColorInput extends RexPlugins.UI.ColorInput {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var colorInput = new MyColorInput(scene, config);\n
"},{"location":"ui-colorinput/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

colorInput.layout();\n

See also - dirty

"},{"location":"ui-colorinput/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = colorInput.getElement('background');\n
    • Swatch game object
      var icon = colorInput.getElement('swatch');\n
    • Input text game object
      var textObject = colorInput.getElement('inputText');\n
  • Get by name
    var gameObject = colorInput.getElement('#' + name);\n// var gameObject = colorInput.getElement('#' + name, recursive);\n
    or
    var gameObject = colorInput.getByName(name);\n// var gameObject = colorInput.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-colorinput/#value","title":"Value","text":"

Change value will also change the position of marker on H-palette and SV-palette

  • Get color value
    var value = colorInput.value;\n// var value = colorInput.color;\n
  • Set color value
    colorInput.setValue(value);\n// colorInput.setColor(value);\n
    or
    colorInput.value = value;\ncolorInput.color = value;\n
"},{"location":"ui-colorinput/#events","title":"Events","text":"
  • On value changed
    colorInput.on('valuechange', function(newValue, oldValue, colorInput){\n//\n}, scope);\n
"},{"location":"ui-colorinput/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-colorpicker/","title":"Color picker","text":""},{"location":"ui-colorpicker/#introduction","title":"Introduction","text":"

Pick color value from H and SV palettes.

  • Author: Rex
  • Game object
"},{"location":"ui-colorpicker/#live-demos","title":"Live demos","text":"
  • Color picker
"},{"location":"ui-colorpicker/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-colorpicker/#install-plugin","title":"Install plugin","text":""},{"location":"ui-colorpicker/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add color-picker object
    var colorPicker = scene.rexUI.add.colorPicker(config);\n
"},{"location":"ui-colorpicker/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add color-picker object
    var colorPicker = scene.rexUI.add.colorPicker(config);\n
"},{"location":"ui-colorpicker/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ColorPicker } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add color-picker object
    var colorPicker = new ColorPicker(scene, config);\nscene.add.existing(colorPicker);\n
"},{"location":"ui-colorpicker/#add-colorpicker-object","title":"Add colorPicker object","text":"
var colorPicker = scene.rexUI.add.colorPicker({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\n\nhPalette: {\nposition: 'bottom',\nsize: 10,\nwidth: undefined,\nheight: undefined,       },\n\nsvPalette: {\nwidth: undefined,\nheight: undefined,\n},\n\nvaluechangeCallback: function(newValue, oldValue, knob) {\n},\nvaluechangeCallbackScope: undefined,\n\nvalue: 0xffffff,\n\n// space: { left: 0, right:0, top:0, bottom:0, item:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,    \n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of colorPicker.
  • hPalette : Configuration of h-palette. H-palette is rendered on a canvas game object.
    • hPalette.position : Position of h-palette.
      • 'bottom' or 0 : Place h-palette at bottom side of sv-palette.
      • 'left' or 1 : Place h-palette at left side of sv-palette.
      • 'top' or 2 : Place h-palette at top side of sv-palette.
      • 'right' or 3 : Place h-palette at right side of sv-palette.
    • hPalette.size : Width (if position of h-palette is at left or right side) or height (if position of h-palette is at top or bottom side) of h-palette.
    • hPalette.width : Width (if position of h-palette is at left or right side) of h-palette.
    • hPalette.height : Height (if position of h-palette is at top or bottom side) of h-palette.
  • svPalette : Configuration of sv-palette. SV-palette is rendered on a canvas game object.
    • svPalette.width : Width of sv-palette.
    • svPalette.height : Height of sv-palette.
  • valuechangeCallback : callback function when value changed.
  • value : Initial color value (0 ~ 0xffffff).
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between sv-palette and h-palette.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-colorpicker/#custom-class","title":"Custom class","text":"
  • Define class
    class MyColorPicker extends RexPlugins.UI.ColorPicker {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var colorPicker = new MyColorPicker(scene, config);\n
"},{"location":"ui-colorpicker/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

colorPicker.layout();\n

See also - dirty

"},{"location":"ui-colorpicker/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = colorPicker.getElement('background');\n
    • H-palette game object
      var icon = colorPicker.getElement('hPalette');\n
    • SV-palette game object
      var textObject = colorPicker.getElement('svPalette');\n
  • Get by name
    var gameObject = colorPicker.getElement('#' + name);\n// var gameObject = colorPicker.getElement('#' + name, recursive);\n
    or
    var gameObject = colorPicker.getByName(name);\n// var gameObject = colorPicker.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-colorpicker/#value","title":"Value","text":"

Change value will also change the position of marker on H-palette and SV-palette

  • Get color value
    var value = colorPicker.value;\n// var value = colorPicker.color;\n
  • Set color value
    colorPicker.setValue(value);\n// colorPicker.setColor(value);\n
    or
    colorPicker.value = value;\ncolorPicker.color = value;\n
"},{"location":"ui-colorpicker/#events","title":"Events","text":"
  • On value changed
    colorPicker.on('valuechange', function(newValue, oldValue, colorPicker){\n//\n}, scope);\n
"},{"location":"ui-colorpicker/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-confirmaction/","title":"Confirm action","text":""},{"location":"ui-confirmaction/#introduction","title":"Introduction","text":"

Create a modal confirm dialog temporary, invoke callback after clicking button.

  • Author: Rex
  • Method
"},{"location":"ui-confirmaction/#live-demos","title":"Live demos","text":"
  • Confirm action
"},{"location":"ui-confirmaction/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-confirmaction/#install-plugin","title":"Install plugin","text":""},{"location":"ui-confirmaction/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Run confirm action
    var dialog = scene.rexUI.confirmAction(scene, config);\n
    • dialog : Confirm dialog will be destroy after clicking any button.
"},{"location":"ui-confirmaction/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Run confirm action
    var dialog = scene.rexUI.confirmAction(scene, config)\n
    • dialog : Confirm dialog will be destroy after clicking any button.
"},{"location":"ui-confirmaction/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ConfirmAction } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Run confirm action
    var dialog = ConfirmAction(scene, config)\n
    • dialog : Confirm dialog will be destroy after clicking any button.
"},{"location":"ui-confirmaction/#run-confirm-action","title":"Run confirm action","text":"
var dialog = scene.rexUI.confirmAction(scene, {    style: confirmDialogConfig\n\ncontent: confirmDialogResetChoiceDisplayContentConfig,\n\n// modal: confirmDialogModalConfig,\n\n// onCreateDialog: function(dialog) { },\n\nconfirm: function() {},\n// confirmScope: \n// confirmButtonIndex: 0,\n\n// cancel: function() {},\n// cancelScope: \n// cancelButtonIndex: 1,\n})\n
  • Build confirm dialog
    • style : Config parameter of Confirm dialog
    • content : Content strings of title, content, button.
    • modal : Config parameter of modal method
    • onCreateDialog : Callback invoking after creating dialog.
      function(dialog) {\n\n}\n
  • Callbacks
    • confirm, confirmScope : Callback invoking when click confirm/OK button of Confirm dialog
    • confirmButtonIndex : Index of confirm/OK button on Confirm dialog. Default value is 0.
    • cancel, cancelScope : Callback invoking when click cancel/cancel button of Confirm dialog
    • cancelButtonIndex : Index of cancel/cancel button on Confirm dialog. Default value is 1.
  • dialog : Confirm dialog will be destroy after clicking any button.
"},{"location":"ui-confirmactionbutton/","title":"Confirm action button","text":""},{"location":"ui-confirmactionbutton/#introduction","title":"Introduction","text":"

Click this label to invoke ConfirmAction. It will create a modal confirm dialog temporary, invoke callback after clicking button.

  • Author: Rex
  • Game object
"},{"location":"ui-confirmactionbutton/#live-demos","title":"Live demos","text":"
  • Open page
"},{"location":"ui-confirmactionbutton/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-confirmactionbutton/#install-plugin","title":"Install plugin","text":""},{"location":"ui-confirmactionbutton/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add button object
    var button = scene.rexUI.add.confirmActionButton(config);\n
"},{"location":"ui-confirmactionbutton/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add button object
    var button = scene.rexUI.add.confirmActionButton(config);\n
"},{"location":"ui-confirmactionbutton/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ConfirmActionButton } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add button object
    var button = new ConfirmActionButton(scene, config);\nscene.add.existing(button);\n
"},{"location":"ui-confirmactionbutton/#add-button-object","title":"Add button object","text":"
var button = scene.rexUI.confirmActionButton({\n// Parameters of Label\n\n\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\n\nicon: iconGameObject,\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntext: textGameObject,\nexpandTextWidth: false,\nexpandTextHeight: false,\n\naction: actionGameObject,\n// actionMask: false,\n// squareFitAction: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nalign: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\n\nicon: 0, iconTop: 0, iconBottom: 0, iconLeft: 0, iconRight: 0,\n\ntext: 0,\nactionTop: 0, actionBottom: 0, actionLeft: 0, actionRight: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n\n\n// Parameter of building confirm dialog\nconfirmDialog: {\nstyle: confirmDialogConfig\n// content: confirmDialogResetChoiceDisplayContentConfig,\n// modal: confirmDialogModalConfig,\n// onCreateDialog: function(dialog) { },\n\n// confirmButtonIndex: 0,\n// cancelButtonIndex: 1,\n\n},\n\n// Callbacks\nconfirm: function() {},\n// confirmScope:\n\n// cancel: function() {},\n// cancelScope: \n});\n
  • Parameters of Label...
  • Parameter of building confirm dialog
    • confirmDialog.style : Config parameter of Confirm dialog
    • confirmDialog.content : Content strings of title, content, button. Can assign this value later.
    • confirmDialog.modal : Config parameter of modal method
    • confirmDialog.onCreateDialog : Callback invoking after creating dialog.
      function(dialog) {\n\n}\n
    • confirmDialog.confirmButtonIndex : Index of confirm/OK button on Confirm dialog. Default value is 0.
    • confirmDialog.cancelButtonIndex : Index of cancel/cancel button on Confirm dialog. Default value is 1.
  • Callbacks
    • confirm, confirmScope : Callback invoking when click confirm/OK button of Confirm dialog
    • cancel, cancelScope : Callback invoking when click cancel/cancel button of Confirm dialog

Destroy confirm dialog after clicking confirm/OK, or cancel/cancel button.

"},{"location":"ui-confirmactionbutton/#custom-class","title":"Custom class","text":"
  • Define class
    class MyButton extends RexPlugins.UI.ConfirmActionButton {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var button = new MyButton(scene, config);\n
"},{"location":"ui-confirmactionbutton/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

button.layout();\n

See also - dirty

"},{"location":"ui-confirmactionbutton/#get-element","title":"Get element","text":"

See Get element

"},{"location":"ui-confirmactionbutton/#set-callbacks","title":"Set callbacks","text":"
  • Callback after clicking confirm/OK button of confirm dialog
    button.setConfirmCallback(callback);\n// button.setConfirmCallback(callback, scope);\n
    • callback : Any function object
      function() {\n\n}\n
  • Callback after clicking cancel/cancel button of confirm dialog
    button.setCancelCallback(callback);\n// button.setCancelCallback(callback, scope);\n
    • callback : Any function object
      function() {\n\n}\n
"},{"location":"ui-confirmactionbutton/#set-display-content-of-confirm-dialog","title":"Set display content of confirm dialog","text":"
button.setConfirmDialogContent({\ntitle: '',\ncontent: '',\nbuttonA: '',\nbuttonB: '',\n});\n

or

button.setConfirmDialogContent({\ntitle: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\ncontent: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nbuttonA: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nbuttonB: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nchoices: [\n{\ntext: '', value: undefined,\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n},        // ...\n]\n});\n
  • title, content,buttonA, buttonB : Display content
    • A string : Set text of simple lable
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
  • choices : Array of display content
    • A string : Set text of simple lable, also use this string as option value.
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
      • Property value : Option value.
"},{"location":"ui-confirmactionbutton/#set-style-of-confirm-dialog","title":"Set style of confirm dialog","text":"
button.setConfitmDialogStyle(style);\n
  • style : See Config parameter of Confirm dialog
"},{"location":"ui-confirmactionbutton/#set-configuration-of-confirm-dialogs-modal-behavior","title":"Set configuration of confirm dialog's modal behavior","text":"
button.setConfitmDialogModalConfig(config);\n
  • config : See Config parameter of modal method
"},{"location":"ui-confirmactionbutton/#disalbe-confirm-dialog","title":"Disalbe confirm dialog","text":"

Run confirm callback directly without confirm dialog.

button.setConfirmDialogEnable(false);\n
"},{"location":"ui-confirmactionbutton/#other-properties","title":"Other properties","text":"

See label, sizer object, base sizer object, container-lite.

"},{"location":"ui-confirmdialog/","title":"Confirm dialog","text":""},{"location":"ui-confirmdialog/#introduction","title":"Introduction","text":"

Using json style to create confirm dialog, composed of simple-label title, simple-label content, with simple-label 0, 1, or 2 action button(s).

  • Author: Rex
  • Game object
"},{"location":"ui-confirmdialog/#live-demos","title":"Live demos","text":"
  • Yes-no buttons
  • Ok button
  • Any-touch closing
  • TextArea content
  • Radio-choices
"},{"location":"ui-confirmdialog/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-confirmdialog/#install-plugin","title":"Install plugin","text":""},{"location":"ui-confirmdialog/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add dialog object
    var dialog = scene.rexUI.add.confirmDialog(style).resetDisplayContent(config);\n// var dialog = scene.rexUI.add.confirmDialog(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-confirmdialog/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add dialog object
    var dialog = scene.rexUI.add.confirmDialog(style).resetDisplayContent(config);\n// var dialog = scene.rexUI.add.confirmDialog(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-confirmdialog/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ConfirmDialog } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add dialog object
    var dialog = new ConfirmDialog(scene, config);\n// var dialog = new ConfirmDialog(scene, config, creators);\nscene.add.existing(dialog);\ndialog.resetDisplayContent(config);\n
"},{"location":"ui-confirmdialog/#add-dialog-object","title":"Add dialog object","text":"
var dialog = scene.rexUI.add.confirmDialog({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\nbackground: backgroundStyle,\n// background: null,\n\ntitle: titleStyle,  // SimpleLabelConfig\n// title: null,\n\ncontent: contentStyle, // SimpleLabelConfig, or TextAreaStyle\n// content: null,\n\nbuttonMode: 0,  // 0|1|2\n\nbutton: SimpleLabelConfig,\n// buttonA: SimpleLabelConfig\n// buttonB: SimpleLabelConfig\n\n// choice: SimpleLabelConfig,\n// choicesType\n// choicesWidth: undefined,\n// choicesHeight: undefined,\n\n// Space\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\ntitle: 0,\ntitleLeft: 0,\ntitleRight: 0,\n\ncontent: 0,\ncontentLeft: 0,\ncontentRight: 0,\n\nactionsLeft: 0,\nactionsRight: 0,\naction: 0,\n\nchoices: 0,\nchoicesLeft: 0,\nchoicesRight: 0,\nchoice: 0,\nchoiceLine: 0,\nchoiceColumn: 0, choiceRow: 0,\nchoicesBackgroundLeft: 0,\nchoicesBackgroundRight: 0,\nchoicesBackgroundTop: 0,\nchoicesBackgroundBottom: 0,\n},\n\nproportion: {\ntitle: 0,\ncontent: 0,\nactions: 0,\nchoices: 0,\n},\n\nexpand: {\ntitle: true,\ncontent: true,\nactions: false,\nchoices: true,\n},\n\nalign: {\ntitle: 'center',\ncontent: 'center',\nactions: 'center',\nchoices: 'center',\n},\n\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n},\n\nmodal: {\ncover: {\ncolor: 0x0,\nalpha: 0.8,\ntransitIn: function(gameObject, duration) { },\ntransitOut: function(gameObject, duration) { },\n},\n// cover: false, \n\n// When to close modal dialog?\ntouchOutsideClose: false,\nanyTouchClose: false,\ntimeOutClose: false,\nmanualClose: false,\n\nduration: {\nin: 200,\nhold: 2000,\nout: 200\n}\n\ntransitIn: 0,\ntransitOut: 0,\n\ndestroy: true,\n\ndefaultBehavior: true,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n\n// confirmButtonIndex: 0,\n// cancelButtonIndex: 1,\n\n}, creators);\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as background element.
    • null : Don't create any game object.
  • title :
    • Styles of simple-label
    • null : Don't create any game object.
  • content :
    • Styles of simple-label : Create Label as content element.
    • Style of TextArea : Create TextArea as content element.
    • null : Don't create any game object.
  • buttonMode : 0, 1, or 2
    • 0 : No action button, any touch can close modal dialog
    • 1, 2 : Dialog with 1 or 2 action buttons, clicking any action button to close modal dialog.
  • button, buttonA, buttonB, choice :
    • Styles of simple-label, optional.
  • choicesType : Sizer type (Buttons/FixWidthButtons/GridButtons) and behavior (''/'radio'/'checkboxes') of choice buttons.
    • undefined, '', or 'y' : Buttons in vertical/horizontal without any extra behavior, default behavior.
    • 'radio', or 'x-radio' : Buttons in vertical/horizontal, with radio behavior.
      • Name of selected button game object (gameObject.name) will be returned via method dialog.setChoicesSelectedButtonName().
    • 'checkboxes', or 'x-checkboxes' : Buttons in vertical/horizontal, with checkboxes behavior.
      • Name of selected button game object (gameObject.name) will be return via method dialog.getChoicessButtonStates().
    • 'wrap' : FixWidthButtons without any extra behavior, default behavior.
    • 'wrap-radio' : FixWidthButtons with radio behavior.
      • Name of Selected button game object (gameObject.name) will be returned via method dialog.setChoicesSelectedButtonName()
    • 'wrap-checkboxes' : FixWidthButtons with checkboxes behavior.
      • Name of selected button game object (gameObject.name) will be return via method dialog.getChoicessButtonStates().
  • choicesWidth, choicesHeight : Minimum width, minimum height of choices.
    • Must assign choicesHeight value if using GridButtons choices.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.title : Space between title game object and below game object.
    • space.titleLeft, space.titleRight : Extra left/right padding of title game object.
    • space.content : Space between content game object and below game object.
    • space.contentLeft, space.contentRight : Extra left/right padding of content game object.
    • space.action : Space between each action-button game objects.
  • proportion : Keep height of element, or expand height of element.
    • proportion.title : Set to 1 to expand height of title. Default is 0.
    • proportion.content : Set to 1 to expand height of content. Default is 0.
    • proportion.actions : Set to 1 to expand height of actions. Default is 0.
  • expand : Expand width of element
    • expand.title : Set true to expand width of title game object. Default is true.
    • expand.content : Set true to expand width of content game object. Default is true.
    • expand.actions : Set true to expand width of actions game object. Default is false.
  • align : Align element
    • align.title
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value. Will add Spaces at right and left sides.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center. Will add a Space at right side.
    • align.content : Align content game object to 'left'/'center'/'right', if expand.content is false.
    • align.actions : Align action game objects to 'left'/'center'/'right', if expand.actions is false.
  • click: Configuration of button clicking.
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
  • modal : Configuration of modal, See Modal behavior.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false..
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • confirmButtonIndex, cancelButtonIndex : Button index for firing 'confirm', 'cancel' events. Default values are 0, 1.
  • creators : Callbacks for creating components.
    {\nbackground: undefined,\ntitle: undefined,\ncontent: undefined,\nbutton: undefined,\nbuttonA: undefined,\nbuttonB: undefined,\n}\n
    • creators.background : Callback to create background of dialog. Default behavior is creating a round-rectangle-shape.
      function(scene, config)  {\nreturn gameObject;\n}\n
    • creators.title, creators.content, creators.button, creators.buttonA, creators.buttonB : Creators of simple-label, included these properties
      {\nbackground: undefined,\ntext: undefined,\nicon: undefined,\naction: undefined,\n}\n
"},{"location":"ui-confirmdialog/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDialog extends RexPlugins.UI.ConfirmDialog {\nconstructor(scene, config, creators) {\nsuper(scene, config, creators);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var dialog = new MyDialog(scene, config, creators);\n
"},{"location":"ui-confirmdialog/#reset-display-content","title":"Reset display content","text":"
dialog.resetDisplayContent({\ntitle: '',\ncontent: '',\nbuttonA: '',\nbuttonB: '',\n});\n

or

dialog.resetDisplayContent({\ntitle: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\ncontent: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nbuttonA: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nbuttonB: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nchoices: [\n{\ntext: '', value: undefined,\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n},        // ...\n]\n});\n
  • title, content : Display content
    • A string : Set text of simple lable
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
    • null : Hide title or content element.
  • buttonA, buttonB : Display content
    • A string : Set text of simple lable
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
  • choices : Array of display content
    • A string : Set text of simple lable, also use this string as option value.
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
      • Property value : Option value.

Run dialog.layout() after this method, to layout children again.

"},{"location":"ui-confirmdialog/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

dialog.layout();\n

See also - dirty

"},{"location":"ui-confirmdialog/#modal","title":"Modal","text":"

Pop this dialog as modal dialog, close this modal dialog under these conditions :

  • Clicking any action button.
  • Clicking any choice button and no action button on dialog.
dialog.modal(onClose);  // Use default modal config\n

or

dialog.modal({\n// cover: {\n//     color: 0x0,\n//     alpha: 0.8,\n//     transitIn: function(gameObject, duration) { },\n//     transitOut: function(gameObject, duration) { },\n// },\n// cover: false, \n\n// When to close modal dialog?\n// touchOutsideClose: false,\n// anyTouchClose: false,\n// timeOutClose: false,\n// manualClose: false,\n\n// duration: {\n//     in: 200,\n//     hold: 2000,\n//     out: 200\n// }\n\n// transitIn: 0,\n// transitOut: 0,\n\n// destroy: true\n}, onClose);\n

or

dialog\n.modalPromise(config)\n.then(function(data){\n\n})\n
  • config : See Modal behavior
    • config.defaultBehavior :
      • undefined, or true : Will close modal dialog when clicking any action button.
      • false : Disable default behavior.
  • onClose : Callback when closing modal dialog
    function(data) {\n// var index = data.index;\n// var text = data.text;\n// var value = data.value;\n// var button = data.button;\n// var dialog = data.dialog;\n}\n
    • data : Contains these properties
      • data.index : Index of clicking action button
      • data.text : button.text, this property is valided if button game object is a label.
      • data.value :
        • A single value : Return selected value, if choicesType is 'radio'
        • A dictionary contains {value: boolean} : Return selected values, if choicesType is 'checkboxes'
        • undefined : Default value
      • data.button : Clicked button game object.
      • data.dialog : This dialog game object.
"},{"location":"ui-confirmdialog/#button-index","title":"Button index","text":"
  • Confirm button
    • Get
      var confirmButtonIndex = dialog.confirmButtonIndex;\n
    • Set
      dialog.setConfirmButtonIndex(index);\n// dialog.confirmButtonIndex = index;\n
  • Cancel button
    • Get
      var cancelButtonIndex = dialog.cancelButtonIndex;\n
    • Set
      dialog.setCancelButtonIndex(index);\n// dialog.cancelButtonIndex = index;\n
"},{"location":"ui-confirmdialog/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = dialog.getElement('background');\n
    • Title game object
      var title = dialog.getElement('title');\n
    • Content game object
      var content = dialog.getElement('content');\n
    • Buttons game object
      var buttonA = dialog.getElement('buttonA');\nvar buttonB = dialog.getElement('buttonB');\n
  • Get by name
    var gameObject = dialog.getElement('#' + name);\n// var gameObject = dialog.getElement('#' + name, recursive);\n
    or
    var gameObject = dialog.getByName(name);\n// var gameObject = dialog.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-confirmdialog/#other-properties","title":"Other properties","text":"

See dialog, sizer object, base sizer object, container-lite.

"},{"location":"ui-confirmdialog/#events","title":"Events","text":"
  • Click confirm button
    dialog.on('confirm', function (data) {\n// var index = data.index;\n// var text = data.text;\n// var value = data.value;\n// var button = data.button;\n// var dialog = data.dialog;\n}, scope);\n
    • data : See modal
  • Click cancel button
    dialog.on('cancel', function (data) {\n// var index = data.index;\n// var text = data.text;\n// var value = data.value;\n// var button = data.button;\n// var dialog = data.dialog;\n}, scope);\n
    • data : See modal
"},{"location":"ui-dialog/","title":"Dialog","text":""},{"location":"ui-dialog/#introduction","title":"Introduction","text":"

A container with a title, content, buttons and background.

  • Author: Rex
  • Game object
"},{"location":"ui-dialog/#live-demos","title":"Live demos","text":"
  • Dialog
  • Yes-no dialog
  • Action buttons with Space
  • Radio choices dialog
  • Horizontal-radio choices dialog
  • Wrap-radio choices dialog
  • Wrap-checkboxes choices dialog
  • Grid-checkboxes choices dialog
  • Popup/scaledown
    • Pop-up dialog
  • Ease-in, ease-out
  • Show/hide buttons
  • Add button
  • Wrap label
  • Modal dialog
  • Content sizer
"},{"location":"ui-dialog/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-dialog/#install-plugin","title":"Install plugin","text":""},{"location":"ui-dialog/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add dialog object
    var dialog = scene.rexUI.add.dialog(config);\n
"},{"location":"ui-dialog/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add dialog object
    var dialog = scene.rexUI.add.dialog(config);\n
"},{"location":"ui-dialog/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Dialog } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add dialog object
    var dialog = new Dialog(scene, config);\nscene.add.existing(dialog);\n
"},{"location":"ui-dialog/#add-dialog-object","title":"Add dialog object","text":"
var dialog = scene.rexUI.add.dialog({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\nbackground: backgroundGameObject,\n\ntitle: titleGameObject,\n\ntoolbarBackground: toolbarBackgroundGameObject,\ntoolbar: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\n\nleftToolbarBackground: leftToolbarBackgroundGameObject,\nleftToolbar: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\n\ncontent: contentGameObject,\n\ndescription: descriptionGameObject,\n\nchoicesType: '',\n// choicesWidth: undefined,\n// choicesHeight: undefined,  // Used when choicesType is `'grid'`, `'grid-radio'`, or `'grid-checkboxes'`\nchoicesBackground: choicesBackgroundGameObject,\nchoices: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\n\nactionsBackground: actionsBackgroundGameObject,\nactions: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\n\n// Space\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\ntitle: 0,\ntitleLeft: 0,\ntitleRight: 0,\ntitleTop: 0,\n\ntoolbarItem: 0,\nleftToolbarItem: 0,\n\ncontent: 0,\ncontentLeft: 0,\ncontentRight: 0,\n\ndescription: 0,\ndescriptionLeft: 0,\ndescriptionRight: 0\n\nchoices: 0,\nchoicesLeft: 0,\nchoicesRight: 0,\n\n// choiceLine: 0,   // Used when choicesType is `'wrap'`, `'wrap-radio'`, or `'wrap-checkboxes'`\n// choiceColumn: 0, // Used when choicesType is `'grid'`, `'grid-radio'`, or `'grid-checkboxes'`\n// choiceRow: 0,    // Used when choicesType is `'grid'`, `'grid-radio'`, or `'grid-checkboxes'`\nchoicesBackgroundLeft: 0,\nchoicesBackgroundRight: 0,\nchoicesBackgroundTop: 0,\nchoicesBackgroundBottom: 0,\n\naction: 0,\nactionsLeft: 0,\nactionsRight: 0,\nactionsBottom: 0,\n\n},\n\nproportion: {\ntitle: 0,\ncontent: 0,\ndescription: 0,\nchoices: 0,\nactions: 0,\n},\n\nexpand: {\ntitle: true,\ncontent: true,\ndescription: true,\nchoices: true,\nactions: false,\n},\n\nalign: {\ntitle: 'center',\ncontent: 'center',\ndescription: 'center',\nchoices: 'center',\nactions: 'center',\n},\n\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n}\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of dialog.
  • title : Game object of title, optional.
  • toolbar : Array of Game objects for toolbar-buttons group which arranged from left to right, optional.
    • [] : Assign an empty array if user will add button later.
  • toolbarBackground : Game object of toolbar buttons background, optional. This background game object will be resized to fit the size of dialog.
  • leftToolbar : Array of Game objects for left-toolbar-buttons group which arranged from left to right, optional.
    • [] : Assign an empty array if user will add button later.
  • leftToolbarBackground : Game object of leftToolbar buttons background, optional. This background game object will be resized to fit the size of dialog.
  • content : Game object of content, optional.
  • description : Game object of description, optional.
  • choices : Array of Game objects for choice-buttons group which arranged from top to bottom, optional.
    • Array of Game objects, for Buttons/FixWidthButtons choices.
      • [] : Assign an empty array if user will add button later.
    • 2d Array of Game objects, for GridButtons choices..
  • choicesBackground : Game object of choices buttons background, optional. This background game object will be resized to fit the size of dialog.
  • choicesType : Sizer type (Buttons/FixWidthButtons/GridButtons) and behavior (''/'radio'/'checkboxes') of choice buttons.
    • undefined, 'x', or 'y' : Buttons in vertical/horizontal without any extra behavior, default behavior.
    • 'radio', or 'x-radio' : Buttons in vertical/horizontal, with radio behavior.
      • Name of selected button game object (gameObject.name) will be returned via method dialog.setChoicesSelectedButtonName().
    • 'checkboxes', or 'x-checkboxes' : Buttons in vertical/horizontal, with checkboxes behavior.
      • Name of selected button game object (gameObject.name) will be return via method dialog.getChoicessButtonStates().
    • 'wrap' : FixWidthButtons without any extra behavior, default behavior.
    • 'wrap-radio' : FixWidthButtons with radio behavior.
      • Name of Selected button game object (gameObject.name) will be returned via method dialog.setChoicesSelectedButtonName()
    • 'wrap-checkboxes' : FixWidthButtons with checkboxes behavior.
      • Name of selected button game object (gameObject.name) will be return via method dialog.getChoicessButtonStates().
    • 'grid' : GridButtons without any extra behavior, default behavior.
    • 'grid-radio' : GridButtons with radio behavior.
      • Name of Selected button game object (gameObject.name) will be returned via method dialog.setChoicesSelectedButtonName()
    • 'grid-checkboxes' : GridButtons with checkboxes behavior.
      • Name of selected button game object (gameObject.name) will be return via method dialog.getChoicessButtonStates().
  • choicesWidth, choicesHeight : Minimum width, minimum height of choices.
    • Must assign choicesHeight value if using GridButtons choices.
  • actions : Array of Game objects, or Space (scene.rexUI.add.space()) for action-buttons group which arranged from left to right, optional.
    • [] : Assign an empty array if user will add button later.
  • choicesBackground : Game object of choices buttons background, optional. This background game object will be resized to fit the size of dialog.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.title : Space between title game object and below game object.
    • space.titleLeft, space.titleRight : Extra left/right padding of title game object.
    • space.content : Space between content game object and below game object.
    • space.contentLeft, space.contentRight : Extra left/right padding of content game object.
    • space.description : Space between description game object and below game object.
    • space.descriptionLeft, space.descriptionRight : Extra left/right padding of description game object.
    • space.choices : Space between last choice-button and below game object.
    • space.choicesLeft, space.choicesRight : Extra left/right padding of choice buttons.
    • space.actionsLeft, space.actionsRight : Extra left/right padding of actions buttons.
    • space.toolbarItem : Space between each toolbar item game objects.
    • space.leftToolbarItem : Space between each left-toolbar item game objects.
    • space.choice : Space between each choice-button game objects.
    • space.choicesBackgroundLeft, space.choicesBackgroundRight, space.choicesBackgroundTop, space.choicesBackgroundBottom : Padding space around choices-background.
    • space.action : Space between each action-button game objects.
  • proportion : Keep height of element, or expand height of element.
    • proportion.title : Set to 1 to expand height of title. Default is 0.
    • proportion.content : Set to 1 to expand height of content. Default is 0.
    • proportion.description : Set to 1 to expand height of description. Default is 0.
    • proportion.choices : Set to 1 to expand height of choices. Default is 0.
    • proportion.actions : Set to 1 to expand height of actions. Default is 0.
  • expand : Expand width of element
    • expand.title : Set true to expand width of title game object. Default is true.
    • expand.content : Set true to expand width of content game object. Default is true.
    • expand.description : Set true to expand width of description game object. Default is true.
    • expand.choices : Set true to expand width of choices game object. Default is true.
    • expand.actions : Set true to expand width of actions game object. Default is false.
  • align : Align element
    • align.title
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value. Will add Spaces at right and left sides.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center. Will add a Space at right side.
    • align.content : Align content game object to 'left'/'center'/'right', if expand.content is false.
    • align.description : Align description game object to 'left'/'center'/'right', if expand.description is false.
    • align.choices : Align choices game object to 'left'/'center'/'right', if expand.choices is false.
    • align.actions : Align action game objects to 'left'/'center'/'right', if expand.actions is false.
  • click: Configuration of button clicking.
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false..
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-dialog/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDialog extends RexPlugins.UI.Dialog {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var dialog = new MyDialog(scene, config);\n
"},{"location":"ui-dialog/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

dialog.layout();\n

See also - dirty

"},{"location":"ui-dialog/#modal","title":"Modal","text":"

Pop this dialog as modal dialog, clicking any action button to close this modal dialog.

dialog.modal({\n// cover: {\n//     color: 0x0,\n//     alpha: 0.8,\n//     transitIn: function(gameObject, duration) { },\n//     transitOut: function(gameObject, duration) { },\n// },\n// cover: false, \n\n// When to close modal dialog?\n// touchOutsideClose: false,\n// anyTouchClose: false,\n// timeOutClose: false,\n// manualClose: false,\n\n// duration: {\n//     in: 200,\n//     hold: 2000,\n//     out: 200\n// }\n\n// transitIn: 0, // 0|'popUp'|1|'fadeIn'\n// transitIn: function(gameObject, duration) { },\n\n// transitOut: 0, // 0|'scaleDown'|1|'fadeOut'\n// transitOut: function(gameObject, duration) { },\n\n// destroy: true,\n\n// defaultBehavior: true,\n});\n// dialog.modal(config, onClose);\n

or

dialog\n.modalPromise(config)\n.then(function(data){\n\n})\n
  • config : See Modal behavior
    • config.defaultBehavior :
      • undefined, or true : Will close modal dialog when clicking any action button.
      • false : Disable default behavior. User has to invoke dialog.modalClose(data) manually.
  • onClose : Callback when closing modal dialog
    function(data) {\n// var index = data.index;\n// var text = data.text;\n// var button = data.button;\n// var dialog = data.dialog;\n}\n
    • data : Contains these properties
      • data.index : Index of clicking action button
      • data.text : button.text, this property is valided if button game object is a label.
      • data.button : Clicked button game object.
      • data.dialog : This dialog game object.
"},{"location":"ui-dialog/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-dialog/#events","title":"Events","text":"
  • Click button
    dialog.on('button.click', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
    or
    dialog.on('choice.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('action.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('toolbar.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('leftToolbar.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'choices', 'actions', or 'toolbar', 'leftToolbar'.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-over button
    dialog.on('button.over', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
    or
    dialog.on('choice.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('action.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('toolbar.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('leftToolbar.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Triggered button game object
    • groupName : 'choices', 'actions', 'toolbar', or 'leftToolbar'.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-out button
    dialog.on('button.out', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
    or
    dialog.on('choice.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('action.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('toolbar.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('leftToolbar.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'choices', 'actions', 'toolbar', or 'leftToolbar'
    • index : Index of triggered button game object.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Enable button's input
    dialog.on('button.enable', function(button, groupName, index) {\n// ...\n}, scope);\n
    or
    dialog.on('choice.enable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('action.enable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('toolbar.enable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('leftToolbar.enable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'choices', 'actions', 'toolbar', or 'leftToolbar'
    • index : Index of triggered button game object.
  • Disable button's input
    dialog.on('button.disable', function(button, groupName, index) {\n// ...\n}, scope);\n
    or
    dialog.on('choice.disable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('action.disable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('toolbar.disable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    dialog.on('leftToolbar.disable', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'choices', 'actions', 'toolbar', or 'leftToolbar'
    • index : Index of triggered button game object.
"},{"location":"ui-dialog/#emit-button-click-event","title":"Emit button click event","text":"
  • Emit choice/action/toolbar/left-toolbar button's click event
    dialog.emitChoiceClick(index);\ndialog.emitActionClick(index);\ndialog.emitToolbarClick(index);\ndialog.emitLeftToolbarClick(index);\n
    • index : A number index, or a button game object.
"},{"location":"ui-dialog/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = dialog.getElement('background');\n
    • Title game object
      var title = dialog.getElement('title');\n
    • Content game object
      var content = dialog.getElement('content');\n
    • Description game object
      var description = dialog.getElement('description');\n
    • Choice button game object
      var buttons = dialog.getElement('choices');\n
      or
      var button = dialog.getChoice(index);\n
      or
      var button = dialog.getElement('choices[' + index + ']');\n
    • Action button game object
      var buttons = dialog.getElement('actions');\n
      or
      var button = dialog.getAction(index);\n
      or
      var button = dialog.getElement('actions[' + index + ']');\n
    • Toolbar button game object
      var buttons = dialog.getElement('toolbar');\n
      or
      var button = dialog.getToolbar(index);\n
      or
      var button = dialog.getElement('toolbar[' + index + ']');\n
    • Left-toolbar button game object
      var buttons = dialog.getElement('leftToolbar');\n
      or
      var button = dialog.getLeftToolbar(index);\n
      or
      var button = dialog.getElement('leftToolbar[' + index + ']');\n
  • Get by name
    var gameObject = dialog.getElement('#' + name);\n// var gameObject = dialog.getElement('#' + name, recursive);\n
    or
    var gameObject = dialog.getByName(name);\n// var gameObject = dialog.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-dialog/#add-button","title":"Add button","text":"

Add choice/action/toolbar/left-toolbar button

dialog.addChoice(gameObject);\ndialog.addAction(gameObject);\ndialog.addToolbar(gameObject);\ndialog.addLeftToolbar(gameObject);\n
  • gameObject : A game object, or an array of game objects.
"},{"location":"ui-dialog/#remove-button","title":"Remove button","text":"
  • Remove a choice/action/toolbar/left-toolbar button
    dialog.removeChoice(index, destroyChild);\ndialog.removeAction(index, destroyChild);\ndialog.removeToolbar(index, destroyChild);\ndialog.removeLeftToolbar(index, destroyChild);\n
    • index : A number index, a string name, or a button game object.
    • destroyChild : Set true to destroy button game object.
  • Remove all choice/action/toolbar/left-toolbar buttons
    dialog.clearChoices(destroyChild);\ndialog.clearActions(destroyChild);\ndialog.clearToolbar(destroyChild);\ndialog.clearLeftToolbar(destroyChild);\n
    • destroyChild : Set true to destroy button game object.
"},{"location":"ui-dialog/#enabledisable-input-of-button","title":"Enable/disable input of button","text":"
  • Enable choice/action/toolbar/left-toolbar button
    dialog.setChoiceEnable(index);\ndialog.setActionEnable(index);\ndialog.setToolbarEnable(index);\ndialog.setLeftToolbarEnable(index);\n
    • index : A number index, or a button game object.
  • Enable all buttons
    dialog.setAllButtonsEnable();\n
  • Disable choice/action/toolbar/left-toolbar button's input
    dialog.setChoiceEnable(index, false);\ndialog.setActionEnable(index, false);\ndialog.setToolbarEnable(index, false);\ndialog.setLeftToolbarEnable(index, false);\n
    • index : A number index, or a button game object.
  • Disable all buttons
    dialog.setAllButtonsEnable(false);\n
  • Toggle choice/action/toolbar/left-toolbar button's input
    dialog.toggleChoiceEnable(index);\ndialog.toggleActionEnable(index);\ndialog.toggleToolbarEnable(index);\ndialog.toggleLeftToolbarEnable(index);\n
    • index : A number index, or a button game object.
  • Get choice/action/toolbar/left-toolbar button's input enable
    var enabled = dialog.getChoiceEnable(index);\nvar enabled = dialog.getActionEnable(index);\nvar enabled = dialog.getToolbarEnable(index);\nvar enabled = dialog.getLeftToolbarEnable(index);\n
    • index : A number index, or a button game object.
"},{"location":"ui-dialog/#showhide-button","title":"Show/hide button","text":"

Hidden elements won't be counted when layouting. Call dialog.layout(), or topSizer.layout() after show/hide any button.

  • Show choice/action/toolbar/left-toolbar button
    dialog.showChoice(index);\ndialog.showAction(index);\ndialog.showToolbar(index);\ndialog.showLeftToolbar(index);\n
    • index : A number index, a string name, or a button game object.
  • Hide choice/action/toolbar/left-toolbar button.
    dialog.hideChoice(index);\ndialog.hideAction(index);\ndialog.hideToolbar(index);\ndialog.hideLeftToolbar(index);\n
    • index : A number index, a string name, or a button game object.
"},{"location":"ui-dialog/#for-each-button","title":"For each button","text":"
dialog.forEachChoice(callback, scope);\ndialog.forEachAction(callback, scope);\ndialog.forEachToolbar(callback, scope);\ndialog.forEachLeftToolbar(callback, scope);\n
  • callback :
    function(button, index, buttons) {\n// ...\n}\n
"},{"location":"ui-dialog/#state-of-choices-buttons","title":"State of choices buttons","text":""},{"location":"ui-dialog/#radio","title":"Radio","text":"
  • Read state
    var value = dialog.getChoicesSelectedButtonName();\n
  • Set state
    dialog.setChoicesSelectedButtonName(name);\n
"},{"location":"ui-dialog/#checkboxes","title":"Checkboxes","text":"
  • Read states
    var states = dialog.getChoicesButtonStates();\n
    • states : {name: boolean}
  • Set state
    dialog.setChoicesButtonState(name, state);\n
    • name : Name of button game object
    • state : Set true if button is selected
  • Clear all states to false
    dialog.clearChoicesButtonStates();\n
"},{"location":"ui-dialog/#events_1","title":"Events","text":"
  • On button state changed. For Checkboxes/radio
    dialog.on('button.statechange', function(button, groupName, index, value, previousValue) {\n// ...\n}, scope);\n
    • Can be used to replace setValueCallback.
"},{"location":"ui-dropdownlist/","title":"Drop down list","text":""},{"location":"ui-dropdownlist/#introduction","title":"Introduction","text":"

A label can open a drop-down list panel.

  • Author: Rex
  • Game object
"},{"location":"ui-dropdownlist/#live-demos","title":"Live demos","text":"
  • Drop-down list
  • Drop-down wrap-list
  • Custom transit
  • Align to right side
  • Cursor select
  • Drop-down scrollable-list
"},{"location":"ui-dropdownlist/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-dropdownlist/#install-plugin","title":"Install plugin","text":""},{"location":"ui-dropdownlist/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add drop-down list object
    var dropDownList = scene.rexUI.add.dropDownList(config);\n
"},{"location":"ui-dropdownlist/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add drop-down list object
    var dropDownList = scene.rexUI.add.dropDownList(config);\n
"},{"location":"ui-dropdownlist/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { DropDownList } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add dropDownList object
    var dropDownList = new DropDownList(scene, config);\nscene.add.existing(dropDownList);\n
"},{"location":"ui-dropdownlist/#add-drop-down-list-object","title":"Add drop-down list object","text":"
var dropDownList = scene.rexUI.add.dropDownList({\noptions: [\noption0,\noption1,\n// ...\n],\n\nlist: {\n// createBackgroundCallback: function(scene) {\n//     // this : dropDownList\n//     return gameObject;\n// },\n\ncreateButtonCallback: function(scene, option, index, options) {\n// this : dropDownList\nreturn gameObject;\n},\n\n// createTrackCallback: function(scene) {\n//     // this : dropDownList\n//     return gameObject;\n// },\n\n// createThumbCallback: function(scene) {\n//     // this : dropDownList\n//     return gameObject;\n// },\n\nmouseWheelScroller: undefined,\n// mouseWheelScroller: {\n//     focus: true,\n//     speed: 0.1\n// },\n\nonButtonClick: function(button, index, pointer, event) {\n// this : dropDownList\n},\n\n// onButtonOver: function(button, index, pointer, event) {\n//     // this : dropDownList\n// },\n\n// onButtonOut: function(button, index, pointer, event) {\n//     // this : dropDownList\n// },\n\n// easeIn: 500,\n// transitIn: undefined,\n// transitIn: function(listPanel, duration) {  },\n\n// easeOut: 100,\n// transitOut: undefined,\n// transitOut: function(listPanel, duration) {  },\n\n// wrap: false,\n// maxHeight: undefined,\n// width: undefined, \n// height: undefined,\n// alignParent: 'text',\n// alignSide: '',\n// expandDirection: 0,\n// bounds: undefined,\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom: 0, item: 0,\n//     line: 0\n// },\n\n// draggable: false\n},\n\nsetValueCallback: function(dropDownList, value, previousValue) {\n\n},\nsetValueCallbackScope: undefined,\nvalue: undefined,\n\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\nicon: iconGameObject,\niconMask: false,\ntext: textGameObject,\nexpandTextWidth: false,\nexpandTextHeight: false,\naction: actionGameObject,\nactionMask: false,\nalign: undefined,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0,\ntext: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • options : Array of strings, or objects.
  • list : Configuration of list panel.
    • list.createBackgroundCallback : Create background of list panel
      function(scene) {\n// this : dropDownList\nreturn gameObject;\n}\n
    • list.createButtonCallback : Create option button of list panel
      function(scene, option, index, options) {\n// this : dropDownList\nreturn gameObject;\n}\n
    • list.createTrackCallback : Create slider's track of list panel, optional.
      function(scene) {\n// this : dropDownList\nreturn gameObject;\n}\n
    • list.createThumbCallback : Create slider's thumb of list panel, optional.
      function(scene) {\n// this : dropDownList\nreturn gameObject;\n}\n
    • list.mouseWheelScroller : Configuration of mouse-wheel-scroller behavior.
      • list.mouseWheelScroller.focus :
        • false, or 0 : Without checking if cursor is over game object or not.
        • true, or 1 : Cursor is inside the rectangle bounds of game object. Default behavior.
        • 2 : Cursor is over game object.
      • list.mouseWheelScroller.speed : Scrolling speed, default value is 0.1.
      • Set to false to skip creating mouse-wheel-scroller. Default behavior.
    • list.onButtonClick : Callback when clicking a button
      function(button, index, pointer, event) {\n// this : dropDownList\n}\n
    • list.onButtonOver : Callback when pointer over a button
      function(button, index, pointer, event) {\n// this : dropDownList\n}\n
    • list.onButtonOut : Callback when pointer out a button
      function(button, index, pointer, event) {\n// this : dropDownList\n}\n
    • list.easeIn : Pop-up duration in ms. Default value is 500.
    • list.transitIn : Tween behavior of opening list panel.
      • undefined : Expand list panel by pop-up, default behavior.
      • Custom callback
        function(listPanel, duration) {\n\n}\n
    • list.easeOut : Scale-down duration in ms. Default value is 100.
    • list.transitOut : Tween behavior of closing list panel.
      • undefined : Closing list panel by scale-down, default behavior.
      • Custom callback
        function(listPanel, duration) {\n\n}\n
    • list.wrap : Layout mode of buttons
      • true : fixwidth-sizer layout.
      • false : sizer layout. Default behavior.
    • list.maxHeight : If height of button list is larger than this maxHeight, put this button list into scrollable panel.
      • undefined, or 0 : Ignore this behavior.
      • > 0 and list.createThumbCallback parameter is given : If height of button list is larger than this maxHeight, put this button list into scrollable panel.
    • list.width : Minimum width.
      • undefined : Minimum width of panel will equal to width of parent label. Default value.
      • A number : Width of panel. Required fields when list.wrap is true.
    • list.height : Minimum height.
      • undefined : Create button list or wrap button list. Default value.
      • > 0 and list.createThumbCallback parameter is given : Create scrollable button list or wrap button list.
    • list.alignParent : Align x position to label.
      • 'icon' : Align x position to icon game object of parent label.
      • 'text' : Align x position to text game object of parent label. Default behavior
      • 'label', or null : Align x position to parent label.
    • list.alignSide : Align list to label's left or right side.
      • undefined, or 'left' : Align list's left side to label's left side. Default behavior.
      • 'right : Align list's right side to label's right side. Default behavior.
    • list.expandDirection :
      • 0, 'down' : Expand list down. i.e. list panel will put below parent label.
      • 1, 'up' : Expand list up. i.e. list panel will put above parent label.
    • list.bounds : Put list panel below parent label if bottom of list panel is inside bounds (Rectangle)
      • undefined : Use viewport as bounds
      • Rectangle
    • list.space : space properties of list panel.
      • left, right, top, bottom, item : For sizer layout. (list.wrap is false)
      • left, right, top, bottom, item, line : For fixwidth-sizer layout. (list.wrap is true)
    • list.draggable : Set true to drag top-most object.
  • value, setValueCallback, setValueCallbackScope : See value
    function(dropDownList, value, previousValue) {\n\n}\n
  • Properties of Label
    • x, y : Position of this object, it is valid when this object is the top object.
    • anchor : See anchor.
      • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
        • Percentage of visible width/height : 'p%', p: 0 ~ 100.
          • 'left'(=0%), 'center'(=50%), 'right'(=100%)
          • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
        • Offset : '+n', or '-n'.
      • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
        • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • Padding : '+n', or '-n'.
      • onResizeCallback : A default resize callback will be assigned interanlly.
    • width, height : Minimum width, minimum height.
    • orientation :
      • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
      • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
    • rtl :
      • true : Layout children from right to left.
      • false : Layout children from left to right. Default behavior.
    • background : Game object of background, optional. This background game object will be resized to fit the size of label.
    • icon : Game object of icon, optional.
    • iconMask : Set true to add a circle mask on icon game object.
      • Phaser 3 engine does not support nested mask, uses circle mask image instead.
    • text : Game object of text, optional.
    • expandTextWidth : Set true to expand width of text object.
    • expandTextHeight : Set true to expand height of text object.
    • action : Game object of action icon, optional.
    • actionMask : Set true to add a circle mask on action icon game object.
      • Phaser 3 engine does not support nested mask, uses circle mask image instead.
    • align : Alignment of icon, text, action-icon game objects.
      • undefined, or 'left', or 'top' : Align game objects at left, or top.
      • 'center' : Align game objects at center.
      • 'right', or 'bottom' : Align game objects at right, or bottom.
    • space : Pads spaces.
      • space.left, space.right, space.top, space.bottom : Space of bounds.
      • space.icon : Space between icon game object and text game object.
      • space.text : Space between text game object and action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-dropdownlist/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDropDownList extends RexPlugins.UI.DropDownList {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var dropDownList = new MyDropDownList(scene, config);\n
"},{"location":"ui-dropdownlist/#options","title":"Options","text":"
  • Set
    dropDownList.setOptions(options);\n
    or
    dropDownList.options = options;\n
    • options : Array of strings, or objects.
  • Get
    var options = dropDownList.options;\n
"},{"location":"ui-dropdownlist/#clicking","title":"Clicking","text":"
  • Enable
    dropDownList.enableClick();\n
  • Disable
    dropDownList.disableClick();\n
  • Register another clicking callback
    dropDownList.onClick(callback, scope);\n
"},{"location":"ui-dropdownlist/#emit-button-click-event","title":"Emit button click event","text":"
dropDownList.emitButtonClick(index);\n// dropDownList.emitButtonClick();\n
  • index : Index of button/option.
    • undefined : Click current focus (over) button.

Will fire 'button.click' event

dropDownList.on('button.click', function(dropDownList, listPanel, button, index, pointer, event) {\n// ...\n}, scope);\n
  • listPanel : listPanel, or undefined if list is not created.
  • button : Button game object, or option if list is not created.
  • pointer : undefined
  • event : undefined

This method won't close list panel.

"},{"location":"ui-dropdownlist/#emit-button-over-event","title":"Emit button over event","text":"
dropDownList.emitButtonOver(index);\n
  • index : Index of button/option.

or

dropDownList.focusNextButton();\ndropDownList.focusPrevButton();\n

Will fire 'button.out', 'button.over' event

dropDownList.on('button.out', function(dropDownList, listPanel, button, index, pointer, event) {\n// ...\n}, scope);\n
dropDownList.on('button.over', function(dropDownList, listPanel, button, index, pointer, event) {\n// ...\n}, scope);\n

  • listPanel : listPanel, or undefined if list is not created.
  • button : Button game object, or option if list is not created.
  • pointer : undefined
  • event : undefined
"},{"location":"ui-dropdownlist/#value","title":"Value","text":"
  • Set value under list.onButtonClick callback.
    dropDownList.setValue(value);\n
    or
    dropDownList.value = value;\n
    • When value changing
      • Will invoke setValueCallback
        function(dropDownList, value, previousValue) {\n\n}\n
      • Will fire 'valuechange' event
  • Get
    var value = dropDownList.value;\n
"},{"location":"ui-dropdownlist/#openclose-list-panel","title":"Open/close list panel","text":""},{"location":"ui-dropdownlist/#open-list-panel","title":"Open list panel","text":"
  • Click parent label to open (create and pop-up) list panel.
  • Or invoke this method dropDownList.openListPanel().
"},{"location":"ui-dropdownlist/#close-list-panel","title":"Close list panel","text":"
  • When list panel is opened, click any where will close (scale-down then destroy) this list panel.
  • Or invoke this method dropDownList.closeListPanel().
"},{"location":"ui-dropdownlist/#toggle-list-panel","title":"Toggle list panel","text":"
dropDownList.toggleListPanel();\n
"},{"location":"ui-dropdownlist/#is-list-opened","title":"Is list opened","text":"
var isOpened = dropDownList.isOpened;\n
"},{"location":"ui-dropdownlist/#other-properties","title":"Other properties","text":"

See label object, sizer object, base sizer object, container-lite.

"},{"location":"ui-dropdownlist/#events","title":"Events","text":"
  • Open list
    dropDownList.on('list.open', function(dropDownList, listPanel) {\n\n})\n
  • Close list
    dropDownList.on('list.close', function(dropDownList, listPanel) {\n\n})\n
  • Click button
    dropDownList.on('button.click', function(dropDownList, listPanel, button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Game object of triggered button on list panel.
    • index : Index of triggered button.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Over button
    dropDownList.on('button.over', function(dropDownList, listPanel, button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Game object of triggered button on list panel.
    • index : Index of triggered button.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Out button
    dropDownList.on('button.out', function(dropDownList, listPanel, button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Game object of triggered button on list panel.
    • index : Index of triggered button.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • On value changing
    dropDownList.on('valuechange', function(dropDownList, value, previousValue) {\n// ...\n}, scope);\n
"},{"location":"ui-expbar/","title":"Exp bar","text":""},{"location":"ui-expbar/#introduction","title":"Introduction","text":"

Disply experience bar on NameValueLabel.

  • Author: Rex
  • Game object
"},{"location":"ui-expbar/#live-demos","title":"Live demos","text":"
  • Exp bar
  • Custom bar
"},{"location":"ui-expbar/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-expbar/#install-plugin","title":"Install plugin","text":""},{"location":"ui-expbar/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add expBar object
    var expBar = scene.rexUI.add.expBar(config);\n
"},{"location":"ui-expbar/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add expBar object
    var expBar = scene.rexUI.add.expBar(config);\n
"},{"location":"ui-expbar/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ExpBar } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add expBar object
    var expBar = new ExpBar(scene, config);\nscene.add.existing(expBar);\n
"},{"location":"ui-expbar/#add-expbar-object","title":"Add expBar object","text":"
var expBar = scene.rexUI.add.expBar({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\nicon: iconGameObject,\niconMask: false,\n\nnameText: nameTextGameObject,\nvalueText: valueTextGameObject,\n// valueTextFormatCallback: function(value, min, max) {\n//     return `${value}/${max}`;\n// },\n// valueTextFormatCallback: null,\n\n// barShape: 'line',   // 'line', or 'circle'\n\n// line bar\nbar: {\ntrackColor: undefined,\ntrackThickness: 2,\ntrackStrokeColor: undefined,\nbarColor: undefined,\nbarColor2: undefined,\n\nskewX: 0,\n\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'linear'\n},\n}, // circle bar\n/*\n    bar: {\n        barColor: undefined,\n        barColor2: undefined,\n        trackColor: undefined,\n        centerColor: undefined,\n        thickness: 0.2,\n        startAngle: Phaser.Math.DegToRad(270),\n        endAngle: Phaser.Math.DegToRad(270+360),\n        anticlockwise: false,\n    }\n    */\n\n// bar: CustomProgressGameObject,\n\n// bar: undefined,\n\naction: actionGameObject,\nactionMask: false,\n\nalign: {        text: 'bottom',  // 'top', 'center', 'bottom'\n},\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0, iconTop: 0, iconBottom: 0,\nname: 0, value: 0,\nbar:0, barBottom: 0, barLeft: 0, barRight: 0,\ntext: 0,\nactionTop: 0, actionBottom: 0,\n},\n\n// easeDuration: 1000,\n\nlevelCounter: {\ntable: function(level) { return level * 100; },\n// table: [0, 100, 200, 300,],        \n// maxLevel: -1,        \n// exp: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of expBar.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • nameText : Game object of nameText.
    • OriginX of nameText will be set to 0.
    • Empty text will be set to a space character ' '. To preserve height of this text game object.
  • valueText : Game object of valueText.
    • OriginX of nameText will be set to 1.
    • Empty text will be set to a space character ' '. To preserve height of this text game object.
  • valueTextFormatCallback : Callback to return a string set to valueText game object when invokeing label.setValue(value, min, max) method.
    • A callback
      function(value, min, max) {\nreturn `${value}/${max}`;\n}\n
    • null, or false : Don't set valueText game object.
  • barShape : 'line' or 'circle'.
  • bar : Game object of bar, or config of horizontal line progress bar, or config of circular progress bar or undefined.
    • Config of horizontal line progress bar
      • bar.trackColor : Fill color of bar's track, in number or css string value.
      • bar.trackStrokeColor : Stroke color of bar's track, in number or css string value.
      • bar.trackThickness : Stroke line width of bar's track.
      • bar.barColor, bar.barColor2 : Fill color of bar, in number or css string value. Assign gradient start color by barColor2.
      • bar.skewX : Horizontal skew of track and bar.
      • bar.rtl :
        • false : Bar starts from left side. Default behavior.
        • true : Bar starts from right side.
    • Config of circular progress bar
      • bar.shape : 'circle'
      • bar.barColor, bar.barColor2 : Fill color of circular bar, in number or css string value. Assign gradient start color by barColor2.
      • bar.trackColor : Color of circular track, in number or css string value.
      • bar.centerColor : Color of center circle, in number or css string value.
      • bar.thickness : 0 ~ 1, thickness of circular bar. Default value is 0.2 (0.2*radius)
      • bar.startAngle : Start angle of circular bar, in radians. Default value is 270 degrees.
      • bar.endAngle : End angle of circular bar, in radians. Default value is 270+360 degrees.
      • bar.anticlockwise : Set true to put anticlockwise circular bar. Default value is false.
    • (CustomProgress) Game object.
    • undefined : No bar game object.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • align :
    • align.text : Alignment of nameText, valueText game objects.
      • 'top', 'center', or 'bottom'. Default value is 'bottom'.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.icon : Space between icon game object and text game object.
    • space.iconTop, space.iconBottom : Space around icon game object.
    • space.name : Left space of nameText game object.
    • space.value : Right space of valueText game object.
    • space.bar, space.barLeft, space.barRight, space.barBottom : Space around bar game object.
    • space.text : Space between text game object and action icon game object.
    • space.actionTop, space.actionBottom : Space around action game object.
  • easeDuration : Total duration of easing value from level-start to level-end. Default value is 1000 ms.
  • levelCounter : Config of level-counter
    • levelCounter.table : Level table, return experience value from level value. Level value starts from 0.
      • A callback
        function(level) {\nreturn experience;\n}\n
      • A number array : Experience value of each level.
    • levelCounter.maxLevel :
      • undefined : Default value
        • No upper limit for callback level table.
        • (table.length - 1) for number array level table.
      • A number : Maximum level value
    • levelCounter.exp : Initial experience value. Default value is 0.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-expbar/#custom-class","title":"Custom class","text":"
  • Define class
    class MyExpBar extends RexPlugins.UI.ExpBar {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var expBar = new MyExpBar(scene, config);\n
"},{"location":"ui-expbar/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

expBar.layout();\n

See also - dirty

"},{"location":"ui-expbar/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = expBar.getElement('background');\n
    • Icon game object
      var icon = expBar.getElement('icon');\n
    • NameText game object
      var nameTextObject = expBar.getElement('name');\n
    • ValueText game object
      var valueTextObject = expBar.getElement('value');\n
    • Bar game object
      var textObject = expBar.getElement('bar');\n
    • Action icon game object
      var action = expBar.getElement('action');\n
  • Get by name
    var gameObject = expBar.getElement('#' + name);\n// var gameObject = expBar.getElement('#' + name, recursive);\n
    or
    var gameObject = expBar.getByName(name);\n// var gameObject = expBar.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-expbar/#accumulate-experience","title":"Accumulate experience","text":"
  • Accumulate experience
    expBar.gainExp(incExp);\n// expBar.exp += incExp;\n
    • Will fire 'levelup' event
  • Reset experience value
    expBar.resetExp(exp);\n
    • Won't fire 'levelup' event.
  • Force level up
    expBar.setLevel(level);\n
    • Will fire 'levelup' event
"},{"location":"ui-expbar/#level-and-experience","title":"Level and experience","text":"
  • Get current experience
    var exp = expBar.getExp();\n// var exp = expBar.exp;\n
  • Get current level
    var level = expBar.getLevel();\n// var level = expBar.level;\n
  • Get current required experience to next level
    var exp = expBar.requiredExp;\n
  • Get experience of level
    var exp = expBar.getExp(level);\n
  • Get level from experience
    var level = expBar.getLevel(exp);\n
  • Get required experience to level
    var exp = expBar.getRequiredExpToNextLevel(level);\n// var exp = expBar.getRequiredExpToNextLevel(level, exp);\n
"},{"location":"ui-expbar/#events","title":"Events","text":"
  • Easing starting of Level-up
    expBar.on('levelup.start', function(level, fromExp, toExp){        }, scope);\n
    • level : Current level
  • Easing end of Level-up
    expBar.on('levelup.end', function(level, fromExp, toExp){        }, scope);\n
    • level : Current level
  • Total easing of Level-up complete
    expBar.on('levelup.complete', function(level){        }, scope);\n
    • level : Current level
"},{"location":"ui-expbar/#other-properties","title":"Other properties","text":"

See NameValueLabel, sizer object, base sizer object, container-lite.

"},{"location":"ui-fileselectorbutton/","title":"File selector button","text":""},{"location":"ui-fileselectorbutton/#introduction","title":"Introduction","text":"

A transparent file chooser button (<input type=\"file\">) above a Label.

  • Author: Rex
  • Game object, DOM Game object
"},{"location":"ui-fileselectorbutton/#live-demos","title":"Live demos","text":"
  • File selector button
"},{"location":"ui-fileselectorbutton/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-fileselectorbutton/#install-plugin","title":"Install plugin","text":""},{"location":"ui-fileselectorbutton/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add file selector button object
    var button = scene.add.fileSelectorButton(config);\n
"},{"location":"ui-fileselectorbutton/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import FileChooserPlugin from 'phaser3-rex-plugins/plugins/filechooser-plugin.js';\nvar config = {    parent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add file selector button object
    var button = scene.add.fileSelectorButton(config);\n
"},{"location":"ui-fileselectorbutton/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import { FileSelectorButton } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add file chooser object
    var button = new FileSelectorButton(scene, config);\nscene.add.existing(button);\n
"},{"location":"ui-fileselectorbutton/#add-file-chooser-object","title":"Add file chooser object","text":"
var button = scene.add.fileSelectorButton({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\n\nicon: iconGameObject,\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntext: textGameObject,\nexpandTextWidth: false,\nexpandTextHeight: false,\n\naction: actionGameObject,\n// actionMask: false,\n// squareFitAction: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nalign: undefined,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0,\ntext: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n\n// accept: '',\n// multiple: false,\n});\n// var fileChooser = scene.add.fileSelectorButton(x, y, width, height, config);\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • squareFitIcon :
    • true : Resize icon size to square to fit label height/width.
    • false : Ignore this feature. Default behavior.
  • iconSize : Set display size of icon game object to iconSizexiconSize
  • iconWidth : Set display width of icon game object to iconWidth.
    • If iconHeight is undefined, set scaleY of icon game object to scaleX of icon game object, to keep size ratio.
  • iconHeight : Set display height of icon game object to iconHeight.
    • If iconWidth is undefined, set scaleX of icon game object to scaleY of icon game object, to keep size ratio.
  • text : Game object of text, optional.
  • expandTextWidth :
    • false : Keep width of text to original size. Default behavior.
    • true : Expand width of text object. Will set display width by default.
      • Must set to true if using scene.rexUI.wrapExpandText method with any text game object.
  • expandTextHeight : Set true to expand height of text object.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • squareFitAction :
    • true : Resize action icon size to square to fit label height/width.
    • false : Ignore this feature. Default behavior.
  • actionSize : Set display size of action game object to actionSizexactionSize
  • actionWidth : Set display width of action game object to actionWidth.
    • If actionHeight is undefined, set scaleY of action game object to scaleX of action game object, to keep size ratio.
  • actionHeight : Set display height of action game object to actionHeight.
    • If actionWidth is undefined, set scaleX of action game object to scaleY of action game object, to keep size ratio.
  • align : Alignment of icon, text, action game objects.
    • undefined, or 'left', or 'top' : Align game objects at left, or top.
    • 'center' : Align game objects at center.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.icon : Space between icon game object and text game object.
    • space.text : Space between text game object and action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • accept : A filter for what file types the user can pick from the file input dialog box.
    • 'image/*' : The user can pick all image files.
    • 'audio/*' : The user can pick all sound files.
    • 'video/*' : The user can pick all video files.
    • file_extension : Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can pick from.
  • multiple : Set true to select multiple files.
"},{"location":"ui-fileselectorbutton/#custom-class","title":"Custom class","text":"
  • Define class
    class MyFileSelectorButton extends RexPlugins.UI.FileSelectorButton {\nconstructor(scene, config) {\nsuper(scene, config) {\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var button = new MyFileSelectorButton(scene, config);\n
"},{"location":"ui-fileselectorbutton/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

label.layout();\n

See also - dirty

"},{"location":"ui-fileselectorbutton/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = label.getElement('background');\n
    • Icon game object
      var icon = label.getElement('icon');\n
    • Text game object
      var textObject = label.getElement('text');\n
    • Action icon game object
      var action = label.getElement('action');\n
    • File chooser game object
      var fileChooser = label.getElement('fileChooser');\n
  • Get by name
    var gameObject = label.getElement('#' + name);\n// var gameObject = label.getElement('#' + name, recursive);\n
    or
    var gameObject = label.getByName(name);\n// var gameObject = label.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-fileselectorbutton/#selected-files","title":"Selected files","text":"
var files = fileChooser.files;\n
  • files : Array of file object.
"},{"location":"ui-fileselectorbutton/#set-accept-filter","title":"Set accept filter","text":"
fileChooser.setAccept(accept);\n
  • accept : A filter for what file types the user can pick from the file input dialog box.
    • 'image/*' : The user can pick all image files.
    • 'audio/*' : The user can pick all sound files.
    • 'video/*' : The user can pick all video files.
    • file_extension : Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can pick from.
"},{"location":"ui-fileselectorbutton/#multiple-files","title":"Multiple files","text":"
  • Enable
    fileChooser.setMultiple();\n
  • Disable
    fileChooser.setMultiple(false);\n
"},{"location":"ui-fileselectorbutton/#events","title":"Events","text":"
  • Selected file(s) changed
    button.on('select', function(files, button) {        var file = files[0];\nvar url = URL.createObjectURL(file);\n// ...\n})\n
"},{"location":"ui-fileselectorbutton/#load-file-to-cache","title":"Load file to cache","text":"
fileChooser.loadFile(file, loaderType, key);\n// fileChooser.loadFile(file, loaderType, key, cahceType);\n

or

fileChooser.loadFilePromise(file, loaderType, key, cahceType)\n.then(function(content) {\n\n})\n
  • file : File object, see Events
  • loaderType : image, text, binary, ... See Loader
  • key : Unique string key.
  • cahceType :
    • undefined : Use default value.
  • content : Content of file.
"},{"location":"ui-fileselectorbutton/#create-object-url","title":"Create object URL","text":"
  • Create object url
    var objectURL = URL.createObjectURL(file);\n
  • Release object url
    URL.createObjectURL(objectURL);\n
"},{"location":"ui-fileselectorbutton/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"

See dom-element's Interactive with other game objects

"},{"location":"ui-fileselectorbutton/#other-properties","title":"Other properties","text":"

See label object, sizer object, base sizer object, container-lite.

"},{"location":"ui-fixwidthbuttons/","title":"Fix-width buttons","text":""},{"location":"ui-fixwidthbuttons/#introduction","title":"Introduction","text":"

A container with a group of fix-width buttons.

  • Author: Rex
  • Game object
"},{"location":"ui-fixwidthbuttons/#live-demos","title":"Live demos","text":"
  • Checkboxes/radio
  • Indent left
  • Indent top
"},{"location":"ui-fixwidthbuttons/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-fixwidthbuttons/#install-plugin","title":"Install plugin","text":""},{"location":"ui-fixwidthbuttons/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add fix-Width buttons object
    var buttons = scene.rexUI.add.fixWidthButtons(config);\n
"},{"location":"ui-fixwidthbuttons/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add fix-Width buttons object
    var buttons = scene.rexUI.add.fixWidthButtons(config);\n
"},{"location":"ui-fixwidthbuttons/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { FixWidthButtons } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add fix-Width buttons object
    var buttons = new FixWidthButtons(scene, config);\nscene.add.existing(buttons);\n
"},{"location":"ui-fixwidthbuttons/#add-buttons-object","title":"Add Buttons object","text":"
var buttons = scene.rexUI.add.fixWidthButtons({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\n// background: backgroundGameObject,\n\nbuttons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\n// rtl: false,\nalign: 0,\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n},\n\n// space: 0,\n// space: {\n//     left: 0, right: 0, top: 0, bottom: 0,\n//     item: 0, line: 0,\n//     indentLeftOdd: 0, indentLeftEven: 0,\n//     indentTopOdd: 0, indentTopEven: 0,\n// },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n// eventEmitter: this,\n// groupName: undefined,\n\n// buttonsType: undefined,\n// setValueCallback: undefined,  // or setButtonStateCallback: undefined\n// setValueCallbackScope: undefined  // or setButtonStateCallbackScope: undefined\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of grid table.
  • buttons : 1d/2d array of button game objects.
  • align : Align children of a line.
    • 0, 'left' : Align children of a line to left/top side.
    • 1, 'right' : Align children of a line to right/bottom side.
    • 2, 'center' : Align children of a line to ceter.
    • 3, 'justify', 'justify-left' : If remainder space is less or equal than 25%, then justify children. Else align children to left/top side.
    • 4, 'justify-right' : If remainder space is less or equal than 25%, then justify children. Else align children to right/bottom side.
    • 5, 'justify-cneter' : If remainder space is less or equal than 25%, then justify children. Else align children to center.
  • click: Configuration of button clicking.
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
  • space :
    • A number: Space between 2 button game objects.
    • An object: Padding of button game objects.
      • space.left, space.right, space.top, space.bottom : Space of bounds.
      • space.item : Space betwen each child of a line.
      • space.line : Space between each line.
      • space.indentLeftOdd, space.indentLeftEven : Indent at each odd/even line.
      • space.indentTopOdd, space.indentTopEven : Indent at each odd/even item.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • eventEmitter : Dispatch buttons' touch events to other game obhect, default is this buttons game object.
  • groupName : Optional group name for argument of touch events.
  • buttonsType : Type/behavior of these buttons.
    • undefined : No extra behavior, default value.
    • 'checkboxes' : Set these buttons to checkboxes.
    • 'radio' : Set these buttons to radio.
  • setValueCallback or setButtonStateCallback : Callback to set value of a button.
    • undefined : No callback, default value.
    • A function object.
      function(button, value, previousValue) {\n// ...\n}\n
      • button : Button game object.
      • value: true, or false.
      • previousValue : true, or false.
"},{"location":"ui-fixwidthbuttons/#custom-class","title":"Custom class","text":"
  • Define class
    class MyButtons extends RexPlugins.UI.FixWidthButtons {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var buttons = new MyButtons(scene, config);\n
"},{"location":"ui-fixwidthbuttons/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

buttons.layout();\n

See also - dirty

"},{"location":"ui-fixwidthbuttons/#other-properties","title":"Other properties","text":"

See sizer object

"},{"location":"ui-fixwidthbuttons/#events","title":"Events","text":"
  • Click button
    buttons.on('button.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.click', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
    • groupName : Optional group name.
    • button : Triggered button game object.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-over button
    buttons.on('button.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.over', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Pointer-out button
    buttons.on('button.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    or
    buttons.on('button.out', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Enable button's input
    buttons.on('button.enable', function(button, index) {\n// ...\n}, scope);\n
    or
    buttons.on('button.enable', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
  • Disable button's input
    buttons.on('button.disalbe', function(button, index) {\n// ...\n}, scope);\n
    or
    buttons.on('button.disalbe', function(button, groupName, index, pointer, event) {\n// ...\n}, scope);\n
"},{"location":"ui-fixwidthbuttons/#emit-button-click-event","title":"Emit button click event","text":"
buttons.emitButtonClick(index);\n
  • index : Index of triggered button game object, or a button game object.
"},{"location":"ui-fixwidthbuttons/#enabledisable-input-of-button","title":"Enable/disable input of button","text":"
  • Enable a button's input
    buttons.setButtonEnable(index);\n// buttons.setButtonEnable(index, true);\n
    • index : Index of triggered button game object, or a button game object.
  • Enable all buttons' input
    buttons.setButtonEnable();\n// buttons.setButtonEnable(true);\n
  • Disable
    buttons.setButtonEnable(index, true);\n
    • index : Index of triggered button game object, or a button game object.
  • Disable all buttons' input
    buttons.setButtonEnable(false);\n
  • Toggle
    buttons.toggleButtonEnable(index);\n
  • Toggle all buttons's input
    buttons.toggleButtonEnable();\n
  • Get button's input enable
    var enabled = bottons.getButtonEnable(index);\n
"},{"location":"ui-fixwidthbuttons/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = buttons.getElement('background');\n
    • Button game objects
      var buttonObjects = buttons.getElement('buttons');\n
      or
      var buttonObject = buttons.getButton(index);\n
      or
      var buttonObjects = buttons.getElement('buttons[0]'); // First button\n
  • Get by name
    var gameObject = buttons.getElement('#' + name);\n// var gameObject = buttons.getElement('#' + name, recursive);\n
    or
    var gameObject = buttons.getByName(name);\n// var gameObject = buttons.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-fixwidthbuttons/#add-child","title":"Add child","text":"
  • Add button child
    buttons.addButton(gameObject)\n
    • gameObject : A game object, or an array of game objects.
  • Add non-button child, see fixWidthSizer.add() method.
    buttons.add(gameObject,\n{\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nkey: undefined,\nindex: undefined\n}\n)\n
"},{"location":"ui-fixwidthbuttons/#remove-child","title":"Remove child","text":"
  • Remove button child
    buttons.removeButton(gameObject, destroyChild);\n
    • gameObject :
      • Game object, or array of game objects : Button game object.
      • A number, or array of numbers : Index of button game object.
      • A string, or array of strings : Name of button game object.
    • destroyChild : Set true to destroy button game object.
  • Remove all buttton children
    buttons.clearButtons(destroyChild);\n
    • destroyChild : Set true to destroy button game objects.
  • Remove a button or non-button child, see fixWidthSizer.remove() method.
    buttons.remove(gameObject, destroyChild);\n
  • Remove all button or non-button children, see fixWidthSizer.remove() method.
    buttons.removeAll(destroyChild);\n
"},{"location":"ui-fixwidthbuttons/#showhide-button","title":"Show/hide button","text":"

The same as for each button of buttons.

"},{"location":"ui-fixwidthbuttons/#for-each-button","title":"For each button","text":"

The same as for each button of buttons.

"},{"location":"ui-fixwidthbuttons/#checkboxesradio","title":"Checkboxes/radio","text":"

The same as checkboxes/radio of buttons.

"},{"location":"ui-fixwidthsizer/","title":"Fix-width sizer","text":""},{"location":"ui-fixwidthsizer/#introduction","title":"Introduction","text":"

Layout children game objects into lines.

  • Author: Rex
  • Game object
"},{"location":"ui-fixwidthsizer/#live-demos","title":"Live demos","text":"
  • Fix-width sizer
  • Scrollable, fix-width sizer
  • Indent
  • Drag-drop item
  • Set children interactive
  • vertical & horizontal
"},{"location":"ui-fixwidthsizer/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-fixwidthsizer/#install-plugin","title":"Install plugin","text":""},{"location":"ui-fixwidthsizer/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add sizer object
    var sizer = scene.rexUI.add.fixWidthSizer(config);\n
"},{"location":"ui-fixwidthsizer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add sizer object
    var sizer = scene.rexUI.add.fixWidthSizer(config);\n
"},{"location":"ui-fixwidthsizer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { FixWidthSizer } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add sizer object
    var sizer = new FixWidthSizer(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-fixwidthsizer/#add-sizer-object","title":"Add sizer object","text":"
var sizer = scene.rexUI.add.fixWidthSizer({\n// x: 0,\n// y: 0,\n// anchor: undefined,    \n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// orientation: 0,\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom: 0,\n//     item: 0, line: 0, \n//     indentLeftOdd: 0, indentLeftEven: 0,\n// },\n\n// rtl: false,\n// align: 0,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n

or

var sizer = scene.rexUI.add.fixWidthSizer(x, y, {\n// width: 2,\n// height: 2\n// orientation: 0,\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom: 0,\n//     item: 0, line: 0,\n//     indentLeftOdd: 0, indentLeftEven: 0,\n//     indentTopOdd: 0, indentTopEven: 0,\n// },\n\n// rtl: false,\n// align: 0,\n\n// name: '',\n// draggable: false\n});\n

or

var sizer = scene.rexUI.add.fixWidthSizer(x, y, width, height, {\n// orientation: 0,\n// space: {\n//     left: 0, right: 0, top: 0, bottom: 0,\n//     item: 0, line: 0\n// },\n\n// rtl: false,\n// align: 0,\n\n// name: '',\n// draggable: false\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation : Orientation of the sizer.
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Arrange game objects from left ot right. Default value is 0.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Arrange game objects from top to bottom.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space betwen each child of a line.
    • space.line : Space between each line.
    • space.indentLeftOdd, space.indentLeftEven : Indent at each odd/even line.
    • space.indentTopOdd, space.indentTopEven : Indent at each odd/even item.
  • rtl : Order of children in each line.
    • false : Place children from left-to-right/top-to-bottom, default value.
    • true : Place children from right-to-left/bottom-to-top.
  • align : Align children of a line.
    • 0, 'left' : Align children of a line to left/top side.
    • 1, 'right' : Align children of a line to right/bottom side.
    • 2, 'center' : Align children of a line to ceter.
    • 3, 'justify', 'justify-left' : If remainder space is less or equal than 25%, then justify children. Else align children to left/top side.
    • 4, 'justify-right' : If remainder space is less or equal than 25%, then justify children. Else align children to right/bottom side.
    • 5, 'justify-cneter' : If remainder space is less or equal than 25%, then justify children. Else align children to center.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-fixwidthsizer/#custom-class","title":"Custom class","text":"
  • Define class
    class MySizer extends RexPlugins.UI.FixWidthSizer {\nconstructor(scene, x, y, minWidth, minHeight, orientation, space, config) {\nsuper(scene, x, y, minWidth, minHeight, orientation, space, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var sizer = new MySizer(scene, x, y, minWidth, minHeight, orientation, space, config);\n
"},{"location":"ui-fixwidthsizer/#add-background","title":"Add background","text":"
sizer.addBackground(child);\n

or

sizer.addBackground(child, {left: 0, right: 0, top: 0, bottom: 0}, key);\n
  • left, right, top, bottom : Extra padded space. Default is 0.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
"},{"location":"ui-fixwidthsizer/#add-child","title":"Add child","text":"

Add a game obejct to sizer

sizer.add(child);\n

or

sizer.add(child,\n{\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nkey: undefined,\nindex: undefined\n}\n);\n

or

sizer.add(child, padding, key, index);\n
  • child : A game object
  • padding : Add space between bounds. Default is 0.
    • A number for left/right/top/bottom bounds
    • Or a plain object
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
    • items : Reserved key, for all children item.
  • index : Insert child to.
    • undefined : Insert child at last.
"},{"location":"ui-fixwidthsizer/#insert-child","title":"Insert child","text":"
sizer.insert(index, child, {\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nkey: undefined,\n}\n);\n

or

sizer.insert(index, child, padding, key);\n
"},{"location":"ui-fixwidthsizer/#insert-at-position","title":"Insert at position","text":"
sizer.insertAtPosition(x, y, child, {\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nkey: undefined,\n}\n);\n

or

sizer.insertAtPosition(x, y, index, child, padding, key);\n
"},{"location":"ui-fixwidthsizer/#add-new-line","title":"Add new line","text":"
sizer.addNewLine();\n
"},{"location":"ui-fixwidthsizer/#layout-children","title":"Layout children","text":"

Arrange position of all children.

sizer.layout();\n

See also - dirty

"},{"location":"ui-fixwidthsizer/#hide","title":"Hide","text":"
  • Set invisible, won't layout it
    sizer.hide();\n
    or
    sizer.hide(gameObject);\n
  • Set visible, will layout it
    sizer.show();\n
    or
    sizer.show(gameObject);\n
"},{"location":"ui-fixwidthsizer/#remove-child","title":"Remove child","text":"
  • Remove a child
    sizer.remove(child);\n
  • Remove and destroy a child
    sizer.remove(child, true);\n
  • Remove all children
    sizer.removeAll();\n
  • Remove and destroy all children
    sizer.removeAll(true);\n
  • Remove all children and backgrounds
    sizer.clear();\n
  • Remove and destroy all children and backgrounds
    sizer.clear(true);\n
  • Remove from parent sizer
    sizer.removeFromParentSizer();\n
"},{"location":"ui-fixwidthsizer/#sort-children","title":"Sort children","text":"
  • Sort by data
    sizer.sortChildrenByData(key, descending).layout();\n
    • key : Data key
    • descending :
      • true : Descending order
      • false : Ascending order, default behavior.
  • Sort by property of child
    sizer.sortChildrenByProperty(key, descending).layout();\n
    • key : Property key
    • descending :
      • true : Descending order
      • false : Ascending order, default behavior.
  • Sort by callback
    sizer.sortChildren(function(childA, childB){\n// var valueA = childA.getData(key);\n// var valueB = childB.getData(key);\n// return valueB - valueA\n}).layout();\n
    • childA, childB : 2 children of this size
"},{"location":"ui-fixwidthsizer/#get-element","title":"Get element","text":"
  • Get element
    • All children items
      var items = sizer.getElement('items');\n
  • Get by name
    var gameObject = sizer.getElement('#' + name);\n// var gameObject = sizer.getElement('#' + name, recursive);\n
    or
    var gameObject = sizer.getByName(name);\n// var gameObject = sizer.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-fixwidthsizer/#get-child-index","title":"Get child index","text":"
var index = sizer.getChildIndex(child);\n
  • index : A number, or null.
"},{"location":"ui-fixwidthsizer/#other-properties","title":"Other properties","text":"

See base-sizer object.

"},{"location":"ui-folder/","title":"Folder","text":""},{"location":"ui-folder/#introduction","title":"Introduction","text":"

A container with a title, foldable child, and background.

  • Author: Rex
  • Game object
"},{"location":"ui-folder/#live-demos","title":"Live demos","text":"
  • Scrollable folders
  • Draggable folder
  • Nested folders
"},{"location":"ui-folder/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-folder/#install-plugin","title":"Install plugin","text":""},{"location":"ui-folder/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add folder object
    var folder = scene.rexUI.add.folder(config);\n
"},{"location":"ui-folder/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add folder object
    var folder = scene.rexUI.add.folder(config);\n
"},{"location":"ui-folder/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Folder } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add folder object
    var folder = new Folder(scene, config);\nscene.add.existing(folder);\n
"},{"location":"ui-folder/#add-folder-object","title":"Add folder object","text":"
var folder = scene.rexUI.add.folder({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\n\ntitle: titleGameObject,    child: childGameObject,\n// customChildOrigin: false,\n\ntoggleByTarget: undefined,\ntoggleClickConfig: {\nmode:'pointerup',\nclickInterval: 100,\nthreshold: undefined,\n},\n\nalign: {\ntitle: 'left',\nchild: 'left',\n},\n\nexpand: {\ntitle: true,\nchild: true,\n},\n\nspace: { left: 0, right:0, top:0, bottom:0, item:0,\n\ntitleLeft: 0, titleRight: 0, titleTop: 0, titleBottom: 0,\nchildLeft: 0, childRight: 0, childTop: 0, childBottom: 0,\n},\n\ntransition: {\nduration: 200,\nexpandCallback: undefined,\ncollapseCallback: undefined,\n},\n\nreLayoutTarget: undefined,\n\nonExpandStart: undefined,\nonExpandComplete: undefined,\nonCollapseStart: undefined,\nonCollapseComplete: undefined,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nitem: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of folder.
  • title : Game object of title, required.
  • child : Game object of child, required.
  • customChildOrigin :
    • false : Set origin of child to 0, or 1 (if rtl is set to true). Default behavior.
    • true : Don't change origin of child.
  • toggleByTarget : Toggle expanding/collapsing by clicking this target game object
    • undefined : Toggle by clicking title game object.
  • toggleClickConfig : Configuration of clicking behavior
    • undefined : Use default configuration.
  • align.title, align.child : Alignment of title, child game objects.
    • undefined, or 'left', or 'top' : Align game objects at left, or top. Default behavior.
    • 'center' : Align game objects at center.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
  • expand.title, expand.child : Expand width/height of title, child game objects.
    • true : Expand width/heigh. Default behavior.
    • false : Use origin width/height.
  • transition : Configuration of expanding/collapsing transition.
    • transition.duration : Duration of expanding/collapsing transition.
    • transition.expandCallback : Callback invoked when expading child. Default behavior is scale-up.
    • transition.collapseCallback : Callback invoked when collapsing child. Default behavior is scale-down.
  • reLayoutTarget : Layout topmost sizer when expanding/collapsing start.
    • undefined : Topmost sizer will be layouted again. Default behavior.
    • A sizer : Layout this sizer.
  • onExpandStart : Callback invoked when expanding start. Register this callback on 'expand.start' event.
    function(folder) {  }\n
  • onExpandComplete : Callback invoked when expanding complete. Register this callback on 'expand.complete' event.
    function(folder) {  }\n
  • onCollapseStart : Callback invoked when collapsing start. Register this callback on 'collapse.start' event.
    function(folder) {  }\n
  • onCollapseComplete : Callback invoked when collapsing complete. Register this callback on 'collapse.complete' event.
    function(folder) {  }\n
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.icon : Space between icon game object and text game object.
    • space.text : Space between text game object and action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-folder/#custom-class","title":"Custom class","text":"
  • Define class
    class MyFolder extends RexPlugins.UI.Folder {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var folder = new MyFolder(scene, config);\n
"},{"location":"ui-folder/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

folder.layout();\n

See also - dirty

Note

Layout topmost sizer when expanding/collapsing start.

"},{"location":"ui-folder/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = folder.getElement('background');\n
    • Title game object
      var title = folder.getElement('title');\n
    • Child game object
      var child = folder.getElement('child');\n
  • Get by name
    var gameObject = folder.getElement('#' + name);\n// var gameObject = folder.getElement('#' + name, recursive);\n
    or
    var gameObject = folder.getByName(name);\n// var gameObject = folder.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-folder/#expandcollapse","title":"Expand/collapse","text":"
  • Expand, will re-layout from topmost sizer
    folder.expand();\n// folder.expand(duration);\n
    folder.expand(0);  // Immediately, won't invoke expandCallback\n
  • Collapse, will re-layout from topmost sizer
    folder.collapse();\n// folder.collapse(duration);\n
    folder.collapse(0);  // Immediately, won't invoke collapseCallback\n
  • Toggle, will re-layout from topmost sizer
    folder.toggle();\n// folder.toggle(duration);\n
    folder.toggle(0);  // Immediately, won't invoke expandCallback/collapseCallback\n
  • Set expanded state without re-layouting
    folder.setExpandedState(expanded);  // true, or false\n
  • Get expanded state
    var expanded = folder.expanded;\n
    • expanded : Initial value is undefined
"},{"location":"ui-folder/#transition-callbacks","title":"Transition callbacks","text":"
  • Set transition callbacks
    folder.setExpandCallback(callback);\nfolder.setCollapseCallback(callback);\n
    • callback :
      function(gameObject, duration) {\n}\n
      • gameObject : Child game object
  • Transition duration
    • Set
      folder.setTransitionDuration(duration);\n
    • Get
      var duration = folder.transitionDuration;\n
"},{"location":"ui-folder/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-folder/#events","title":"Events","text":"
  • On expand-start
    folder.on('expand.start', function(folder){\n\n})\n
    title.on('folder.expand', function(folder){\n\n})\n
    child.on('folder.expand', function(folder){\n\n})\n
  • On expand-complete
    folder.on('expand.complete', function(folder){\n\n})\n
  • On collapse-start
    folder.on('collapse.start', function(folder){\n\n})\n
    title.on('folder.collapse', function(folder){\n\n})\n
    child.on('folder.collapse', function(folder){\n\n})\n
  • On collapse-complete
    folder.on('collapse.complete', function(folder){\n\n})\n
"},{"location":"ui-gridbuttons/","title":"Grid buttons","text":""},{"location":"ui-gridbuttons/#introduction","title":"Introduction","text":"

A container with a group of buttons in grids.

  • Author: Rex
  • Game object
"},{"location":"ui-gridbuttons/#live-demos","title":"Live demos","text":"
  • Number pad
  • Checkboxes/radio
"},{"location":"ui-gridbuttons/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-gridbuttons/#install-plugin","title":"Install plugin","text":""},{"location":"ui-gridbuttons/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add buttons object
    var buttons = scene.rexUI.add.gridButtons(config);\n
"},{"location":"ui-gridbuttons/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add buttons object
    var buttons = scene.rexUI.add.gridButtons(config);\n
"},{"location":"ui-gridbuttons/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { GridButtons } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add buttons object
    var buttons = new GridButtons(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-gridbuttons/#add-grid-sizer-object","title":"Add grid sizer object","text":"
var buttons = scene.rexUI.add.gridButtons({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\n// background: backgroundGameObject,\n\nbuttons: [\n[buttonGameObject, buttonGameObject, buttonGameObject, ...],\n[buttonGameObject, buttonGameObject, buttonGameObject, ...],\n[buttonGameObject, buttonGameObject, buttonGameObject, ...],\n...\n],\n// row: 0, \n// column: 0,   // col: 0\n// createCellContainerCallback: function(scene, x, y) {\n//       return cellContainer;\n// },    \nexpand: true,\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n},\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom:0,\n//     column: 0, // [0, 0, 0]\n//     row: 0     // [0, 0, 0]\n// },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n// eventEmitter: this,\n// groupName: undefined,\n\n// buttonsType: undefined,\n// setValueCallback: undefined,  // or setButtonStateCallback: undefined\n// setValueCallbackScope: undefined  // or setButtonStateCallbackScope: undefined\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width : Minimum width. i.e. Width of this gridButtons will larger then this value.
  • height : Minimum height. i.e. Hieght of this gridButtons will larger then this value.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of grid table.
  • buttons : 2d array of button game objects, or create buttons via row, column(or col), and createCellContainerCallback.
  • createCellContainerCallback : Callback to create buttons.
    function(scene, x, y) {\nreturn cellContainer;\n}\n
  • expand : Set true to expand width and height of buton game objects.
  • space : Space around this sizer, and space between columns/rows
    • space.left, space.right, space.top, space.bottom : Space around this sizer.
    • space.column : Space between 2 columns
      • A number
      • A number array
    • space.row : Space between 2 rows
      • A number
      • A number array
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • eventEmitter : Dispatch buttons' touch events to other game object, default is this buttons game object.
  • groupName : Optional group name for argument of touch events.
  • buttonsType : Type/behavior of these buttons.
    • undefined : No extra behavior, default value.
    • 'checkboxes' : Set these buttons to checkboxes.
    • 'radio' : Set these buttons to radio.
  • setValueCallback or setButtonStateCallback : Callback to set value of a button.
    • undefined : No callback, default value.
    • A function object.
      function(button, value, previousValue) {\n// ...\n}\n
      • button : Button game object.
      • value: true, or false.
      • previousValue : true, or false.
"},{"location":"ui-gridbuttons/#custom-class","title":"Custom class","text":"
  • Define class
    class MyGridButtons extends RexPlugins.UI.GridButtons {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var buttons = new MyGridButtons(scene, config);\n
"},{"location":"ui-gridbuttons/#layout-children","title":"Layout children","text":"

Arrange position of all children.

buttons.layout();\n

See also - dirty

"},{"location":"ui-gridbuttons/#other-properties","title":"Other properties","text":"

See grid sizer object.

"},{"location":"ui-gridbuttons/#events","title":"Events","text":"

The same as events of buttons.

"},{"location":"ui-gridbuttons/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = buttons.getElement('background');\n
    • Button game objects
      var buttonObjects = buttons.getElement('buttons');\n
      or
      var buttonObject = buttons.getButton(index);\n
      or
      var buttonObjects = buttons.getElement('buttons[0]'); // First button\n
  • Get by name
    var gameObject = buttons.getElement('#' + name);\n// var gameObject = buttons.getElement('#' + name, recursive);\n
    or
    var gameObject = buttons.getByName(name);\n// var gameObject = buttons.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-gridbuttons/#showhide-button","title":"Show/hide button","text":"

The same as for each button of buttons.

"},{"location":"ui-gridbuttons/#for-each-button","title":"For each button","text":"

The same as for each button of buttons.

"},{"location":"ui-gridbuttons/#checkboxesradio","title":"Checkboxes/radio","text":"

The same as checkboxes/radio of buttons.

"},{"location":"ui-gridsizer/","title":"Grid sizer","text":""},{"location":"ui-gridsizer/#introduction","title":"Introduction","text":"

Layout children game objects in grids.

  • Author: Rex
  • Game object
"},{"location":"ui-gridsizer/#live-demos","title":"Live demos","text":"
  • Create cell-containers
  • Scrollable grids
  • Add new row
  • Add new column
  • Full viewport
  • Set children interactive
  • Destroy cell
  • Reset grid
"},{"location":"ui-gridsizer/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-gridsizer/#install-plugin","title":"Install plugin","text":""},{"location":"ui-gridsizer/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add sizer object
    var sizer = scene.rexUI.add.gridSizer(config);\n
"},{"location":"ui-gridsizer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add sizer object
    var sizer = scene.rexUI.add.gridSizer(config);\n
"},{"location":"ui-gridsizer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { GridSizer } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add sizer object
    var sizer = new GridSizer(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-gridsizer/#add-grid-sizer-object","title":"Add grid sizer object","text":"
var gridSizer = scene.rexUI.add.gridSizer({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\ncolumn: 0,  // col: 0\nrow: 0,\n// columnProportions: undefined,\n// rowProportions: undefined,\n// space: {\n//     left: 0, right: 0, top: 0, bottom:0,\n//     column: 0, // [0, 0, 0]\n//     row: 0,    // [0, 0, 0]\n//     indentLeftOdd: 0, indentLeftEven: 0,\n//     indentTopOdd: 0, indentTopEven: 0,\n// },\n\n// createCellContainerCallback: function(scene, x, y, config) {\n//     config.expand = true;\n//     return cellContainer;\n// },\n\n// name: '',\n// draggable: false\n});\n

or

var gridSizer = scene.rexUI.add.gridSizer(x, y, {\ncolumn: 0,  // col: 0\nrow: 0,\n// columnProportions: undefined,\n// rowProportions: undefined,\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom:0,\n//     column: 0, // [0, 0, 0]\n//     row: 0,    // [0, 0, 0]\n//     indentLeftOdd: 0, indentLeftEven: 0,\n//     indentTopOdd: 0, indentTopEven: 0,\n// },\n\n// createCellContainerCallback: function(scene, x, y, config) {\n//     config.expand = true;\n//     return cellContainer;\n// },\n\n// width: undefined,\n// height: undefined\n});\n

or

var gridSizer = scene.rexUI.add.gridSizer(x, y, width, height, {\ncolumn: 0,   // col: 0\nrow: 0,\n// columnProportions: undefined,\n// rowProportions: undefined,\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom:0,\n//     column: 0, // [0, 0, 0]\n//     row: 0,    // [0, 0, 0]\n//     indentLeftOdd: 0, indentLeftEven: 0,\n//     indentTopOdd: 0, indentTopEven: 0,\n// },\n\n// createCellContainerCallback: function(scene, x, y, config) {\n//     config.expand = true;\n//     return cellContainer;\n// },\n});\n

or

var gridSizer = scene.rexUI.add.gridSizer(x, y, width, height, column, row, {\n// space: {\n//     left: 0, right: 0, top: 0, bottom:0,\n//     column: 0, // [0, 0, 0]\n//     row: 0,    // [0, 0, 0]\n//     indentLeftOdd: 0, indentLeftEven: 0,\n//     indentTopOdd: 0, indentTopEven: 0,\n// },\n\n// createCellContainerCallback: function(scene, x, y, config, gridSizer) {\n//     config.expand = true;\n//     return cellContainer;\n// },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width : Minimum width. i.e. Width of this gridSizer will larger then this value.
  • height : Minimum height. i.e. Hieght of this gridSizer will larger then this value.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • column, or col : Amount of column grids.
  • row : Amount of row grids.
  • columnProportions, rowProportions : Proportion of each column/row.
    • Number : Apply this number proportion to each column/row
    • Number array : Apply proportion of column/row through elements of this number array.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.column : Space between 2 columns
      • A number
      • A number array
    • space.row : Space between 2 rows
      • A number
      • A number array
    • space.indentLeftOdd, space.indentLeftEven : Indent at each odd/even row.
    • space.indentTopOdd, space.indentTopEven : Indent at each odd/even column.
  • createCellContainerCallback : Callback to create container(sizer) of each cell.
    function(scene, x, y, config) {\nreturn cellContainer;\n}\n
    • x, y : Column, row index of this cell.
    • config : Config of adding child
      config.align = 'center';\nconfig.padding = {left: 0, right: 0, top: 0, bottom: 0};\nconfig.expand = false;\nconfig.key = undefined;\n
    • cellContainer : Return a game object for this cell.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-gridsizer/#custom-class","title":"Custom class","text":"
  • Define class
    class MyGridSizer extends RexPlugins.UI.GridSizer {\nconstructor(scene, x, y, minWidth, minHeight, column, row) {\nsuper(scene, x, y, minWidth, minHeight, column, row);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var gridSizer = new MyGridSizer(scene, x, y, minWidth, minHeight, column, row);\n
"},{"location":"ui-gridsizer/#add-background","title":"Add background","text":"
gridSizer.addBackground(child);\n

or

gridSizer.addBackground(child, {left: 0, right: 0, top: 0, bottom: 0}, key);\n
  • left, right, top, bottom : Extra padded space. Default is 0.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
"},{"location":"ui-gridsizer/#add-child","title":"Add child","text":"

Add a game obejct to grid sizer

gridSizer.add(child, column, row);\n

or

gridSizer.add(child,\n{\ncolumn: 0,\nrow: 0,\nalign: 'center',\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nexpand: false,        // expand: {width, height}\nkey: undefined\n}\n);\n

or

gridSizer.add(child, column, row, align, padding, expand, key);\n
  • child : A game object
  • column, row : Index of grid to add.
    • column and row are numbers : Insert game object to cell (column, row).
      • Do nothing if that cell has item already.
    • column and row are undefined : Search each column, each row to find an empty cell for inserting.
      • Add an new row (gridSizer.addEmptyRow()) if last row was full, then find an empty cell in new row.
    • column is undefined, and row is true : Search each row, each column to find an empty cell for inserting.
      • Add an new column (gridSizer.addEmptyColumn()) if last column was full, then find an empty cell in new column.
    • column is a number, and row is undefined : Search each row of column column to find an empty cell for inserting.
      • Add an new row (gridSizer.addEmptyRow()) if last row was full, then find an empty cell in new row.
    • column is undefined and row is a number : Search each column of row row to find an empty cell for inserting.
      • Add an new column (gridSizer.addEmptyColumn()) if last column was full, then find an empty cell in new column.
  • align :
    • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
    • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
    • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game object at top-center.
    • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at bottom-center.
  • padding : Add space between bounds. Default is 0.
    • A number for left/right/top/bottom bounds
    • Or a plain object
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • expand :
    • Boolean value
      • true : Expand width and height of child. Default value.
      • false : Don't expand width or height of child.
    • A plain object
      • {width: true} : Only expand width of child.
      • {height: true} : only expand height of child.
      • {width: true, height: true} : Expand width and height of child.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
"},{"location":"ui-gridsizer/#insert-empty-rowcolumn","title":"Insert empty row/column","text":"
  • Insert an empty row
    gridSizer.insertEmptyRow(rowIndex);\n// gridSizer.insertEmptyRow(rowIndex, proportion, space);\n
    • proportion : Proportion of this new row.
      • undefined : Use proportion of 1st row as default value.
    • space : Space between this new row and previous row.
      • undefined : Use space of 1st row as default value.
  • Add an empty row
    gridSizer.addEmptyRow();\n// gridSizer.addEmptyRow(rowIndex, proportion, space);\n
  • Insert an empty column
    gridSizer.insertEmptyColumn(colIndex);\n// gridSizer.insertEmptyColumn(colIndex, proportion, space);\n
    • proportion : Proportion of this new column.
      • undefined : Use proportion of 1st column as default value.
    • space : Space between this new column and previous column.
      • undefined : Use space of 1st column as default value.
  • Add an empty row
    gridSizer.addEmptyColumn();\n// gridSizer.addEmptyColumn(colIndex, proportion, space);\n
"},{"location":"ui-gridsizer/#proportion","title":"Proportion","text":"

Set proportion of each column or row via

gridSizer.setColumnProportion(columnIndex, proportion);\ngridSizer.setRowProportion(rowIndex, proportion);\n
"},{"location":"ui-gridsizer/#layout-children","title":"Layout children","text":"

Arrange position of all children.

gridSizer.layout();\n

See also - dirty

"},{"location":"ui-gridsizer/#hide","title":"Hide","text":"
  • Set invisible, won't layout it
    sizer.hide();\n
    or
    sizer.hide(gameObject);\n
  • Set visible, will layout it
    sizer.show();\n
    or
    sizer.show(gameObject);\n
"},{"location":"ui-gridsizer/#grid-index-child","title":"Grid index <-> child","text":"
  • Grid index -> child
    var child = gridSizer.getChildAt(columnIndex, rowIndex);\n
  • Child -> grid index
    var gridIndex = gridSizer.childToGridIndex(child);\n// var gridIndex = gridSizer.childToGridIndex(child, out);\n
    • gridIndex : {x, y}, or null if child is not belong this sizer.
"},{"location":"ui-gridsizer/#remove-child","title":"Remove child","text":"
  • Remove a child
    gridSizer.remove(child);\n
    or
    gridSizer.removeAt(columnIndex, rowIndex);\n
  • Remove and destroy a child
    gridSizer.remove(child, true);\n
    or
    gridSizer.removeAt(columnIndex, rowIndex, true);\n
  • Remove all children
    gridSizer.removeAll();\n
  • Remove and destroy all children
    gridSizer.removeAll(true);\n
  • Remove all children and backgrounds
    gridSizer.clear();\n
  • Remove and destroy all children and backgrounds
    gridSizer.clear(true);\n
  • Remove from parent sizer
    sizer.removeFromParentSizer();\n
"},{"location":"ui-gridsizer/#sort-children","title":"Sort children","text":"
  • Sort by data
    gridSizer.sortChildrenByData(key, descending).layout();\n
    • key : Data key
    • descending :
      • true : Descending order
      • false : Ascending order, default behavior.
  • Sort by property of child
    gridSizer.sortChildrenByProperty(key, descending).layout();\n
    • key : Property key
    • descending :
      • true : Descending order
      • false : Ascending order, default behavior.
  • Sort by callback
    gridSizer.sortChildren(function(childA, childB){\n// var valueA = childA.getData(key);\n// var valueB = childB.getData(key);\n// return valueB - valueA\n}).layout();\n
    • childA, childB : 2 children of this size
"},{"location":"ui-gridsizer/#grid-size","title":"Grid size","text":"
  • Amount of column
    var columnCount = gridSizer.columnCount;\n
  • Amount of row
    var rowCount = gridSizer.rowCount;\n
  • Amount of grid = columnCount * rowCount
    var gridCount = gridSizer.gridCount;\n
"},{"location":"ui-gridsizer/#get-element","title":"Get element","text":"
  • Get element
    • All children items
      var items = gridSizer.getElement('items');\n
  • Get by name
    var gameObject = gridSizer.getElement('#' + name);\n// var gameObject = gridSizer.getElement('#' + name, recursive);\n
    or
    var gameObject = gridSizer.getByName(name);\n// var gameObject = gridSizer.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-gridsizer/#get-child-index","title":"Get child index","text":"
var index = sizer.getChildIndex(child);\n
  • index : A number, or null.
"},{"location":"ui-gridsizer/#reset-grid","title":"Reset grid","text":"
sizer.resetGrid(column, row, columnProportions, rowProportions, space);\n
  • column : Amount of column grids.
  • row : Amount of row grids.
  • columnProportions, rowProportions : Proportion of each column/row.
    • Number : Apply this number proportion to each column/row
    • Number array : Apply proportion of column/row through elements of this number array.
  • space :
    • space.column : Space between 2 columns
      • A number
      • A number array
    • space.row : Space between 2 rows
      • A number
      • A number array

Note

Children game objects will be removed without destroyed.

Note

Will invoke createCellContainerCallback to create cellContainer of each cell.

"},{"location":"ui-gridsizer/#other-properties","title":"Other properties","text":"

See base sizer object, container-lite.

"},{"location":"ui-gridtable/","title":"Grid table","text":""},{"location":"ui-gridtable/#introduction","title":"Introduction","text":"

A container with a grid table, slider, and scroller.

  • Author: Rex
  • Game object
"},{"location":"ui-gridtable/#live-demos","title":"Live demos","text":"
  • Grid table
  • Varying cell size
  • Messages
    • Demo 1
    • Demo 2
    • Demo 3
  • Sizer cell:
    • Demo 1
    • Demo 2
  • Click child of cell
  • Two sliders
  • Separator
  • Modal
  • Fixed cell size
  • Drag item
  • Layer + mask padding
  • Fade-out-destroy cell
  • Custom mask
"},{"location":"ui-gridtable/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-gridtable/#install-plugin","title":"Install plugin","text":""},{"location":"ui-gridtable/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add table object
    var table = scene.rexUI.add.gridTable(config);\n
"},{"location":"ui-gridtable/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add table object
    var table = scene.rexUI.add.gridTable(config);\n
"},{"location":"ui-gridtable/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { GridTable } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add table object
    var table = new GridTable(scene, config);\nscene.add.existing(table);\n
"},{"location":"ui-gridtable/#add-table-object","title":"Add table object","text":"
var table = scene.rexUI.add.gridTable({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// scrollMode: 0,\n\n// Elements\nbackground: backgroundGameObject,\n\ntable: {\nwidth: undefined,\nheight: undefined,\n\ncellWidth: undefined,\ncellHeight: undefined,\ncolumns: 1,\n// rows: 1,\n// fixedCellSize: false,\n\nmask: {\npadding: 0,\n// updateMode: 0,\n},\n// enableLayer: false,\ninteractive: true,\nreuseCellContainer: false,\n\n// click: undefined,\n// tap: undefined,\n// press: undefined,\n// swipe: undefined,\n},\n\nslider: {\n// background: sliderBackgroundGameObject,\ntrack: trackGameObject,\n/* \n        track: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\nthumb: thumbGameObject,\n/* \n        thumb: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\n// input: 'drag',\n// position: 'right',\n\n// hideUnscrollableSlider: false,\n// adaptThumbSize: false,\n// minThumbSize: undefined,\n\n// buttons: {\n//     top: topButtonGameObject, bottom: bottomButtonGameObject,\n//     left: leftButtonGameObject, right: rightButtonGameObject,\n//     step: 0.01,\n// }\n},\n\n// sliderX: {...},\n// sliderY: {...},\n\n// scroller: {\n//     threshold: 10,\n//     slidingDeceleration: 5000,\n//     backDeceleration: 2000,\n//     pointerOutRelease: true,\n//     rectBoundsInteractive: true,\n//     dragRate: 1,\n// },\n\n// scrollerX: {...},\n// scrollerY: {...},\n\nmouseWheelScroller: false,\n// mouseWheelScroller: {\n//     focus: true,\n//     speed: 0.1\n// }.\n\n// mouseWheelScrollerX: {...},\n// mouseWheelScrollerY: {...},\n\nclampChildOY: false,\n\nheader: headerGameObject,\nfooter: footerGameObject,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\ntable: 0,\n// table: {\n//    top: 0,\n//    bottom: 0,\n//    left: 0,\n//    right: 0,\n//},\n\nslider: 0,\n// slider: {\n//     top: 0,\n//     bottom: 0,\n//     left: 0,\n//     right: 0,\n// },\n// sliderX: 0,\n// sliderY: 0,\n\nheader: 0,\nfooter: 0,\n},\n\nexpand: {\nheader: true,\nfooter: true,\n},\n\nalign: {\nheader: 'center',\nfooter: 'center',\n},\n\ncreateCellContainerCallback: function(cell, cellContainer) {\nvar scene = cell.scene,\nwidth = cell.width,\nheight = cell.height,\nitem = cell.item,\nitems = cell.items,\nindex = cell.index;\nif (cellContainer === null) { // No reusable cell container, create a new one\n// cellContainer = scene.rexUI.add.label();\n}\n// Set child properties of cell container ...\n\n// cell.setCellContainerAlign();  // Set alignment of cellContainer\n\nreturn cellContainer; // or null\n},\n\nitems: [],\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
    • Set width to undefined, and table.width is not undefined, will count width via table + slider.
    • Set height to undefined, and table.height is not undefined, will count height via table + slider.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • scrollMode : Scroll panel vertically, or horizontally.
    • 0, 'vertical', or 'v', 'y' : Scroll panel vertically. Default value.
    • 1, 'horizontal', or 'h'. 'x' : Scroll panel horizontally.
    • 2, or 'xy' : Two-sliders mode, scroll panel vertically and horizontally.
  • background : Game object of background, optional. This background game object will be resized to fit the size of grid table.
  • table : Configuration of grid table core.
    • table.width : Width of table, in pixels.
      • Set to undefined to expand table width to fit this grid table object.
    • table.height : Height of table, in pixels.
      • Set to undefined to expand table height to fit this grid table object.
    • table.cellHeight : Default height of each cell.
      • Necessary field in vertical scrollMode.
      • undefined : Expand cell height to fit table height, in horizontal scrollMode.
    • table.cellWidth : Width of each cell.
      • Necessary field in horizontal scrollMode.
      • undefined : Expand cell width to fit table width, in vertical scrollMode.
    • table.columns : Columns count of each row. Can be used in vertical or horizontal scroll mode.
    • table.rows : Rows count of each column. Can be used in horizontal scroll mode.
    • table.fixedCellSize : Assign columns according to cellWidth (if scrollMode is 0) or cellHeight (if scrollMode is 1) , when initialize and resizing. \u3000\u3000 - false : Ignore this parameter. Default behavior.
      • true : Set columns according to cellWidth/cellHeight.
    • table.mask : A rectangle mask of cells
      • table.mask.padding : Extra left/right/top/bottom padding spacing of this rectangle mask. Default value is 0.
      • table.mask.updateMode : When to update cells mask
        • 0, or update : Apply mask to cell container only when table.updateTable() is invoked. Default behavior.
        • 1, or everyTick : Apply mask to cell container every tick. Use this mode if game objects of cell are moved after table.updateTable() and still been masked.
      • false : No mask.
    • table.enableLayer :
      • false : Add cell game objects into scene's display list. Default behavior.
      • true : Add cell game objects into an internal layer game object. See also.
    • table.reuseCellContainer :
      • true : Reuse cell container when creating new cell container.
      • false : Destory cell container when cell is invisible, create new cell container when cell is visible. Default behavior.
    • table.interactive : Set true to install touch events (tap/press/over/out/click). Default value is true.
    • table.click : Configuration of cell-click behavior, if table.interactive is true.
      • undefined : Use default click behavior.
    • table.tap : Configuration of cell-tap behavior, if table.interactive is true.
      • undefined : Use default tap behavior.
    • table.press : Configuration of cell-press behavior, if table.interactive is true.
      • undefined : Use default press behavior.
    • table.swipe : Configuration of cell-swipe behavior, if table.interactive is true.
      • undefined : Use default swipe behavior.
  • slider : Componments of slider, optional.
    • slider.background : Game object of slider background, optional.
    • slider.track : Game object of track.
    • slider.thumb : Game object of thumb.
    • slider.input :
      • 'pan', 'drag', or 0 : Control slider by panning/dragging thumb game object. Default setting.
      • 'click', or 1 : Control slider by touching track game object.
      • 'none', or -1 : Disable sider controlling.
    • slider.position : Position of this slider.
      • 0, 'right', 'bottom' : Slider at right/bottom side. Default value.
      • 1, 'left', 'top' : Slider at left/top side.
    • slider.hideUnscrollableSlider :
      • false : Slider is always visible no matter it is scrollable or not. Default behavior.
      • true : Set slider to invisible if it is unscrollable.
    • slider.adaptThumbSize :
      • false : Don't adjust height/width of thumb. Default behavior.
      • true : Adjust height/width of thumb according to ratio of visible child.
        • Minimum height/width of thumb = slider.minThumbSize. If content is larger then a page.
        • Maximum height/width of thumb = height/width of slider.track. If content is less then a page.
    • slider.minThumbSize : Minimum height/width of thumb used in slider.adaptThumbSize mode.
    • slider.buttons : Press button to scroll content in each tick.
      • slider.buttons.top, slider.buttons.bottom : Top and bottom buttons.
      • slider.buttons.left, slider.buttons.right : Left and right buttons
      • slider.buttons.step : Scrolling step in each tick. Default value is 0.01.
    • Set to false to skip creating slider.
  • sliderX, sliderY : Componments of sliderX and sliderY, for two-sliders mode.
  • scroller : Configuration of scroller behavior.
    • scroller.threshold : Minimal movement to scroll. Set 0 to scroll immediately.
    • scroller.slidingDeceleration : Deceleration of slow down when dragging released.
      • Set false to disable it.
    • scroller.backDeceleration : Deceleration of pull back when out of bounds.
      • Set false to disable it.
    • scroller.pointerOutRelease : Set to true to release input control when pointer out of gameObject.
    • scroller.rectBoundsInteractive :
      • false : Detect scrolling by game object's touch input.
      • true : Detect scrolling by rectangle bounds of game object. Default behavior.
    • scroller.dragRate : Rate of dragging distance/dragging speed. Default value is 1.
    • Set to false to skip creating scroller.
  • scrollerX, scrollerY : Configuration of scrollerX, scrollerY behavior, for two-sliders mode.
  • mouseWheelScroller : Configuration of mouse-wheel-scroller behavior.
    • mouseWheelScroller.focus :
      • false, or 0 : Without checking if cursor is over game object or not.
      • true, or 1 : Cursor is inside the rectangle bounds of game object. Default behavior.
      • 2 : Cursor is over game object.
    • mouseWheelScroller.speed : Scrolling speed, default value is 0.1.
    • Set to false to skip creating mouse-wheel-scroller. Default behavior.
  • mouseWheelScrollerX, mouseWheelScrollerY : Configuration of mouse-wheel-scrollerX, or mouse-wheel-scrollerY behavior, for two-sliders mode.
  • clampChildOY : Set true to clamp scrolling.
  • createCellContainerCallback : Callback to return a container object, or null of each visible cell.
    • Properties of cell parameter
      • cell.scene : Scene of this grid table object.
      • cell.width : Width of this cell, in pixels.
      • cell.height : Height of this cell, in pixels.
      • cell.item : Item of this cell to display.
      • cell.items : Array of item data for each cell, equal to items parameter.
      • cell.index : Index of this cell.
    • Alignment of cellContainer :
      cell.setCellContainerAlign(align);\n
      • align :
        • undefined : Set position of cellContainer to left-top of cell space. Default behavior.
        • 'center', or Phaser.Display.Align.CENTER : Align game object at center of cell space.
        • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center of cell space.
        • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center of cell space.
        • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game object at top-center of cell space.
        • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at bottom-center of cell space.
    • If cell.align is undefined (default value), Origin of returned cell container will be set to (0, 0)
    • cellContainer : Cell container picked from object pool for reusing. Set reuseCellContainer to true to enable this feature.
      • null : No cell container available.
      • Game object : Reusable cell container.
  • header : Game object of header, optional.
  • footer : Game object of footer, optional.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.table :
      • A number: Space between table object and slider object.
      • An object: Padding of table object.
        • If scrollMode is 0 (vertical) :
          • space.table.top, space.table.bottom : Top, bottom padding space of table object.
          • space.table.right : Space between table object and slider object.
        • If scrollMode is 1 (horizontal) :
          • space.table.left, space.table.right : Left, right padding space of table object.
          • space.table.bottom : Space between table object and slider object.
    • space.slider :
      • 0 : No space around slider.
      • space.slider.left, space.slider.right, space.slider.top, space.slider.bottom : Space around slider.
    • space.sliderX, space.sliderX : Space configuration of sliderX, sliderX, for two-sliders mode.
      • 0 : No space around slider.
    • space.header : Space between header and table.
    • space.footer : Space between footer and table.
  • expand : Expand width or height of element
    • expand.header : Set true to expand width or height of header game object.
    • expand.footer : Set true to expand width or height of footer game object.
  • align : Align element
    • align.header
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • align.footer
  • items : Array of item data for each cell.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
"},{"location":"ui-gridtable/#scroll-mode","title":"Scroll mode","text":"

If scrollMode parameter is not given :

  • Set scrollMode to 2, if configuration has sliderX, sliderY, or scrollerX, scrollerY parameters.
  • Set scrollMode to 0, if configuration has sliderY, or scrollerY parameters.
  • Set scrollMode to 1, if configuration has sliderX, or scrollerX parameters.
"},{"location":"ui-gridtable/#custom-class","title":"Custom class","text":"
  • Define class
    class MyGridTable extends RexPlugins.UI.GridTable {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var table = new MyGridTable(scene, config);\n
"},{"location":"ui-gridtable/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

table.layout();\n

See also - dirty

"},{"location":"ui-gridtable/#items","title":"Items","text":"
  • Set
    table.setItems(items);\n
    • items : Array of item data for each cell.
    • This method will update each visible cell of grid table.
  • Clear all items
    table.setItems();\n
  • Get
    var items = table.items;\n
  • Add item
    Phaser.Utils.Array.Add(table.items, item);\ntable.refresh();\n
  • Insert item
    Phaser.Utils.Array.AddAt(table.items, item, index);\ntable.refresh();\n
  • Remove item
    Phaser.Utils.Array.Remove(table.items, item);\ntable.refresh();\n
  • Remove item at index
    Phaser.Utils.Array.RemoveAt(table.items, index);\ntable.refresh();\n
  • Remove items between indexes
    Phaser.Utils.Array.RemoveBetween(table.items, startIndex, endIndex);\ntable.refresh();\n
  • Remove random item
    Phaser.Utils.Array.RemoveRandomElement(table.items);\ntable.refresh();\n
"},{"location":"ui-gridtable/#cell-container","title":"Cell container","text":"
  • Get
    var container = table.getCellContainer(cellIndex);\n
"},{"location":"ui-gridtable/#reset-size-of-all-cells","title":"Reset size of all cells","text":"
table.resetAllCellsSize(width, height);\n
"},{"location":"ui-gridtable/#scroll-content","title":"Scroll content","text":"
  • Set
    table.childOY = oy;\n// table.setChildOY(oy);\n
  • Set and clamp
    table.setChildOY(oy, true);\n
  • Add
    table.addChildOY(oy);\n
  • Add and clamp
    table.addChildOY(oy, true);\n
  • Get
    var childOY = table.childOY;\n
  • Top OY
    var topOY = table.topChildOY;\n
  • Bottom OY
    var bottomOY = table.bottomChildOY;\n
  • Is overflow (height of content is larger than display height)
    var isOverflow = textArea.isOverflow;\n
"},{"location":"ui-gridtable/#scroll-by-percentage","title":"Scroll by percentage","text":"
  • Set
    table.t = t;  // t: 0~1\n// table.setT(t);  \n
  • Set and clamp
    table.setT(t, true);\n
  • Get
    var t = table.t;\n
"},{"location":"ui-gridtable/#scroll-to-topbottom","title":"Scroll to top/bottom","text":"
  • Scroll to top
    table.scrollToTop();\n
    • Equal to table.t = 0;
  • Scroll to bottom
    table.scrollToBottom();\n
    • Equal to table.t = 1;
"},{"location":"ui-gridtable/#scroll-to-row","title":"Scroll to row","text":"
  • Scroll to next row
    table.scrollToNextRow();\n
  • Scroll to next n row
    table.scrollToNextRow(n);\n
  • Scroll to row
    table.scrollToRow(rowIndex);\n
  • Get current row index
    var rowIndex = table.startRowIndex;\n
"},{"location":"ui-gridtable/#enabledisable-scrolling","title":"Enable/disable scrolling","text":"
  • Slider
    • Set enable state
      table.setSliderEnable(enabled);\n
      or
      table.sliderEnable = enabled;\n
    • Get enable state
      var enable = table.sliderEnable;\n
  • Scroller
    • Set enable state
      table.setScrollerEnable(enabled);\n
      or
      table.scrollerEnable = enabled;\n
    • Get enable state
      var enable = table.scrollerEnable;\n
  • Mouse-Wheel-Scroller
    • Set enable state
      table.setMouseWheelScrollerEnable(enabled);\n
      or
      table.mouseWheelScrollerEnable = enabled;\n
    • Get enable state
      var enable = table.mouseWheelScrollerEnable;\n
"},{"location":"ui-gridtable/#refresh-table-cells","title":"Refresh table cells","text":"
  • Refresh all visible cells
    table.refresh();\n
    • Equal to table.setItems(table.items).
  • Update a visible cell
    table.updateVisibleCell(cellIndex);\n
"},{"location":"ui-gridtable/#table-size","title":"Table size","text":"
  • Table width
    var tableWidth = table.getElement('table').tableWidth;\n
  • Table height
    var tableHeight = table.getElement('table').tableHeight;\n
"},{"location":"ui-gridtable/#other-properties","title":"Other properties","text":"

See base sizer object, container-lite.

"},{"location":"ui-gridtable/#events","title":"Events","text":"
  • Pointer-down cell
    table.on('cell.down', function(cellContainer, cellIndex, pointer, event) {\n// ...\n}, scope);\n
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-up cell
    table.on('cell.up', function(cellContainer, cellIndex, pointer, event) {\n// ...\n}, scope);\n
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-over cell
    table.on('cell.over', function(cellContainer, cellIndex, pointer, event) {\n// ...\n}, scope);\n
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-out cell
    table.on('cell.out', function(cellContainer, cellIndex, pointer, event) {\n// ...\n}, scope);\n
    • Cancel remaining touched events : event.stopPropagation()
  • Click cell
    table.on('cell.click', function(cellContainer, cellIndex, pointer, event) {\n// ...\n}, scope);\n
    • Cancel remaining touched events : event.stopPropagation()
  • Tap cell
    table.on(tapEventName, function(cellContainer, cellIndex, pointer) {\n// ...\n}, scope);\n
    • tapEventName : 'cell.1tap', 'cell.2tap', 'cell.3tap', etc ...
    • cellContainer : Container game object of triggered cell.
    • cellIndex : Index of triggered cell.
  • Press cell
    table.on(`cell.pressstart`, function(cellContainer, cellIndex, pointer) {\n// ...\n}, scope);\n
    table.on(`cell.pressend`, function(cellContainer, cellIndex, pointer) {\n// ...\n}, scope);\n
  • Swipe cell
    table.on(swipeEventName, function(cellContainer, cellIndex, pointer) {\n// ...\n}, scope);\n
    • swipeEventName : 'cell.swipeleft', 'cell.swiperight', 'cell.swipeup', 'cell.swipedown'.
  • Scroll table
    table.on('scroll', function(table) {\n// ...\n})\n
  • Slider
    • Slider drag start
      table.getElement('slider').on('inputstart', function(panel) {\n// ...\n})\n
    • Slider drag end
      table.getElement('slider').on('inputend', function(panel) {\n// ...\n})\n
  • Scroller
    • Scroller drag start
      table.getElement('scroller').on('dragstart', function(panel) {\n// ...\n})\n
    • Scroller drag end
      table.getElement('scroller').on('dragend', function(panel) {\n// ...\n})\n
"},{"location":"ui-gridtable/#interactive-with-child-of-cell","title":"Interactive with child of cell","text":"
table.on('cell.click', function(cellContainer, cellIndex, pointer, event) {\nvar child;\n// child = cellContainer.getElement(...);\nif (cellContainer.isPointerInBounds(child)) {\n// Pointer on this child\n}\n}, scope);\n

Reference of isPointerInBounds method

"},{"location":"ui-gridtable/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = table.getElement('background');\n
    • Grid table
      var tableBody = table.getElement('table');\n
    • Layer of gridtable, assigned at config table.mask.layer.
      var layer = table.getElement('tableLayer');\n
    • Slider
      • Track
        var track = table.getElement('slider.track');\n
      • Thumb
        var thumb = table.getElement('slider.thumb');\n
    • Scroller
      var scroller = table.getElement('scroller');\n
    • Header game object
      var tableBody = table.getElement('header');\n
    • Footer game object
      var tableBody = table.getElement('footer');\n
  • Get by name
    var gameObject = table.getElement('#' + name);\n// var gameObject = table.getElement('#' + name, recursive);\n
    or
    var gameObject = table.getByName(name);\n// var gameObject = table.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-holygrail/","title":"Holy grail","text":""},{"location":"ui-holygrail/#introduction","title":"Introduction","text":"

Layout elements in Holy grail style.

  • Author: Rex
  • Game object
"},{"location":"ui-holygrail/#live-demos","title":"Live demos","text":"
  • Simple
  • Align
  • Layout modes
  • Change layout mode
"},{"location":"ui-holygrail/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-holygrail/#install-plugin","title":"Install plugin","text":""},{"location":"ui-holygrail/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add holy-grail object
    var holyGrail = scene.rexUI.add.holyGrail(config);\n
"},{"location":"ui-holygrail/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add holy-grail object
    var holyGrail = scene.rexUI.add.holyGrail(config);\n
"},{"location":"ui-holygrail/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { HolyGrail } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add holy-grail object
    var holyGrail = new HolyGrail(scene, config);\nscene.add.existing(holyGrail);\n
"},{"location":"ui-holygrail/#add-holygrail-object","title":"Add holyGrail object","text":"
var holyGrail = scene.rexUI.add.holyGrail({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nlayoutMode: 0,\n\n// Elements\nbackground: backgroundGameObject,\n\nheader: headerGameObject,\n\nleftSide: leftSideGameObject,\n\ncontent: contentGameObject,\n\nrightSide: rightSideGameObject,\n\nfooter: footerGameObject,\n\n// Space\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nheader: 0,  // {left, right, top, bottom}\nfooter: 0,  // {left, right, top, bottom}\nleftSide: 0, // {left, right, top, bottom}\nrightSide: 0, // {left, right, top, bottom}\n},\n\n// proportion: {\n//     header: 0,\n//     footer: 0,\n//     leftSide: 0,\n//     rightSide: 0,\n//     content: 1,\n// },\n\n// expand: {\n//     header: true,\n//     footer: true,\n//     leftSide: true,\n//     rightSide: true,\n//     content: false,\n// },\n\n// align: {\n//     header: 'center',\n//     footer: 'center',\n//     leftSide: 'center',\n//     rightSide: 'center',\n//     content: 'center',\n// },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • layoutMode : Expand left side, right side to bottom row.
    • 0, or 'FFF' : Bottom row is footer. Default behavior
    • 1, or 'LFF' : Left side will expand down to bottom row.
    • 2, or 'FFR' : Right side will expand down to bottom row.
    • 3, or 'LFR' : Left side and right side will expand down to bottom row.
  • background : Game object of background, optional. This background game object will be resized to fit the size of holyGrail.
  • header : Game object of header, optional.
    • Will fixed height (proportion=0) and expand width (expand=true) width default setting.
  • leftSide : Game object of leftSide, optional.
    • Will fixed width (proportion=0) and expand height (expand=true) width default setting.
  • content : Game object of content, optional.
    • Will expand width (proportion=1) and expand height (expand=true) width default setting.
  • rightSide : Game object of rightSide, optional.
    • Will fixed width (proportion=0) and expand height (expand=true) width default setting.
  • footer : Game object of footer, optional.
    • Will fixed height (proportion=0) and expand width (expand=true) width default setting.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.header :
      • A number : Space between header game object and below game object, equal to {bottom}
      • {left, right, top, bottom} : Padding values of header game object.
    • space.footer
      • A number : Space between footer game object and above game object, equal to {top}
      • {left, right, top, bottom} : Padding values of footer game object.
    • space.leftSide :
      • A number : Space between leftSide game object and content game object, equal to {right}
      • {left, right, top, bottom} : Padding values of leftSide game object.
    • space.rightSide :
      • A number : Space between rightSide game object and content game object, equal to {left}
      • {left, right, top, bottom} : Padding values of rightSide game object.
  • expand : Expand width or height of element
    • expand.header : Set true to expand width of header game object. Default is true.
    • expand.footer : Set true to expand width of footer game object. Default is true.
    • expand.leftSide : Set true to expand height of leftSide game object. Default is true.
    • expand.rightSide : Set true to expand height of rightSide game object. Default is true.
    • expand.content : Set true to expand height of content game object. Default is true.
  • proportion : Fixed width or height of element
    • proportion.header :
      • 0 : Fixed height. Default behavior.
      • 1, or other numbers : Expand height.
    • proportion.footer :
      • 0 : Fixed height. Default behavior.
      • 1, or other numbers : Expand height.
    • proportion.leftSide :
      • 0 : Fixed width. Default behavior.
      • 1, or other numbers : Expand width.
    • proportion.rightSide :
      • 0 : Fixed width. Default behavior.
      • 1, or other numbers : Expand width.
    • proportion.content :
      • 0 : Fixed width.
      • 1, or other numbers : Expand width. Default value is 1.
  • align : Align element
    • align.header
    • align.footer
    • align.leftSide
    • align.rightSide
    • align.content
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false..
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-holygrail/#custom-class","title":"Custom class","text":"
  • Define class
    class MyHolyGrail extends RexPlugins.UI.HolyGrail {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var holyGrail = new MyHolyGrail(scene, config);\n
"},{"location":"ui-holygrail/#layout-modes","title":"Layout modes","text":""},{"location":"ui-holygrail/#mode-0","title":"Mode 0","text":"

Bottom row is footer. Default behavior.

Header Left side Content Right side Footer"},{"location":"ui-holygrail/#mode-1","title":"Mode 1","text":"

Left side will expand down to bottom row.

Header Left side Content Right side Footer"},{"location":"ui-holygrail/#mode-2","title":"Mode 2","text":"

Right side will expand down to bottom row.

Header Left side Content Right side Footer"},{"location":"ui-holygrail/#mode-3","title":"Mode 3","text":"

Left side and right side will expand down to bottom row.

Header Left side Content Right side Footer"},{"location":"ui-holygrail/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

holyGrail.layout();\n

See also - dirty

"},{"location":"ui-holygrail/#re-build","title":"Re-build","text":"

Destroy current elements then add elements with new config.

holyGrail\n.build({\n// Elements\nbackground: backgroundGameObject,\n\nheader: headerGameObject,\n\nleftSide: leftSideGameObject,\n\ncontent: contentGameObject,\n\nrightSide: rightSideGameObject,\n\nfooter: footerGameObject,\n\nlayoutMode: 0,\n\n// Space\nspace: {        header: 0,  // {left, right, top, bottom}\nfooter: 0,  // {left, right, top, bottom}\nleftSide: 0, // {left, right, top, bottom}\nrightSide: 0, // {left, right, top, bottom}\n},\n\n// proportion: {\n//     header: 0,\n//     footer: 0,\n//     leftSide: 0,\n//     rightSide: 0,\n//     content: 1,\n// },\n\n// expand: {\n//     header: true,\n//     footer: true,\n//     leftSide: true,\n//     rightSide: true,\n//     content: false,\n// },\n\n// align: {\n//     header: 'center',\n//     footer: 'center',\n//     leftSide: 'center',\n//     rightSide: 'center',\n//     content: 'center',\n// },\n})\n.layout()\n
"},{"location":"ui-holygrail/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-holygrail/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = holyGrail.getElement('background');\n
    • Header game object
      var header = holyGrail.getElement('header');\n
    • Left-side game object
      var leftSide = holyGrail.getElement('leftSide');\n
    • Content game object
      var content = holyGrail.getElement('content');\n
    • Right-side game object
      var rightSide = holyGrail.getElement('rightSide');\n
    • Footer game object
      var footer = holyGrail.getElement('footer');\n
  • Get by name
    var gameObject = holyGrail.getElement('#' + name);\n// var gameObject = holyGrail.getElement('#' + name, recursive);\n
    or
    var gameObject = holyGrail.getByName(name);\n// var gameObject = holyGrail.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-imageinputlabel/","title":"Image input label","text":""},{"location":"ui-imageinputlabel/#introduction","title":"Introduction","text":"

A container with a canvas icon, text, and background. Click icon to popup a (image) file chooser dialog, display selected image on canvas.

  • Author: Rex
  • Game object
"},{"location":"ui-imageinputlabel/#live-demos","title":"Live demos","text":"
  • Save texture
"},{"location":"ui-imageinputlabel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-imageinputlabel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-imageinputlabel/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add image-input label object
    var imageInputLabel = scene.rexUI.add.imageInputLabel(config);\n
"},{"location":"ui-imageinputlabel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin, enable dom element in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\nparent: divId,\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Add image-input label object
    var imageInputLabel = scene.rexUI.add.imageInputLabel(config);\n
"},{"location":"ui-imageinputlabel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import { ImageInputLabel } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add image-input label object
    var imageInputLabel = new ImageInputLabel(scene, config);\nscene.add.existing(imageInputLabel);\n
"},{"location":"ui-imageinputlabel/#add-imageinputlabel-object","title":"Add imageInputLabel object","text":"
var imageInputLabel = scene.rexUI.add.imageInputLabel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\n\ncanvas: {\n// width: 128, \n// height: 128,\n// fill: undefined,\n\n// key: undefined, \n// frame: undefined,        \n},\n\n// scaleUpIcon: false,\n\niconBackground: iconBackgroundGameObject,    // squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntext: textGameObject,\nexpandTextWidth: false,\nexpandTextHeight: false,\n\naction: actionGameObject,\n// actionMask: false,\n// squareFitAction: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nalign: undefined,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0, iconTop: 0, iconBottom: 0, iconLeft: 0, iconRight: 0,\n\ntext: 0,\nactionTop: 0, actionBottom: 0, actionLeft: 0, actionRight: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n\n// clickTarget: undefined,\n// domButton: true,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of imageInputLabel.
  • canvas : Parameters of creating canvas game object.
    • canvas.width, canvas.height, canvas.fill : Create canvas with size (canvas.width x canvas.height), filling by color canvas.fill.
    • canvas.key, canvas.frame : Create canvas then paste texture canvas.key, canvas.frame.
  • iconBackground : Game object of iconBackground, optional.
    • icon game object will be created internally by imageBox with canvas.
  • squareFitIcon :
    • true : Resize icon size to square to fit imageInputLabel height/width.
      • Can't work wit expandTextWidth: true
    • false : Ignore this feature. Default behavior.
  • iconSize : Set display size of icon game object to iconSizexiconSize
  • iconWidth : Set display width of icon game object to iconWidth.
    • If iconHeight is undefined, set scaleY of icon game object to scaleX of icon game object, to keep size ratio.
  • iconHeight : Set display height of icon game object to iconHeight.
    • If iconWidth is undefined, set scaleX of icon game object to scaleY of icon game object, to keep size ratio.
  • scaleUpIcon :
    • true : Scale-up canvas game object if its size is smaller than icon (imageBox).
    • false : Keep current size when its size is smaller than icon (imageBox). Default behavior.
  • text : Game object of text, optional.
  • expandTextWidth :
    • false : Keep width of text to original size. Default behavior.
    • true : Expand width of text object. Will set display width by default.
      • Must set to true if using scene.rexUI.wrapExpandText method with any text game object.
      • Can't work with squareFitIcon: true.
  • expandTextHeight : Set true to expand height of text object.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • squareFitAction :
    • true : Resize action icon size to square to fit imageInputLabel height/width.
    • false : Ignore this feature. Default behavior.
  • actionSize : Set display size of action game object to actionSizexactionSize
  • actionWidth : Set display width of action game object to actionWidth.
    • If actionHeight is undefined, set scaleY of action game object to scaleX of action game object, to keep size ratio.
  • actionHeight : Set display height of action game object to actionHeight.
    • If actionWidth is undefined, set scaleX of action game object to scaleY of action game object, to keep size ratio.
  • align : Alignment of icon, text, action game objects.
    • undefined, or 'left', or 'top' : Align game objects at left, or top.
    • 'center' : Align game objects at center.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.icon : Space between icon game object and text game object.
    • space.iconTop, space.iconBottom, space.iconLeft, space.iconRight : Space around icon game object.
    • space.text : Space between text game object and action icon game object.
    • space.actionTop, space.actionBottom, space.actionLeft, space.actionRight : Space around action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • clickTarget : Click target to open file chooser dialog
    • A string, 'icon', 'text', 'action', 'background' : Click icon, text, action, background game object to open file chooser dialog.
    • undefined : Click this ImageInputLabel game object to open file chooser dialog. Default behavior.
    • null, false : No clickTarget. Open file chooser dialog manually under a touch event.
  • domButton :
    • true : Put DOM buttom above clickTarget, to receive click event.
    • false : Add click event at clickTarget.
      • This mode won't work at ios
"},{"location":"ui-imageinputlabel/#expand-size-of-text","title":"Expand size of text","text":"

Expand width/height of text when expandTextWidth/expandTextHeight is true

To resize text object, text object should have resize method. For example

class MyText extends Phaser.GameObjects.Text {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\nscene.add.existing(this);\n}\nresize(width, height) {\nthis.setFixedSize(width, height);\nreturn this;\n}\n}\n

Or uses bbcode text object, tag text object, canvasInput object.

"},{"location":"ui-imageinputlabel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLabel extends RexPlugins.UI.ImageInputLabel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var imageInputLabel = new MyLabel(scene, config);\n
"},{"location":"ui-imageinputlabel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

imageInputLabel.layout();\n

See also - dirty

"},{"location":"ui-imageinputlabel/#open-file-chooser-dialog","title":"Open file chooser dialog","text":"

Failure

This method can't run at ios.

Note

Open a file chooser dialog under any touch event. i.e. User can't open file chooser dialog directly.

imageInputLabel.openPromise()\n.then(function(file){\n})\n
  • file : File object
imageInputLabel.open()\n
"},{"location":"ui-imageinputlabel/#enable-clicking-open","title":"Enable clicking-open","text":"
  • Enable
    imageInputLabel.setClickOpenEnable();\n// imageInputLabel.setClickOpenEnable(true);\n
  • Disable
    imageInputLabel.setClickOpenEnable(false)\n
"},{"location":"ui-imageinputlabel/#save-texture","title":"Save texture","text":"

Save image on canvas into texture manager.

imageInputLabel.saveTexture(key);\n
"},{"location":"ui-imageinputlabel/#events","title":"Events","text":"
  • Select file
    imageInputLabel.on('select', function(file, imageInputLabel) {\n\n})\n
    • file : File object
"},{"location":"ui-imageinputlabel/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = imageInputLabel.getElement('background');\n
    • Canvas game object (a canvas game object created internally)
      var canvas = imageInputLabel.getElement('canvas');\n
    • Icon background game object
      var iconBackground = imageInputLabel.getElement('iconBackground');\n
    • Icon game object (an imageBox game object created internally)
      var imageBox = imageInputLabel.getElement('icon');\n
    • Text game object
      var textObject = imageInputLabel.getElement('text');\n
    • Action icon game object
      var action = imageInputLabel.getElement('action');\n
    • File chooser game object, if domButton is set to true
      var fileChooser = imageInputLabel.getElement('fileChooser');\n
  • Get by name
    var gameObject = imageInputLabel.getElement('#' + name);\n// var gameObject = imageInputLabel.getElement('#' + name, recursive);\n
    or
    var gameObject = imageInputLabel.getByName(name);\n// var gameObject = imageInputLabel.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-imageinputlabel/#other-properties","title":"Other properties","text":"

See label), sizer object, base sizer object, container-lite.

"},{"location":"ui-knob/","title":"Knob","text":""},{"location":"ui-knob/#introduction","title":"Introduction","text":"

A knob button based on circular progress shape.

  • Author: Rex
  • Game object
"},{"location":"ui-knob/#live-demos","title":"Live demos","text":"
  • Knob
"},{"location":"ui-knob/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-knob/#install-plugin","title":"Install plugin","text":""},{"location":"ui-knob/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add knob object
    var knob = scene.rexUI.add.knob(config);\n
"},{"location":"ui-knob/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add knob object
    var knob = scene.rexUI.add.knob(config);\n
"},{"location":"ui-knob/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Knob } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add knob object
    var knob = new Knob(scene, config);\nscene.add.existing(knob);\n
"},{"location":"ui-knob/#add-knob-object","title":"Add knob object","text":"
var knob = scene.rexUI.add.knob({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\n\nbarColor: undefined,\ntrackColor: undefined,\ncenterColor: undefined,\nthickness: 0.2,\nstartAngle: Phaser.Math.DegToRad(270),\nanticlockwise: false,\n// iterations: 128,\nknobDepth: 0,\n\ntext: undefined,\ntextFormatCallback: undefined,\ntextFormatCallbackScope: undefined,\n\ninput: 'pan',\n\nvalue: 0,\ngap: undefined,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},\nvaluechangeCallback: function(newValue, oldValue, knob) {\n},\nvaluechangeCallbackScope: undefined,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n\nenable: true,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of knob.
  • barColor : Color of circular bar, in number or css string value.
  • trackColor : Color of circular track, in number or css string value.
  • centerColor : Color of center circle, in number or css string value.
  • thickness : 0 ~ 1, thickness of circular bar. Default value is 0.2 (0.2*radius)
  • startAngle : Start angle of circular bar, in radians. Default value is 270 degrees.
  • anticlockwise : Set true to put anticlockwise circular bar. Default value is false.
  • iterations : Iterations of curve, set larger value to get more smooth rendering result. Default value is 128.
  • knobDepth : Depth of knob (circular progress). Default value is 0.
  • text : Label, Text, BBCodeText, or TagText, which has setText(text) method, optional.
    • Don't set textColor, textStrokeColor if text parameter is provided.
    • Depth of text object ought to larger than knob (circular progress), to put text object in front of knob.
  • Display text :
    • textColor : Color of display text. Default is undefined.
    • textStrokeColor, textStrokeThickness : Stroke color, stroke line width of display text. Default is undefined.
    • textSize, textFamily, textStyle : Size, family, style of display text.
  • textFormatCallback, textFormatCallbackScope : Formating callback of display text. ex:
    function(value) {\nreturn Math.floor(value * 100).toString();\n}\n
    Default value is undefined.
  • input :
    • 'pan', 'drag', or 0 : Control knob by panning circular progress. Default setting.
    • 'click', or 1 : Control knob by touching circular progress.
    • 'none', or -1 : Disable knob controlling.
  • value : Initial value (0 ~ 1).
  • gap : Snap a value to nearest grid slice, using rounding.
    • undefined : Disalbe this feature.
  • easeValue : Easing value when input is 'click'.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
  • valuechangeCallback : callback function when value changed.
  • enable : Set false to disable controlling.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-knob/#custom-class","title":"Custom class","text":"
  • Define class
    class MyKnob extends RexPlugins.UI.Knob {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var knob = new MyKnob(scene, config);\n
"},{"location":"ui-knob/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

knob.layout();\n

See also - dirty

"},{"location":"ui-knob/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = knob.getElement('background');\n
    • Circular progress game object
      var circularProgress = knob.getElement('knob');\n
    • Text game object
      var text = knob.getElement('text');\n
  • Get by name
    var gameObject = knob.getElement('#' + name);\n// var gameObject = knob.getElement('#' + name, recursive);\n
    or
    var gameObject = knob.getByName(name);\n// var gameObject = knob.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-knob/#enable","title":"Enable","text":"
  • Get
    var enable = knob.enable;\n
  • Set
    knob.setEanble(enable);\n
    or
    knob.enable = enable;\n
"},{"location":"ui-knob/#value","title":"Value","text":"

Change value will also change the position of knob thumb and width of knob indicator.

  • Get value
    var value = knob.getValue(min, max); // value : min ~ max\n
    or
    var value = knob.getValue(); // value: 0 ~ 1\n
    or
    var value = knob.value; // value: 0 ~ 1\n
  • Set value
    knob.setValue(value, min, max); // value: min ~ max\n
    or
    knob.setValue(value); // value: 0 ~ 1\n
    or
    knob.value = value; // value: 0 ~ 1\n
  • Increase value
    knob.addValue(inc, min, max); // inc: min ~ max\n
    or
    knob.addValue(inc); // inc: 0 ~ 1\n
    or
    knob.value += inc; // inc: 0 ~ 1\n
"},{"location":"ui-knob/#ease-value","title":"Ease value","text":"
  • Ease value to
    knob.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    knob.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    knob.stopEaseValue();\n
  • Set ease duration
    knob.setEaseValueDuration(duration);\n
  • Set ease function
    knob.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"ui-knob/#other-properties","title":"Other properties","text":"

See overlap sizer object, base sizer object, container-lite.

"},{"location":"ui-knob/#events","title":"Events","text":"
  • On value changed
    knob.on('valuechange', function(newValue, oldValue, knob){\n//\n}, scope);\n
"},{"location":"ui-label/","title":"Label","text":""},{"location":"ui-label/#introduction","title":"Introduction","text":"

A container with an icon, text, and background.

  • Author: Rex
  • Game object
"},{"location":"ui-label/#live-demos","title":"Live demos","text":"
  • Align
  • Add to layer
  • Text wrap in horizontal label
  • Text wrap in vertical label
  • Adjust text font size
  • Square fit icon
  • Icon size
"},{"location":"ui-label/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-label/#install-plugin","title":"Install plugin","text":""},{"location":"ui-label/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add label object
    var label = scene.rexUI.add.label(config);\n
"},{"location":"ui-label/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add label object
    var label = scene.rexUI.add.label(config);\n
"},{"location":"ui-label/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Label } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add label object
    var label = new Label(scene, config);\nscene.add.existing(label);\n
"},{"location":"ui-label/#add-label-object","title":"Add label object","text":"
var label = scene.rexUI.add.label({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\n\nicon: iconGameObject,\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntext: textGameObject,\n// wrapText: false,\n// adjustTextFontSize: false,\n// expandTextWidth: false,\n// expandTextHeight: false,\n\naction: actionGameObject,\n// actionMask: false,\n// squareFitAction: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nalign: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\n\nicon: 0, iconTop: 0, iconBottom: 0, iconLeft: 0, iconRight: 0,\n\ntext: 0,\nactionTop: 0, actionBottom: 0, actionLeft: 0, actionRight: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • squareFitIcon :
    • true : Resize icon size to square to fit label height/width.
      • Can't work wit expandTextWidth: true
    • false : Ignore this feature. Default behavior.
  • iconSize : Set display size of icon game object to iconSizexiconSize
  • iconWidth : Set display width of icon game object to iconWidth.
    • If iconHeight is undefined, set scaleY of icon game object to scaleX of icon game object, to keep size ratio.
  • iconHeight : Set display height of icon game object to iconHeight.
    • If iconWidth is undefined, set scaleX of icon game object to scaleY of icon game object, to keep size ratio.
  • text : Game object of text, optional.
  • wrapText : Enable WrapExpandText feature.
    • false, 0 : No WrapExpandText feature. Default behavior.
    • true, 1, 'word' : Word WrapExpandText.
      • Text-width will be expanding.
    • 2, 'char' : Character WrapExpandText.
      • Text-width will be expanding.
  • adjustTextFontSize : Enable FontSizeExpandText feature.
    • false : No FontSizeExpandText feature. Default behavior.
    • true : Enable FontSizeExpandText feature. Can't work with wrapText: true.
      • Text-width and text-height will be expanding.
      • Use BBCodeText (scene.rexUI.add.BBCodeText) with {valign: 'center'} style.
  • expandTextWidth :
    • false : Keep width of text to original size. Default behavior.
    • true : Expand width of text object. Will set display width by default.
      • Must set to true if using scene.rexUI.wrapExpandText method with any text game object.
      • Can't work with squareFitIcon: true.
  • expandTextHeight : Set true to expand height of text object.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • squareFitAction :
    • true : Resize action icon size to square to fit label height/width.
    • false : Ignore this feature. Default behavior.
  • actionSize : Set display size of action game object to actionSizexactionSize
  • actionWidth : Set display width of action game object to actionWidth.
    • If actionHeight is undefined, set scaleY of action game object to scaleX of action game object, to keep size ratio.
  • actionHeight : Set display height of action game object to actionHeight.
    • If actionWidth is undefined, set scaleX of action game object to scaleY of action game object, to keep size ratio.
  • align : Alignment of icon, text, action game objects.
    • undefined, or 'left', or 'top' : Align game objects at left, or top.
    • 'center' : Align game objects at center.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.icon : Space between icon game object and text game object.
    • space.iconTop, space.iconBottom, space.iconLeft, space.iconRight : Space around icon game object.
    • space.text : Space between text game object and action icon game object.
    • space.actionTop, space.actionBottom, space.actionLeft, space.actionRight : Space around action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-label/#expand-size-of-text","title":"Expand size of text","text":"

Expand width/height of text when expandTextWidth/expandTextHeight is true

To resize text object, text object should have resize method. For example

class MyText extends Phaser.GameObjects.Text {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\nscene.add.existing(this);\n}\nresize(width, height) {\nthis.setFixedSize(width, height);\nreturn this;\n}\n}\n

Or uses bbcode text object, tag text object, or canvasInput object.

"},{"location":"ui-label/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLabel extends RexPlugins.UI.Label {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var label = new MyLabel(scene, config);\n
"},{"location":"ui-label/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

label.layout();\n

See also - dirty

"},{"location":"ui-label/#change-childrens-align-mode","title":"Change children's align mode","text":"
label\n.setChildrenAlignMode(mode)\n.layout();\n
  • mode : Alignment of icon, text, action game objects.
    • undefined, or 'left', or 'top' : Align game objects at left, or top.
      • Remove first and last space children.
    • 'center' : Align game objects at center.
      • Add two spaces as first and last children.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
      • Add space as first child.
"},{"location":"ui-label/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = label.getElement('background');\n
    • Icon game object
      var icon = label.getElement('icon');\n
    • Text game object
      var textObject = label.getElement('text');\n
    • Action icon game object
      var action = label.getElement('action');\n
  • Get by name
    var gameObject = label.getElement('#' + name);\n// var gameObject = label.getElement('#' + name, recursive);\n
    or
    var gameObject = label.getByName(name);\n// var gameObject = label.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-label/#text","title":"Text","text":"
  • Get text string
    var s = label.text;\n
  • Set text string
    label.setText(s);\n
    or
    label.text = s;\n
  • Append text string
    label.appendText(text);\n// label.text += '\\n' + text;\n
    or
    label.appendText(text, false);\n// label.text += text;\n
"},{"location":"ui-label/#icon-texture","title":"Icon texture","text":"
  • Set texture
    label.setTexture(key);\n// label.setTexture(key, frame);\n
  • Set texture via texture object
    label.setTexture(texture);\n// label.setTexture(texture, frame);\n
  • Get texture, frame
    var texture = label.texture;\nvar frame = label.frame;\n
  • Get texture key, frame name
    var textureKey = label.texture.key;\nvar frameName = label.frame.name;\n
"},{"location":"ui-label/#reset-display-content","title":"Reset display content","text":"
label.resetDisplayContent({\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n})\n

or

label.resetDisplayContent(text);\n
  • text : Set text string.
  • icon, iconFrame
    • A string : Set texture of icon game object.
    • undefined, or null : Hide icon game object.
    • true : Show icon game object without change its texture.
  • iconSize : Set display size of icon game object.
  • action, actionFrame
    • A string : Set texture of icon game object.
    • undefined, or null : Hide action game object.
    • true : Show action game object without change its texture.
  • actionSize : Set display size of action game object.

Run label.layout() after this method, to layout children again.

"},{"location":"ui-label/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-menu/","title":"Menu","text":""},{"location":"ui-menu/#introduction","title":"Introduction","text":"

A container with buttons and sub-menu.

  • Author: Rex
  • Game object
"},{"location":"ui-menu/#live-demos","title":"Live demos","text":"
  • Pop-up menu
  • Static menu
  • Drop-down list
  • Expand, collapse
  • Custom transit
"},{"location":"ui-menu/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-menu/#install-plugin","title":"Install plugin","text":""},{"location":"ui-menu/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add menu object
    var menu = scene.rexUI.add.menu(config);\n
"},{"location":"ui-menu/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add menu object
    var menu = scene.rexUI.add.menu(config);\n
"},{"location":"ui-menu/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Menu } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add menu object
    var menu = new Menu(scene, config);\nscene.add.existing(menu);\n
"},{"location":"ui-menu/#add-menu-object","title":"Add menu object","text":"
var menu = scene.rexUI.add.menu({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n\n// popup: true,\n// orientation: 1,\n// subMenuSide: undefined,\nitems: [],\n\ncreateBackgroundCallback: function(items) {\nvar scene = items.scene;\n// background = ...\nreturn background;\n},\ncreateBackgroundCallbackScope: undefined,\n\ncreateButtonCallback: function(item, index, items) {\nvar scene = item.scene;\n// var isFirstButton = (index === 0);\n// var isLastButton = (index === (items.length - 1));\n// container = ...\nreturn container;\n},\ncreateButtonCallbackScope: undefined,\n\neaseIn: 0,\n// easeIn: {\n//     duration: 500,\n//     orientation: undefined,\n//     ease: 'Cubic'\n// },\ntransitIn: undefined,\n// transitIn: function(menu, duration) {  },\n\neaseOut: 0,\n// easeOut: {\n//     duration: 100,\n//     orientation: undefined,\n//     ease: 'Linear'\n// },\ntransitOut: undefined,\n// transitOut: function(menu, duration) {  },\n\n// expandEvent: 'button.click',\n\n// pointerDownOutsideCollapsing: true,\n\n// childrenKey: 'children',\n\nname: '',\n// draggable: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • popup :
    • true : Pop-up menu, will layout automatically, push inside viewport. Default behavior.
    • false : Static menu, can put into another sizer, won't layout automatically.
  • orientation : Main orientation of the menu, default is 1 (top to bottom)
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Arrange buttons from left ot right.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Arrange buttons from top to bottom.
  • items : Array of item data for each button. Each item has
    • children : An array of items for sub-menu, optional. Can change by childrenKey parameter.
    • Other custom properties
  • createBackgroundCallback : Callback to return container object of menu's bckground.
    • Properties of items parameter
      • items.scene : Scene of this menu object.
  • createButtonCallback : Callback to return container object of each item.
    • Properties of item parameter
      • item.scene : Scene of this menu object.
      • Other custom properties
  • easeIn : Duration of expanding menu.
    • A number : Duration of ease, in milliseconds.
    • An object :
      • easeIn.duration : Duration of ease, in milliseconds.
      • easeIn.ease : Ease function, default is 'Cubic'
      • easeIn.orientation : Orientation of ease.
        • undefined : The same orientation with menu's orientation.
        • 'h', 'x', or 0 : Pop-up menu horizontally.
        • 'v', 'y', or 1 : Pop-up menu vertically.
  • transitIn : Tween behavior of expanding menu.
    • undefined : Expand menu by pop-up, default behavior.
    • Custom callback
      function(menu, duration) {\n\n}\n
  • easeOut : Duration of collapsing menu
    • A number : Duration of ease, in milliseconds.
    • An object :
      • easeOut.duration : Duration of ease, in milliseconds.
      • easeOut.ease : Ease function, default is 'Linear'
      • easeOut.orientation : Orientation of ease.
        • undefined : The same orientation with menu's orientation.
        • 'h', 'x', or 0 : Scale-down menu horizontally.
        • 'v', 'y', or 1 : Scale-down menu vertically.
  • transitOut : Tween behavior of collapsing menu.
    • undefined : Collapse menu by scale-down, default behavior.
    • Custom callback
      function(menu, duration) {\n\n}\n
  • expandEvent : Event name of expanding sub-menu.
    • 'button.click' : Default value
    • 'button.over'
  • pointerDownOutsideCollapsing :
    • true : Collapse all menus (popup:true), or sub-menus (popup:false) when pointer-down outside of all menus. Default behavior.
    • false : Ignore pointer-down outside detection.
  • childrenKey : Key of sub-menu in element of items.
    • children : Default value.
  • subMenuSide : Side of sub-menu
    • undefined : Determine side of sub-menu automatically.
    • 'right', or 0 : Put sub-menu at right side. Used with orientation is set to y.
    • 'left', or 2 : Put sub-menu at left side. Used with orientation is set to y.
    • 'up', or 3 : Put sub-menu at up side. Used with orientation is set to x.
    • 'down', or 1 : Put sub-menu at down side. Used with orientation is set to x.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
"},{"location":"ui-menu/#custom-class","title":"Custom class","text":"
  • Define class
    class MyMenu extends RexPlugins.UI.Menu {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var menu = new MyMenu(scene, config);\n
"},{"location":"ui-menu/#collapse","title":"Collapse","text":"
  • Collapse menu
    menu.collapse();\n
  • Collapse sub-menu
    menu.collapseSubMenu();\n
"},{"location":"ui-menu/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-menu/#events","title":"Events","text":"
  • Click button
    menu.on('button.click', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Game object of triggered button.
    • index : Index of triggered button.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-over button
    menu.on('button.over', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Game object of triggered button.
    • index : Index of triggered button.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Pointer-out button
    menu.on('button.out', function(button, index, pointer, event) {\n// ...\n}, scope);\n
    • button : Game object of triggered button.
    • index : Index of triggered button.
    • pointer : Pointer object.
    • Cancel remaining touched events : event.stopPropagation()
  • Expand(Pop-up start) sub-menu
    menu.on('expand', function(subMenu, parentButton) {\n// ....\n}, scope)\n
    • subMenu : Sub-menu.
    • parentButton : Game object of triggered button.
    • rootMenu : Root-menu
  • Pop-up root-menu, or sub-menu completely
    menu.on('popup.complete', function(menu) {\n// ....\n}, scope)\n
    • menu : Root-menu, or sub-menu
  • Collapse(Scale-down starting) root-menu, or sub-menu
    menu.on('collapse', function(subMenu, parentButton, rootMenu) {\n// ....\n}, scope)\n
    • subMenu : Sub-menu.
    • parentButton : Game object of triggered button.
    • rootMenu : Root-menu
  • Scale-down root-menu completely
    menu.on('scaledown.complete', function(rootMenu) {\n// ....\n}, scope)\n
    • rootMenu : Root-menu
"},{"location":"ui-nameinputdialog/","title":"Name input dialog","text":""},{"location":"ui-nameinputdialog/#introduction","title":"Introduction","text":"

Enter first name and last name via a dialog.

  • Author: Rex
  • Game object
"},{"location":"ui-nameinputdialog/#live-demos","title":"Live demos","text":"
  • Horizontal-layout
  • Vertical-layout
"},{"location":"ui-nameinputdialog/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-nameinputdialog/#install-plugin","title":"Install plugin","text":""},{"location":"ui-nameinputdialog/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add dialog object
    var dialog = scene.rexUI.add.nameInputDialog(style).resetDisplayContent(config);\n// var dialog = scene.rexUI.add.nameInputDialog(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-nameinputdialog/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add dialog object
    var dialog = scene.rexUI.add.nameInputDialog(style).resetDisplayContent(config);\n// var dialog = scene.rexUI.add.nameInputDialog(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-nameinputdialog/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { NameInputDialog } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add dialog object
    var dialog = new NameInputDialog(scene, config);\n// var dialog = new NameInputDialog(scene, config, creators);\nscene.add.existing(dialog);\ndialog.resetDisplayContent(config);\n
"},{"location":"ui-nameinputdialog/#add-dialog-object","title":"Add dialog object","text":"
var dialog = scene.rexUI.add.nameInputDialog({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\nbackground: backgroundStyle,\n// background: null,\n\ntitle: titleStyle,  // SimpleLabelConfig\n// title: null,\n\nfirstNameTitle: titleStyle,  // SimpleLabelConfig\n// firstNameTitle: null,\n\nfirstNameInput: inputTextStyle, // CanvasInputTextConfig\n\nlastNameTitle: titleStyle,  // SimpleLabelConfig\n// firstNameTitle: null,\n\nlastNameInput: inputTextStyle, // CanvasInputTextConfig\n\ncontent: contentStyle, // SimpleLabelConfig, or TextAreaStyle\n// content: null,\n\nbutton: SimpleLabelConfig,\n\n// Space\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\ntitle: 0,\ntitleLeft: 0,\ntitleRight: 0,\n\nnames: 0,\nnamesLeft: 0,\nnamesRight: 0,\nfirstName: 0,\nfirstNameTitle: 0,\nlastNamTitle: 0,\n\nactionsLeft: 0,\nactionsRight: 0,\naction: 0,\n},\n\nproportion: {\ntitle: 0,\nactions: 0,\n},\n\nexpand: {\ntitle: true,\nactions: false,\n},\n\nalign: {\ntitle: 'center',\nactions: 'center',\n},\n\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n},\n\nmodal: {\ncover: {\ncolor: 0x0,\nalpha: 0.8,\ntransitIn: function(gameObject, duration) { },\ntransitOut: function(gameObject, duration) { },\n},\n// cover: false, \n\n// When to close modal dialog?\ntouchOutsideClose: false,\nanyTouchClose: false,\ntimeOutClose: false,\nmanualClose: false,\n\nduration: {\nin: 200,\nhold: 2000,\nout: 200\n}\n\ntransitIn: 0,\ntransitOut: 0,\n\ndestroy: true,\n\ndefaultBehavior: true,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n\n// nameInputButtonIndex: 0,\n// cancelButtonIndex: 1,\n\n}, creators);\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as background element.
    • null : Don't create any game object.
  • title, firstNameTitle, lastNameTitle :
    • Styles of simple-label
    • null : Don't create any game object.
  • firstNameInput, lastNameInput :
    • Styles of canvas-input
  • button :
    • Styles of simple-label, optional.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.title : Space between title game object and below game object.
    • space.titleLeft, space.titleRight : Extra left/right padding of title game object.
    • space.names : Space between names and action buttons.
    • space.namesLeft, space.namesRight : Extra left/right padding of names.
    • space.firstName : Space between first name and last name.
    • space.firstNameTitle : Space between firstNameTitle and firstNameInput.
    • space.lastNameTitle : Space between lastNameTitle and lastNameInput.
    • space.action : Space between each action-button game objects.
  • proportion : Keep height of element, or expand height of element.
    • proportion.title : Set to 1 to expand height of title. Default is 0.
    • proportion.actions : Set to 1 to expand height of actions. Default is 0.
  • expand : Expand width of element
    • expand.title : Set true to expand width of title game object. Default is true.
    • expand.actions : Set true to expand width of actions game object. Default is false.
  • align : Align element
    • align.title
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value. Will add Spaces at right and left sides.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center. Will add a Space at right side.
    • align.actions : Align action game objects to 'left'/'center'/'right', if expand.actions is false.
  • click: Configuration of button clicking.
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
  • modal : Configuration of modal, See Modal behavior.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false..
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • nameInputButtonIndex, cancelButtonIndex : Button index for firing 'nameInput', 'cancel' events. Default values are 0, 1.
  • creators : Callbacks for creating components.
    {\nbackground: undefined,\ntitle: undefined,\nfirstNameTitle: undefined,\nlastNameTitle: undefined,\nbutton: undefined,\n}\n
    • creators.background : Callback to create background of dialog. Default behavior is creating a round-rectangle-shape.
      function(scene, config)  {\nreturn gameObject;\n}\n
    • creators.title, creators.firstNameTitle, creators.lastNameTitle, creators.button : Creators of simple-label, included these properties
      {\nbackground: undefined,\ntext: undefined,\nicon: undefined,\naction: undefined,\n}\n
"},{"location":"ui-nameinputdialog/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDialog extends RexPlugins.UI.NameInputDialog {\nconstructor(scene, config, creators) {\nsuper(scene, config, creators);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var dialog = new MyDialog(scene, config, creators);\n
"},{"location":"ui-nameinputdialog/#reset-display-content","title":"Reset display content","text":"
dialog.resetDisplayContent({\ntitle: '',\nfirstNameTitle: '',\nlastNameTitle: '',\nbutton: '',\n\nfirstName: '',\nlastName: '',\n});\n

or

dialog.resetDisplayContent({\ntitle: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nfirstNameTitle: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nlastNameTitle: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nbutton: {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n},\n\nfirstName: '',\n\nlastName: ''\n});\n
  • title, firstNameTitle, lastNameTitle : Display content
    • A string : Set text of simple lable
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
    • null : Hide title or firstNameTitle, lastNameTitle element.
  • button : Display content
    • A string : Set text of simple lable
    • Configuration of simpleLabel.resetDisplayContent(config) : Set icon, text, action icon of simple label.
  • firstName, lastNmae : A string

Run dialog.layout() after this method, to layout children again.

"},{"location":"ui-nameinputdialog/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

dialog.layout();\n

See also - dirty

"},{"location":"ui-nameinputdialog/#modal","title":"Modal","text":"

Pop this dialog as modal dialog, close this modal dialog when clicking action button.

dialog.modal(onClose);  // Use default modal config\n

or

dialog.modal({\n// cover: {\n//     color: 0x0,\n//     alpha: 0.8,\n//     transitIn: function(gameObject, duration) { },\n//     transitOut: function(gameObject, duration) { },\n// },\n// cover: false, \n\n// When to close modal dialog?\n// touchOutsideClose: false,\n// anyTouchClose: false,\n// timeOutClose: false,\n// manualClose: false,\n\n// duration: {\n//     in: 200,\n//     hold: 2000,\n//     out: 200\n// }\n\n// transitIn: 0,\n// transitOut: 0,\n\n// destroy: true\n}, onClose);\n

or

dialog\n.modalPromise(config)\n.then(function(data){\nvar firstName = data.firstName;\nvar lastName = data.lastName;\n})\n
  • config : See Modal behavior
    • config.defaultBehavior :
      • undefined, or true : Will close modal dialog when clicking any action button.
      • false : Disable default behavior.
  • onClose : Callback when closing modal dialog
    function(data) {\nvar firstName = data.firstName;\nvar lastName = data.lastName;\n}\n
    • data : Contains these properties
      • data.firstName : Enter string of firstNameInput.
      • data.lastName : Enter string of lastNameInput.
"},{"location":"ui-nameinputdialog/#names-input","title":"Names input","text":"
  • First name
    • Get
      var firstName = dialog.firstName;\n
    • Set
      dialog.setFirstName(value);\n// data.firstName = value;\n
  • Last name
    • Get
      var lastName = dialog.lastName;\n
    • Set
      dialog.setLastName(value);\n// data.lastName = value;\n
"},{"location":"ui-nameinputdialog/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = dialog.getElement('background');\n
    • Title game object
      var title = dialog.getElement('title');\n
    • FirstName-title game object
      var firstNameTitle = dialog.getElement('firstNameTitle');\n
    • FirstName-input game object
      var firstNameInput = dialog.getElement('firstNameInput');\n
    • LastName-title game object
      var lastNameTitle = dialog.getElement('lastNameTitle');\n
    • LastName-input game object
      var lastNameInput = dialog.getElement('lastNameInput');\n
    • Button game object
      var button = dialog.getElement('button');\n
  • Get by name
    var gameObject = dialog.getElement('#' + name);\n// var gameObject = dialog.getElement('#' + name, recursive);\n
    or
    var gameObject = dialog.getByName(name);\n// var gameObject = dialog.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-nameinputdialog/#other-properties","title":"Other properties","text":"

See dialog, sizer object, base sizer object, container-lite.

"},{"location":"ui-nameinputdialog/#events","title":"Events","text":"
  • Click confirm button
    dialog.on('confirm', function (data) {\nvar firstName = data.firstName;\nvar lastName = data.lastName;\n}, scope);\n
    • data : See modal
"},{"location":"ui-namevaluelabel/","title":"Name value label","text":""},{"location":"ui-namevaluelabel/#introduction","title":"Introduction","text":"

A container with name text, value text in a row, with a horizontal line progress bar, and an icon, background.

  • Author: Rex
  • Game object
"},{"location":"ui-namevaluelabel/#live-demos","title":"Live demos","text":"
  • Name-value label
  • Custom bar
"},{"location":"ui-namevaluelabel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-namevaluelabel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-namevaluelabel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add label object
    var label = scene.rexUI.add.nameValueLabel(config);\n
"},{"location":"ui-namevaluelabel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add label object
    var label = scene.rexUI.add.nameValueLabel(config);\n
"},{"location":"ui-namevaluelabel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { NameValueLabel } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add label object
    var label = new NameValueLabel(scene, config);\nscene.add.existing(label);\n
"},{"location":"ui-namevaluelabel/#add-label-object","title":"Add label object","text":"
var label = scene.rexUI.add.nameValueLabel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundGameObject,\nicon: iconGameObject,\niconMask: false,\n\nnameText: nameTextGameObject,\nvalueText: valueTextGameObject,\n// valueTextFormatCallback: function(value, min, max) {\n//     return `${value}/${max}`;\n// },\n// valueTextFormatCallback: null,\n\n// barShape: 'line',   // 'line', or 'circle'\n\n// line bar\nbar: {        trackColor: undefined,\ntrackThickness: 2,\ntrackStrokeColor: undefined,\nbarColor: undefined,\nbarColor2: undefined,\n\nskewX: 0,\n\nrtl: false,\n\neaseValue: {\nduration: 0,\nease: 'linear'\n},\n}, // circle bar\n/*\n    bar: {\n        barColor: undefined,\n        barColor2: undefined,\n        trackColor: undefined,\n        centerColor: undefined,\n        thickness: 0.2,\n        startAngle: Phaser.Math.DegToRad(270),\n        endAngle: Phaser.Math.DegToRad(270+360),\n        anticlockwise: false,\n    }\n    */\n\n// bar: CustomProgressGameObject,\n\n// bar: undefined,\n\naction: actionGameObject,\nactionMask: false,\n\nalign: {        text: 'bottom',  // 'top', 'center', 'bottom'\n},\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0, iconTop: 0, iconBottom: 0,\nname: 0, value: 0,\nbar:0, barBottom: 0, barLeft: 0, barRight: 0,\ntext: 0,\nactionTop: 0, actionBottom: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • nameText : Game object of nameText.
    • OriginX of nameText will be set to 0.
    • Empty text will be set to a space character ' '. To preserve height of this text game object.
  • valueText : Game object of valueText.
    • OriginX of nameText will be set to 1.
    • Empty text will be set to a space character ' '. To preserve height of this text game object.
  • valueTextFormatCallback : Callback to return a string set to valueText game object when invokeing label.setValue(value, min, max) method.
    • A callback
      function(value, min, max) {\nreturn `${value}/${max}`;\n}\n
    • null, or false : Don't set valueText game object.
  • barShape : 'line' or 'circle'.
  • bar : Game object of bar, or config of horizontal line progress bar, or config of circular progress bar or undefined.
    • Config of horizontal line progress bar
      • bar.trackColor : Fill color of bar's track, in number or css string value.
      • bar.trackStrokeColor : Stroke color of bar's track, in number or css string value.
      • bar.trackThickness : Stroke line width of bar's track.
      • bar.barColor, bar.barColor2 : Fill color of bar, in number or css string value. Assign gradient start color by barColor2.
      • bar.skewX : Horizontal skew of track and bar.
      • bar.rtl :
        • false : Bar starts from left side. Default behavior.
        • true : Bar starts from right side.
    • Config of circular progress bar
      • bar.barColor, bar.barColor2 : Fill color of circular bar, in number or css string value. Assign gradient start color by barColor2.
      • bar.trackColor : Color of circular track, in number or css string value.
      • bar.centerColor : Color of center circle, in number or css string value.
      • bar.thickness : 0 ~ 1, thickness of circular bar. Default value is 0.2 (0.2*radius)
      • bar.startAngle : Start angle of circular bar, in radians. Default value is 270 degrees.
      • bar.endAngle : End angle of circular bar, in radians. Default value is 270+360 degrees.
      • bar.anticlockwise : Set true to put anticlockwise circular bar. Default value is false.
    • (CustomProgress) Game object.
    • undefined : No bar game object.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • align :
    • align.text : Alignment of nameText, valueText game objects.
      • 'top', 'center', or 'bottom'. Default value is 'bottom'.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.icon : Space between icon game object and text game object.
    • space.iconTop, space.iconBottom : Space around icon game object.
    • space.name : Left space of nameText game object.
    • space.value : Right space of valueText game object.
    • space.bar, space.barLeft, space.barRight, space.barBottom : Space around bar game object.
    • space.text : Space between text game object and action icon game object.
    • space.actionTop, space.actionBottom : Space around action game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-namevaluelabel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyNameValueLabel extends RexPlugins.UI.NameValueLabel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var label = new MyNameValueLabel(scene, config);\n
"},{"location":"ui-namevaluelabel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

label.layout();\n

See also - dirty

"},{"location":"ui-namevaluelabel/#name-text","title":"Name text","text":"
  • Get nameText string
    var s = label.nameText;\n
  • Set nameText string
    label.setNameText(s);\n
    or
    label.nameText = s;\n
"},{"location":"ui-namevaluelabel/#value-text","title":"Value text","text":"
  • Get valueText string
    var s = label.valueText;\n
  • Set valueText string
    label.setValueText(s);\n
    or
    label.valueText = s;\n
"},{"location":"ui-namevaluelabel/#bar","title":"Bar","text":"
  • Get bar value
    var s = label.barValue;\n
  • Set bar value
    label.setBarValue(value);  // 0~1\n
    or
    label.setBarValue(value, min, max);  // min~max\n
    or
    label.barValue = t;  // 0~1\n
  • Ease bar value
    label.easeBarValueTo(value);  // 0~1\n
    or
    label.easeBarValueTo(value, min, max);    // min~max\n
"},{"location":"ui-namevaluelabel/#icon-texture","title":"Icon texture","text":"
  • Set texture
    label.setTexture(key);\n// label.setTexture(key, frame);\n
  • Set texture via texture object
    label.setTexture(texture);\n// label.setTexture(texture, frame);\n
  • Get texture, frame.
    var texture = label.texture;\nvar frame = label.frame;\n
  • Get texture key, frame name.
    var textureKey = label.texture.key;\nvar frameName = label.frame.name;\n
"},{"location":"ui-namevaluelabel/#set-value","title":"Set value","text":"
  • Set valueText game object and bar game object.
    label.setValue(value, min, max);\n// label.setValue(value);  // min, max are not changed\n
    or
    label.setValue(value);  // min, max are not changed\n
    Will invoke valueTextFormatCallback callback.
  • Ease valueText game object and bar game object.
    label\n.setEaseValueDuration(duration)\n.easeValueTo(value, min, max);\n
    or
    label\n.setEaseValueDuration(duration)\n.easeValueTo(value);  // min, max are not changed\n
    Will invoke valueTextFormatCallback callback.
  • Get values
    var value = label.value;\nvar max = label.maxValue;\nvar min = label.minValue;\n
    • value will ease during label.easeValueTo() task.
"},{"location":"ui-namevaluelabel/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = label.getElement('background');\n
    • Icon game object
      var icon = label.getElement('icon');\n
    • NameText game object
      var nameTextObject = label.getElement('name');\n
    • ValueText game object
      var valueTextObject = label.getElement('value');\n
    • Bar game object
      var textObject = label.getElement('bar');\n
    • Action icon game object
      var action = label.getElement('action');\n
  • Get by name
    var gameObject = label.getElement('#' + name);\n// var gameObject = label.getElement('#' + name, recursive);\n
    or
    var gameObject = label.getByName(name);\n// var gameObject = label.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-namevaluelabel/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-numberbar/","title":"Number bar","text":""},{"location":"ui-numberbar/#introduction","title":"Introduction","text":"

A container with an icon, slider, text, and background.

  • Author: Rex
  • Game object
"},{"location":"ui-numberbar/#live-demos","title":"Live demos","text":"
  • Number bar
  • Color picker
  • Video player
"},{"location":"ui-numberbar/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-numberbar/#install-plugin","title":"Install plugin","text":""},{"location":"ui-numberbar/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin(\n\"rexuiplugin\",\n\"https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js\",\n\"rexUI\",\n\"rexUI\"\n);\n
  • Add number bar object
    var numberBar = scene.rexUI.add.numberBar(config);\n
"},{"location":"ui-numberbar/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from \"phaser3-rex-plugins/templates/ui/ui-plugin.js\";\nvar config = {\n// ...\nplugins: {\nscene: [\n{\nkey: \"rexUI\",\nplugin: UIPlugin,\nmapping: \"rexUI\",\n},\n// ...\n],\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add number bar object
    var numberBar = scene.rexUI.add.numberBar(config);\n
"},{"location":"ui-numberbar/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { NumberBar } from \"phaser3-rex-plugins/templates/ui/ui-components.js\";\n
  • Add number bar object
    var sizer = new NumberBar(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-numberbar/#add-number-bar-object","title":"Add number bar object","text":"
var numberBar = scene.rexUI.add.numberBar({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\nicon: iconGameObject,\niconMask: false,\nslider: {\nbackground: backgroundGameObject,\n/* \n        background: { \n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\ntrack: trackGameObject,\n/* \n        track: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */    indicator: indicatorGameObject,\n/* \n        indicator: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\nthumb: thumbGameObject,\n/* \n        thumb: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\ninput: 'drag',\ngap: undefined,        easeValue: {\nduration: 0,\nease: 'Linear'\n},\n}\ntext: textGameObject,\n\nvaluechangeCallback: function(newValue, oldValue, numberBar) {\n// numberBar.text = Math.round(Phaser.Math.Linear(0, 100, newValue));\n}\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0,\nslider: 0,\n},\n\nenable: true,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of numberBar.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
  • slider : Slider game object which composed of
    • slider.width : Fixed width of slider, optional. Width of slider will be extended if this value is not set.
    • slider.background :
      • Game object of background, optional. This background game object will be resized to fit the size of slider.
      • A plain object to create round rectangle shape
        { radius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.track :
      • Game object of track, optional. This track game object will be resized to fit the size of slider, with space.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.indicator :
      • Game object of indicator, optional.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.thumb :
      • Game object of thumb, optional.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.input :
      • 'pan', 'drag', or 0 : Control knob by panning/dragging thumb game object. Default setting.
      • 'click', or 1 : Control slider by touching track game object.
      • 'none', or -1 : Disable sider controlling.
    • slider.gap : Snap a value to nearest grid slice, using rounding.
      • undefined : Disable this feature.
    • slider.easeValue : Easing value when input is 'click'.
      • slider.easeValue.duration : Duration of value easing, default is 0 (no easing).
      • slider.easeValue.ease : Ease function, default is 'Linear'.
  • text : Game object of text, optional.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds
    • space.icon : Space between icon game object and text game object.
    • space.slider : Space between slider game object and text game object.
  • valuechangeCallback : callback function when value changed.
  • enable : Set false to disable controlling.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-numberbar/#custom-class","title":"Custom class","text":"
  • Define class
    class MyNumberBar extends RexPlugins.UI.NumberBar {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var numberBar = new MyNumberBar(scene, config);\n
"},{"location":"ui-numberbar/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

numberBar.layout();\n

See also - dirty

"},{"location":"ui-numberbar/#get-element","title":"Get element","text":"
  • Get element
  • Background game object
    var background = numberBar.getElement(\"background\");\n
  • Icon game object
    var icon = numberBar.getElement(\"icon\");\n
  • Slider game object
    • Slider background
      var sliderBackground = numberBar.getElement(\"slider.background\");\n
    • Slider track
      var sliderTrack = numberBar.getElement(\"slider.track\");\n
    • Slider indicator
      var sliderIndicator = numberBar.getElement(\"slider.indicator\");\n
    • Slider thumb
      var sliderThumb = numberBar.getElement(\"slider.thumb\");\n
  • Text game object
    var textObject = numberBar.getElement(\"text\");\n
  • Get by name
    var gameObject = numberBar.getElement(\"#\" + name);\n// var gameObject = numberBar.getElement('#' + name, recursive);\n
    or
    var gameObject = numberBar.getByName(\"#\" + name);\n// var gameObject = numberBar.getByName(name, recursive);\n
  • recursive : Set true to search all children recursively.
"},{"location":"ui-numberbar/#enable","title":"Enable","text":"
  • Get
    var enable = numberBar.enable;\n
  • Set
    numberBar.setEanble(enable);\n
    or
    numberBar.enable = enable;\n
"},{"location":"ui-numberbar/#value","title":"Value","text":"

Change value will also change the position of slider thumb and width of slider indicator.

  • Get value
    var value = numberBar.getValue(min, max); // value : min ~ max\n
    or
    var value = numberBar.getValue(); // value: 0 ~ 1\n
    or
    var value = numberBar.value; // value: 0 ~ 1\n
  • Set value
    numberBar.setValue(value, min, max); // value: min ~ max\n
    or
    numberBar.setValue(value); // value: 0 ~ 1\n
    or
    numberBar.value = value; // value: 0 ~ 1\n
  • Increase value
    numberBar.addValue(inc, min, max); // inc: min ~ max\n
    or
    numberBar.addValue(inc); // inc: 0 ~ 1\n
    or
    numberBar.value += inc; // inc: 0 ~ 1\n
"},{"location":"ui-numberbar/#ease-value","title":"Ease value","text":"
  • Ease value to
    numberBar.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    numberBar.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    numberBar.stopEaseValue();\n
  • Set ease duration
    numberBar.setEaseValueDuration(duration);\n
  • Set ease function
    numberBar.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"ui-numberbar/#text","title":"Text","text":"
  • Get text string
    var s = numberBar.text;\n
  • Set text string
    numberBar.setText(s);\n
    or
    numberBar.text = s;\n
"},{"location":"ui-numberbar/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-numberbar/#events","title":"Events","text":"
  • On value changed
    numberBar.on('valuechange', function (newValue, oldValue, numberBar) {\n// numberBar.text = Math.round(Phaser.Math.Linear(0, 100, newValue));\n}, scope);\n
  • On input start
    numberBar.on('inputstart', function(pointer) {\n\n}, scope);\n
  • On input end
    numberBar.on('inputend', function(pointer) {\n\n}, scope);\n
"},{"location":"ui-overlapsizer/","title":"Overlap sizer","text":""},{"location":"ui-overlapsizer/#introduction","title":"Introduction","text":"

Layout children game objects overlapped.

  • Author: Rex
  • Game object
"},{"location":"ui-overlapsizer/#live-demos","title":"Live demos","text":"
  • Overlap
  • Aspect ratio
  • Fit viewport
"},{"location":"ui-overlapsizer/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-overlapsizer/#install-plugin","title":"Install plugin","text":""},{"location":"ui-overlapsizer/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add sizer object
    var sizer = scene.rexUI.add.overlapSizer(config);\n
"},{"location":"ui-overlapsizer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add sizer object
    var sizer = scene.rexUI.add.overlapSizer(config);\n
"},{"location":"ui-overlapsizer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { OverlapSizer } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add sizer object
    var sizer = new OverlapSizer(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-overlapsizer/#add-sizer-object","title":"Add sizer object","text":"
var sizer = scene.rexUI.add.overlapSizer({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,    \n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n

or

var sizer = scene.rexUI.add.overlapSizer(x, y, {\n// width: undefined,\n// height: undefined,\n// anchor: undefined,    \n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n

or

var sizer = scene.rexUI.add.overlapSizer(x, y, width, height, {\n// anchor: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-overlapsizer/#custom-class","title":"Custom class","text":"
  • Define class
    class MySizer extends RexPlugins.UI.OverlapSizer {\nconstructor(scene, x, y, minWidth, minHeight, config) {\nsuper(scene, x, y, minWidth, minHeight, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var sizer = new MySizer(scene, x, y, minWidth, minHeight, config);\n
"},{"location":"ui-overlapsizer/#add-background","title":"Add background","text":"
sizer.addBackground(child);\n

or

sizer.addBackground(child, {left: 0, right: 0, top: 0, bottom: 0}, key);\n
  • left, right, top, bottom : Extra padded space. Default is 0.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
    • items is a reserved key, which is used to store all children.
"},{"location":"ui-overlapsizer/#add-child","title":"Add child","text":"

Add a game obejct to sizer

sizer.add(child);\n

or

sizer.add(child,\n{\nkey: undefined,\nalign: 'center',     offsetX: 0,\noffsetY: 0,   padding: {left: 0, right: 0, top: 0, bottom: 0},\nexpand: true,        // expand: {width, height}\nminWidth: undefined,\nminHeight: undefined,\naspectRatio: 0,\n}\n);\n

or

sizer.add(child, key, align, padding, expand, minWidth, minHeight, offsetX, offsetY);\n
  • child : A game object.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Use current timestamp as key.
    • items is a reserved key, which is used to store all children.
  • align :
    • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
    • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
    • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game object at top-center.
    • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at bottom-center.
    • 'left-top' , or Phaser.Display.Align.TOP_LEFT : Align game object at left-top.
    • 'left-center' , or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
    • 'left-bottom' , or Phaser.Display.Align.BOTTOM_LEFT : Align game object at left-bottom.
    • 'center-top' , or Phaser.Display.Align.TOP_CENTER : Align game object at center-top.
    • 'center-center' , or Phaser.Display.Align.CENTER : Align game object at center-center.
    • 'center-bottom' , or Phaser.Display.Align.BOTTOM_CENTER : Align game object at center-bottom.
    • 'right-top' , or Phaser.Display.Align.TOP_RIGHT : Align game object at right-top.
    • 'right-center' , or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • 'right-bottom' , or Phaser.Display.Align.BOTTOM_RIGHT : Align game object at right-bottom.
  • offsetX, offsetY : Apply offset to x, y coordinate after alignment.
  • padding : Extra padded space. Default is 0.
    • A number for left/right/top/bottom bounds,
    • Or a plain object.
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • expand :
    • Boolean value
      • true : Expand width and height of child. Default value.
      • false : Don't expand width or height of child.
    • A plain object
      • {width: true} : Only expand width of child.
      • {height: true} : only expand height of child.
      • {width: true, height: true} : Expand width and height of child.
  • minWidth : Minimum width of normal (non-sizer) game object, used when expand width mode. Default value is current display width.
  • minHeight : Minimum height of normal (non-sizer) game object, used when expand height mode. Default value is current display height.
  • aspectRatio : Keep aspect ratio after layout.
    • 0 : Don't keep aspect ratio. Default behavior.
    • true : Keep aspect ratio via current size.
    • A number : Keep aspect ratio via given value.
"},{"location":"ui-overlapsizer/#layout-children","title":"Layout children","text":"

Arrange position of all children.

sizer.layout();\n

See also - dirty

"},{"location":"ui-overlapsizer/#hide","title":"Hide","text":"
  • Set invisible, won't layout it
    sizer.hide();\n
    or
    sizer.hide(gameObject);\n
  • Set visible, will layout it
    sizer.show();\n
    or
    sizer.show(gameObject);\n
"},{"location":"ui-overlapsizer/#remove-child","title":"Remove child","text":"
  • Remove a child
    sizer.remove(child);\n
    or
    sizer.remove(key);\n
  • Remove and destroy a child
    sizer.remove(child, true);\n
    or
    sizer.remove(key, true);\n
  • Remove all children
    sizer.removeAll();\n
  • Remove and destroy all children
    sizer.removeAll(true);\n
  • Remove all children and backgrounds
    sizer.clear();\n
  • Remove and destroy all children and backgrounds
    sizer.clear(true);\n
  • Remove from parent sizer
    sizer.removeFromParentSizer();\n
"},{"location":"ui-overlapsizer/#get-element","title":"Get element","text":"
  • Get element
  • A child
    var item = sizer.getElement(key);\n
    or
    var item = sizer.getElement('items[' + key + ']');\n
    • All children items
      var items = sizer.getElement('items');\n
  • Get by name
    var gameObject = sizer.getElement('#' + name);\n// var gameObject = sizer.getElement('#' + name, recursive);\n
    or
    var gameObject = sizer.getByName(name);\n// var gameObject = sizer.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-overlapsizer/#get-child-index","title":"Get child index","text":"
var index = sizer.getChildIndex(child);\n
  • index : A number, string, or null.
"},{"location":"ui-overlapsizer/#other-properties","title":"Other properties","text":"

See base sizer object, container-lite.

"},{"location":"ui-overview/","title":"Overview","text":""},{"location":"ui-overview/#install-ui-plugins","title":"Install ui plugins","text":""},{"location":"ui-overview/#install-from-minify-file","title":"Install from minify file","text":"
  1. Download minify file (link).
  2. Install ui plugin in preload stage
    scene.load.scenePlugin({\nkey: 'rexuiplugin',\nurl: filePath,\nsceneKey: 'rexUI'\n});\n
    • key : Must be 'rexuiplugin'
"},{"location":"ui-overview/#install-from-npm-package","title":"Install from npm package","text":"
  1. Install rex plugins
    npm i phaser3-rex-plugins\n
  2. Install ui plugin in configuration of game
    import RexUIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\n\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: RexUIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
"},{"location":"ui-overview/#using-typescript-declaration-file","title":"Using typescript declaration file","text":"
import 'phaser';\nimport RexUIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\ndeclare module 'phaser' {\ninterface Scene {\nrexUI: RexUIPlugin;\n}\n}\n

or

import RexUIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\n\nclass Game extends Phaser.Scene {\nrexUI: RexUIPlugin;  // Declare scene property 'rexUI' as RexUIPlugin type\n\ncreate() {\nvar sizer = this.rexUI.add.sizer({\n// ...\n})\n}\n}\n\nvar game = new Phaser.Game({\nscene: Game,\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: RexUIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n});\n
  • 'phaser3-rex-plugins/templates/ui/ui-plugin' : Factories of rexUI components.
  • 'phaser3-rex-plugins/templates/ui/ui-components' : Class of rexUI components.
    import { Sizer } from 'phaser3-rex-plugins/templates/ui/ui-components';\n

See this example

"},{"location":"ui-overview/#list-of-ui-plugins","title":"List of ui plugins","text":""},{"location":"ui-overview/#ui-components","title":"UI components","text":"
  1. Badge label: A container with badges above a main item.
  2. Buttons: A container with a group of buttons.
  3. Color componets: Edit color value by RGB, or HSV input fields.
  4. Color input: Color number or color string input field.
  5. Color picker: Pick color value from H and SV palettes.
  6. Confirm action button: Create a modal confirm dialog temporary, invoke callback after clicking button.
  7. Confirm dialog: Using json style to create confirm dialog.
  8. Dialog: A container with a title, content, buttons and background.
  9. Drop down list: A label can open a drop-down list panel.
  10. Exp bar: Disply experience bar on NameValueLabel.
  11. File selector button: A transparent file chooser button above a Label.
  12. Fix-width-buttons: A container with a group of fix-width buttons.
  13. Fix-width-sizer: Layout children game objects into lines.
  14. Folder: A container with a title, foldable child, and background.
  15. Grid-buttons: A container with a group of buttons in grids.
  16. Grid-sizer: Layout children game objects in grids.
  17. Grid-table: A container with a grid table, slider, and scroller.
  18. Holy grail: Layout elements in Holy grail style.
  19. Knob: A knob button based on circular progress.
  20. Label: A container with an icon, text, and background.
  21. Menu: A container with buttons and sub-menu.
  22. Name-input dialog: Enter first name and last name via a dialog.
  23. Name-value label: A container with name text, value text in a row, with a horizontal line progress bar, and an icon, background.
  24. Image input label: A container with a canvas icon, text, and background. Click icon to popup a (image) file chooser dialog, display selected image on canvas.
  25. Number-bar: A container with an icon, slider, text, and background.
  26. Overlap sizer: Layout children game objects overlapped.
  27. Pages: A container with pages, only current page is visible.
  28. Perspective card: A container with front and back faces.
  29. Scroll-able panel: A container with a panel, slider, and scroller.
  30. Simple drop down list: Using plain object to create drop down list.
  31. Simple label: Using json style to create label.
  32. Simple title label: Using json style to create title label.
  33. Simple text box: Using json style to create text box.
  34. Sizer: Layout children game objects.
  35. Slider: A container with a track, indicator, thumb and background.
  36. Split panels: A container with left(top) panel, right(bottom) panel, splitter, and background. Drag splitter to resize with left(top) panel, right(bottom) panel.
  37. Tab-pages: A container with tabs and pages, only current page is visible.
  38. Tabs: A container with 4 groups of buttons around a center panel.
  39. TextArea: A container with a text, slider, and scroller.
  40. TextAreaInput: A container with a canvasInput, and slider.
  41. Textbox: A container with an icon, (typing and paging) text, and background.
  42. Title label: A container with title, text in two rows, and an icon, background.
  43. Toast: Show text message for a short while.
  44. Toast queue: Queue messages for a short while.
  45. Trees: A container with trees and leaf-nodes.
  46. Tweaker: Fine-tuning properties of target object.

Scroll-able table

There are 3 kinds of scroll-able tables :

  • Grid-table only creates visible objects. It is suitable for large table.
  • Grid-sizer adds all objects. Put this grid-sizer into scroll-able panel to have a scroll-able table.
  • Fixwidth-sizer adds all objects. Put this fixwidth-sizer into scroll-able panel to have a scroll-able table.
"},{"location":"ui-overview/#basic-container","title":"Basic container","text":"
  1. ContainerLite: Control the position and angle of children game objects.
    var container = scene.rexUI.add.container(x, y);\n
    or
    class MyContainer extends RexPlugins.UI.Container {\nconstructor(scene, x, y, width, height, children) {\nsuper(scene, x, y, width, height, children);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
"},{"location":"ui-overview/#background-objects","title":"Background objects","text":"
  1. Round-rectangle: Round rectangle shape.
    var shape = scene.rexUI.add.roundRectangle(x, y, width, height, radius, fillColor);\n
    or
    class MyRoundRectangle extends RexPlugins.UI.RoundRectangle {\nconstructor(scene, x, y, width, height, radius, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, radius, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  2. Nine-patch: Stretchable imaage.
    var ninePatch = scene.rexUI.add.ninePatch(x, y, width, height, key, columns, rows, config);\n
    var ninePatch = scene.rexUI.add.ninePatch2(x, y, width, height, key, columns, rows, config);\n
    or
    class MyNinePatch extends RexPlugins.UI.NinePatch {\nconstructor(scene, x, y, width, height, key, columns, rows, config) {\nsuper(scene, x, y, width, height, key, columns, rows, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
    class MyNinePatch extends RexPlugins.UI.NinePatch2 {\nconstructor(scene, x, y, width, height, key, columns, rows, config) {\nsuper(scene, x, y, width, height, key, columns, rows, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  3. Quad shape: Quad shape, offsets can be given on four vertices, and additional points can be added on the four sides.
    var quad = scene.rexUI.add.quadShapes(x, y, width, height, fillColor, fillAlpha);\n
    or
    class MyQuadShape extends RexPlugins.UI.QuadShape {\nconstructor(scene, x, y, width, height, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  4. Custom shapes: Custom shapes on shape.
    var customShapes = scene.rexUI.add.customShapes(x, y, width, height, config);\n
    or
    class MyCustomShapes extends RexPlugins.UI.CustomShapes {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  5. Custom progress: Custom progress on shape.
    var customProgress = scene.rexUI.add.customProgress(x, y, width, height, config);\n
    or
    class MyCustomProgress extends RexPlugins.UI.CustomProgress {\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}    
  6. Canvas-round-rectangle: Round rectangle on canvas.
    var shape = scene.rexUI.add.roundRectangleCanvas(x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n
    or
    class MyRoundRectangleCanvas extends RexPlugins.UI.RoundRectangleCanvas {\nconstructor(scene, x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient) {\nsuper(scene, x, y, width, height, radiusConfig, fillStyle, strokeStyle, lineWidth, fillColor2, isHorizontalGradient);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  7. Cover: Rectangle shape covered full window, and block all touch events.
    var shape = scene.rexUI.add.cover(config);\n
    or
    class MyCover extends RexPlugins.UI.Cover {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
"},{"location":"ui-overview/#canvasshape-objects","title":"Canvas/Shape objects","text":"
  1. Canvas: Drawing on canvas.
    var canvas = scene.rexUI.add.canvas(x, y, width, height);\n// var canvas = scene.rexUI.add.canvas(x, y, width, height);\n
    or
    class MyCanvas extends RexPlugins.UI.Canvas {\nconstructor(scene, x, y, width, height) {\nsuper(scene, x, y, width, height);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  2. Circle mask image: Load a texture, then apply a circle mask.
    var image = scene.rexUI.add.circleMaskImage(x, y, key, frame, config);\n
    or
    class MyImage extends RexPlugins.UI.CircleMaskImage {\nconstructor(scene, x, y, key, frame, config) {\nsuper(scene, x, y, key, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  3. Alpha mask image: Load a texture, then apply an alpha mask from another texture.
    var image = scene.rexUI.add.alphaMaskImage(x, y, key, frame, config);\n
    or
    class MyImage extends RexPlugins.UI.AlphaMaskImage {\nconstructor(scene, x, y, key, frame, config) {\nsuper(scene, x, y, key, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  4. Circular progress shape: Circular progress bar shape.
    var circularProgress = scene.rexUI.add.circularProgress(x, y, radius, barColor, value, config);\n
    or
    class MyCircularProgress extends RexPlugins.UI.CircularProgress {\nconstructor(scene, x, y, radius, barColor, value, config) {\nsuper(scene, x, y, radius, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  5. Circular progress canvas: Circular progress bar on canvas
    var circularProgress = scene.rexUI.add.circularProgressCanvas(x, y, radius, barColor, value, config);\n
    or
    class MyCircularProgress extends RexPlugins.UI.CircularProgressCanvas {\nconstructor(scene, x, y, radius, barColor, value, config) {\nsuper(scene, x, y, radius, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  6. Line progress shape: Horizontal line progress bar shape.
    var lineProgress = scene.rexUI.add.lineProgress(x, y, width, height, barColor, value, config);\n
    or
    class MyLineProgress extends RexPlugins.UI.LinerProgress {\nconstructor(scene, x, y, width, height, barColor, value, config) {\nsuper(scene, x, y, width, height, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  7. Line progress canvas: Horizontal line progress bar filled with gradient color on canvas.
    var lineProgress = scene.rexUI.add.lineProgressCanvas(x, y, width, height, barColor, value, config);\n
    or
    class MyLineProgress extends RexPlugins.UI.LinerProgressCanvas {\nconstructor(scene, x, y, width, height, barColor, value, config) {\nsuper(scene, x, y, width, height, barColor, value, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  8. Checkbox: Checkbox input with drawing checker path animation.
    var checkbox = scene.rexUI.add.checkbox(x, y, width, height, color, config);\n
    or
    class MyCheckbox extends RexPlugins.UI.Checkbox {\nconstructor(scene, x, y, width, height, color, config) {\nsuper(scene, x, y, width, height, color, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  9. Toggle switch: Toggle-switch input.
    var toggleSwitch = scene.rexUI.add.toggleSwitch(x, y, width, height, color, config);\n
    or
    class MyToggleSwitch extends RexPlugins.UI.ToggleSwitch {\nconstructor(scene, x, y, width, height, color, config) {\nsuper(scene, x, y, width, height, color, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  10. Triangle: Trangle shape inside a rectangle bounds.
    var triangle = scene.rexUI.add.triangle(x, y, width, height, fillColor, fillAlpha);\n
    or
    class MyTriangle extends RexPlugins.UI.Triangle {\nconstructor(scene, x, y, width, height, fillColor, fillAlpha) {\nsuper(scene, x, y, width, height, fillColor, fillAlpha);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  11. AIO-spinner
    var spinner = scene.rexUI.add.aioSpinner(config);\n
    or
    class MySpinner extends RexPlugins.UI.AIOSpinner {\nconstructor(scene, configa) {\nsuper(scene, configa);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  12. Chart: Draw chart on canvas.
"},{"location":"ui-overview/#colored-text-objects","title":"Colored text objects","text":"
  1. BBCode text: Drawing text with BBCode protocol.
    var txt = scene.rexUI.add.BBCodeText(x, y, text, style);\n
    or
    class MyText extends RexPlugins.UI.BBCodeText {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  2. Tag text: Displays text with multi-color, font face, or font size with tags.
    var txt = scene.rexUI.add.tagText(x, y, text, style);\n
    or
    class MyText extends RexPlugins.UI.TagText {\nconstructor(scene, x, y, text, style) {\nsuper(scene, x, y, text, style);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  3. Dynamic text: Control position, angle of each character drawn on a canvas.
    var txt = scene.rexUI.add.dynamicText(config);\n
    or
    class MyText extends RexPlugins.UI.DynamicText {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  4. Text player: Typing characters on dynamic text, waiting click or key enter, play sound effect or backgroun music.
    var txt = scene.rexUI.add.textPlayer(config);\n
    or
    class MyText extends RexPlugins.UI.TextPlayer {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  5. Canvas input: An invisible Input DOM element to receive character input and display on DynamicText.
    var txt = scene.rexUI.add.canvasInput(config);\n
    or
    class MyText extends RexPlugins.UI.CanvasInput {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
"},{"location":"ui-overview/#behaviors-of-text","title":"Behaviors of text","text":"
  1. Hidden text edit: Create an invisible Input DOM element to edit string content.
    var hiddenEdit = this.rexUI.add.hiddenEdit(textObject, config);\n
    • textObject : text, bbocodetext, tagtext, or label.
  2. Text edit: Create an input text object above a text object to edit string content.
    scene.rexUI.edit(textObject, config);\n// scene.rexUI.edit(textObject, config, onClose);\n
  3. Wrap-expand text
    var textObject = scene.rexUI.wrapExpandText(textObject);\n// var textObject = scene.rexUI.wrapExpandText(textObject, minWidth);\n
    • textObject :
      • Text object, bbcode text object, tag text object,
      • Bitmap text object
      • Dynamic text object, With default wrap configuration, ex:
        {\nlineHeight: 24,\npadding: {bottom: 12}\n}\n
  4. Font-size-expand text
    var textObject = scene.rexUI.fontSizeExpandText(textObject);    
    or
    var textObject = scene.rexUI.fontSizeExpandText(textObject, {\nfitHeight: true\n});\n
    • textObject :
      • Text object, bbcode text object, tag text object, bitmap text game object
    • fitHeight :
      • false : Set font size to fit width only. Default behavior.
      • true : Set font size to fit width and height.
  5. Set font-size to fit width
    var textObject = scene.rexUI.setFontSizeFitToWidth(textObject, width);\n
    • textObject :
      • Text object, bbcode text object, tag text object, bitmap text game object
  6. Text typing
    var textTyping = scene.rexUI.add.textTyping(textObject, config);\n
  7. Text page
    var textPage = scene.rexUI.add.textPage(textObject, config);\n
"},{"location":"ui-overview/#scaled-image","title":"Scaled image","text":"
  1. Image box: Keep aspect ratio of image game object after scale-down resizing.
    var image = scene.rexUI.add.imageBox(x, y, texture, frame, config);\n
    or
    class MyImageBox extends RexPlugins.UI.ImageBox {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
"},{"location":"ui-overview/#transition-image","title":"Transition image","text":"
  1. Transition image: Transit texture to another one.
    var image = scene.rexUI.add.transitionImage(x, y, texture, frame, config);\n
    or
    class MyTransitionImage extends RexPlugins.UI.TransitionImage {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  2. Transition image pack: Transit texture to another one, with some pre-build effects, extended from TransitionImage.
    var image = scene.rexUI.add.transitionImagePack(x, y, texture, frame, config);\n
    or
    class MyTransitionImagePack extends RexPlugins.UI.TransitionImagePack {\nconstructor(scene, x, y, texture, frame, config) {\nsuper(scene, x, y, texture, frame, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
"},{"location":"ui-overview/#dom-game-objects","title":"Dom game objects","text":"
  1. Input text: Input DOM element.
    var inputText = scene.rexUI.add.inputText(config);\n
    or
    class MyInputText extends RexPlugins.UI.InputText {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  2. File chooser: Create a transparent file chooser button (<input type=\"file\">).
    var fileChooser = scene.rexUI.add.fileChooser(config);\n
    or
    class MyFileChooser extends RexPlugins.UI.FileChooser {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  3. File drop zone: Create a div element for dropping file(s).
    var fileDropZone = scene.rexUI.add.fileDropZone(config);\n
    or
    class MyFileDropZpne extends RexPlugins.UI.FileDropZpne {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
"},{"location":"ui-overview/#layer-manager","title":"Layer manager","text":"

Layer manager : A dictionary to store Layer game objects.

var layerManager = scene.rexUI.add.layerManager({\n// layers: ['layer0', 'layer1', ...]\n});\n\n// layerManager.addToLayer(name, gameObject);\n
"},{"location":"ui-overview/#touch-input","title":"Touch input","text":"
  1. Click: Fires 'click' event when touch releasd after pressed.
    var click = scene.rexUI.add.click(gameObject, config);\n
    or
    var click = new RexPlugins.UI.Click(gameObject, config);\n
  2. Click-Outside: Fires 'clickoutside' event when pointer-down or pointer-up outside of game object.
    var clickOutside = scene.rexUI.add.clickOutside(gameObject, config);\n
    or
    var clickOutside = new RexPlugins.UI.ClickOutside(gameObject, config);\n
  3. In touching: Fires 'intouch' event every tick when pressing on a game object.
    var inTouching = scene.rexUI.add.inTouching(gameObject, config);\n
    or
    var inTouching = new RexPlugins.UI.inTouching(gameObject, config);\n
  4. Tap: Get tap/multi-taps events of a game object.
    var tap = scene.rexUI.add.tap(gameObject, config);\n
    or
    var tap = new RexPlugins.UI.Tap(gameObject, config);\n
  5. Press: Get press events of a game object.
    var press = scene.rexUI.add.press(gameObject, config);\n
    or
    var press = new RexPlugins.UI.Press(gameObject, config);\n
  6. Swipe: Get swipe events of a game object.
    var swipe = scene.rexUI.add.swipe(gameObject, config);\n
    or
    var swipe = new RexPlugins.UI.Swipe(gameObject, config);\n
  7. Pan: Get pan events of a game object.
    var pan = scene.rexUI.add.pan(gameObject, config);\n
    or
    var pan = new RexPlugins.UI.Pan(gameObject, config);\n
  8. Pinch: Get scale factor from 2 dragging touch pointers.
    var pinch = scene.rexUI.add.pinch(config);\n
    or
    var pinch = new RexPlugins.UI.Pinch(config);\n
  9. Rotste: Get spin angle from 2 dragging touch pointers.
    var rotate = scene.rexUI.add.rotate(config);\n
    or
    var rotate = new RexPlugins.UI.Rotate(config);\n
  10. Touch event stop: Stop touch events propagation.
    var touchEventStop = scene.rexUI.add.touchEventStop(gameObject, config);\n
    or
    var touchEventStop = new RexPlugins.UI.TouchEventStop(gameObject, config);\n
"},{"location":"ui-overview/#behaviors","title":"Behaviors","text":"
  1. Confirm action : Create a modal confirm dialog temporary, invoke callback after clicking button.
    scene.rexUI.confirmAction(scene, config)\n.then(function(data){ })\n
  2. Modal promise : Modal behavior wrapped into promise.
    scene.rexUI.modalPromise(gameObject, config)\n.then(function(closeEventData){ })\n
    • Close modal dialog:
      scene.rexUI.modalClose(gameObject);\n// scene.rexUI.modalClose(gameObject, closeEventData);\n
      or
      gameObject.emit('modal.requestClose');\n// gameObject.emit('modal.requestClose', closeEventData);\n
      • Fire 'modal.requestClose' event on game object, which will invoke modal.requestClose() method. After closing dialog, resolve part of promise will be triggered.
  3. Flip: Flip game object to another face by scaling width/height.
    var flip = scene.rexUI.add.flip(gameObject, config);\n
    or
    var flip = new RexPlugins.UI.Flip(gameObject, config);\n
  4. Fade in, fade out destroy
    scene.rexUI.fadeIn(gameObject, duration);\n// scene.rexUI.fadeIn(gameObject, duration, alpha);\n
    scene.rexUI.fadeOutDestroy(gameObject, duration);\n
  5. Ease-move to, ease-move from
    scene.rexUI.easeMoveTo(gameObject, duration, x, y);\n// scene.rexUI.easeMoveTo(gameObject, duration, x, y, ease);\n
    scene.rexUI.easeMoveFrom(gameObject, duration, x, y);\n// scene.rexUI.easeMoveFrom(gameObject, duration, x, y, ease);\n
  6. Shake
    scene.rexUI.shake(gameObject, config);\n
  7. Perspective: Snapshot children of containerlite, to a perspective render texture.
    var perspective = scene.rexUI.add.perspective(gameObject, config);\n
    or
    var perspective = new RexPlugins.UI.Perspective(gameObject, config);\n
  8. Skew: Snapshot children of containerlite, to a skew render texture.
    var skew = scene.rexUI.add.skew(gameObject, config);\n
    or
    var skew = new RexPlugins.UI.Skew(gameObject, config);\n
"},{"location":"ui-overview/#helper-methods","title":"Helper methods","text":""},{"location":"ui-overview/#get-parent","title":"Get parent","text":"
  • Get parent sizer
    var parentSizer = scene.rexUI.getParentSizer(gameObject);\n
    • gameObject : Any game object added to sizer.
  • Get ancestor sizer matched given name
    var parentSizer = scene.rexUI.getParentSizer(gameObject, name);\n
    • gameObject : Any game object added to sizer.
    • name : Name string.
  • Get topmost sizer
    var topmostSizer = scene.rexUI.getTopmostSizer(gameObject);\n
    • gameObject : Any game object added to sizer.
"},{"location":"ui-overview/#remove-from-parent","title":"Remove from parent","text":"
scene.rexUI.removeFromParent(gameObject);\n
"},{"location":"ui-overview/#showhide","title":"Show/hide","text":"
  • Show
    scene.rexUI.show(gameObject);\nscene.rexUI.getTopmostSizer(gameObject).layout();\n
  • Hide
    scene.rexUI.hide(gameObject);\nscene.rexUI.getTopmostSizer(gameObject).layout();\n
  • Is shown
    var isShown = scene.rexUI.isShown(gameObject);\n
"},{"location":"ui-overview/#is-pointer-in-bounds","title":"Is pointer in bounds","text":"
var isInBounds = scene.rexUI.isInTouching(gameObject);\n// var isInBounds = scene.rexUI.isInTouching(gameObject, pointer);\n
"},{"location":"ui-overview/#event-promise","title":"Event promise","text":"
  • Get event promise
    var promise = scene.rexUI.waitEvent(eventEmitter, eventName)\n.then(function() {\n\n})\n
    • eventEmitter : Any kind of event emitter. for example, game object, or tween task, or scene event
  • Get complete event promise
    var promise = scene.rexUI.waitComplete(eventEmitter)\n.then(function() {\n\n})\n
    • eventEmitter : Event emitter which will fire 'complete' event, for example, tween task.
  • Delay time promise
    var promise = scene.rexUI.delayPromise(time)\n.then(function() {\n\n})\n
"},{"location":"ui-overview/#view-port","title":"View port","text":"

View port is a rectangle of current visible area.

var viewport = scene.rexUI.viewport;\n

Which will be changed after resizing

scene.scale.on('resize', function() {\nvar viewport = scene.rexUI.viewport;\n/*\n    sizer\n        .setPosition(viewport.centerX, viewport.centerY)\n        .setMinSize(viewport.width, viewport.height)\n        .layout();\n    */\n});\n
"},{"location":"ui-overview/#demos","title":"Demos","text":"
  • Dialog
    • Yes/No
    • Choice
    • Pop-up
  • Text input
    • Text edit
    • Hidden text edit
    • Canvas input
  • Menu
  • Text-box
  • Text-area
  • Number bar
  • Grid table
  • Tabs
    • Tabs-tables
  • Scroll-able panel
  • Pages
  • Fix-width sizer
  • Chart
  • Video player
  • Anchor
  • Round-rectangle
"},{"location":"ui-pages/","title":"Pages","text":""},{"location":"ui-pages/#introduction","title":"Introduction","text":"

A container with pages, only current page is visible.

  • Author: Rex
  • Game object
"},{"location":"ui-pages/#live-demos","title":"Live demos","text":"
  • Pages
  • Tabpage
"},{"location":"ui-pages/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-pages/#install-plugin","title":"Install plugin","text":""},{"location":"ui-pages/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add pages object
    var pages = scene.rexUI.add.pages(config);\n
"},{"location":"ui-pages/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add pages object
    var pages = scene.rexUI.add.pages(config);\n
"},{"location":"ui-pages/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Pages } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add pages object
    var pages = new Pages(scene, config);\nscene.add.existing(pages);\n
"},{"location":"ui-pages/#add-pages-object","title":"Add pages object","text":"
var pages = scene.rexUI.add.pages({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0 },\n// swapMode: 0,\n// fadeIn: 0,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
  • swapMode : Set to invisible or destroy swapped page.
    • 0, 'invisible' : Set swapped page to invisible.
    • 1, 'destroy' : Destroy swapped page.
  • fadeIn : Fade-in duration of current page.
    • 0 : No fade-in effect. Default behavior.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-pages/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPages extends RexPlugins.UI.Pages {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var pages = new MyPages(scene, config);\n
"},{"location":"ui-pages/#add-background","title":"Add background","text":"
pages.addBackground(child);\n

or

pages.addBackground(child, {left: 0, right: 0, top: 0, bottom: 0}, key);\n
  • left, right, top, bottom : Extra padded space. Default is 0.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
"},{"location":"ui-pages/#add-page","title":"Add page","text":"
pages.addPage(child, key, align, padding, expand);\n// pages.add(child, key, align, padding, expand);\n

or

pages.addPage(child, {\nkey: 0,\nalign: Phaser.Display.Align.TOP_LEFT,\npadding: {left: 0, right: 0, top: 0, bottom: 0}, expand: true\n}\n);\n// pages.add(child, config);\n
  • child : A game object.
  • key : Unique name of this page.
  • align :
    • 'left-top', or Phaser.Display.Align.TOP_LEFT : Align game object at left-top. Default value.
    • 'left-center', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
    • 'left-bottom', or Phaser.Display.Align.LEFT_BOTTOM : Align game object at left-bottom.
    • 'center-top', or Phaser.Display.Align.TOP_CENTER : Align game object at center-top.
    • 'center-center', or Phaser.Display.Align.CENTER : Align game object at center-center.
    • 'center-bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at center-bottom.
    • 'right-top', or Phaser.Display.Align.TOP_RIGHT : Align game object at right-top.
    • 'right-center', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • 'right-bottom', or Phaser.Display.Align.RIGHT_BOTTOM : Align game object at right-bottom.
  • padding : Add space between bounds. Default is 0.
    • A number for left/right/top/bottom bounds,
    • Or a plain object.
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • expand : Expand width and height of the page.
    • true : Expand width and height.
    • false : Don't expand width or height.
    • A plain object, to expand width or height
      {\nwidth: true,\nheight: true\n}\n
      • expand.width : Expand width.
      • expand.height : Expand height.
"},{"location":"ui-pages/#swap-to-page","title":"Swap to page","text":"
pages.swapPage(key);\n// pages.swapPage(key, fadeInDuration);\n
  • key : Unique name of this page.

Note

This method will run pages.layout() to arrange position of current page.

"},{"location":"ui-pages/#page-name","title":"Page name","text":"
  • Current page name

    var pageName = pages.currentKey;\n

  • Previous page name

    var pageName = pages.previousKey;\n

  • Name of all pages
    var names = pages.keys;\n
"},{"location":"ui-pages/#page-object","title":"Page object","text":"
  • Get page object
    var pageObject = pages.getPage(key);\n
    • pageObject : A game object or null.
  • Current page object
    var pageObject = pages.currentPage;\n
  • Previous page object
    var pageObject = pages.previousPage;\n
"},{"location":"ui-pages/#fade-in-duration","title":"Fade in duration","text":"
pages.setFadeInDuration(duration);\n
  • 0 : No fade-in effect.
"},{"location":"ui-pages/#get-element","title":"Get element","text":"
  • Get element
    • All page game objects
      var gameObjects = pages.getElement('items');\n
  • Get by name
    var gameObject = pages.getElement('#' + name);\n// var gameObject = pages.getElement('#' + name, recursive);\n
    or
    var gameObject = pages.getByName(name);\n// var gameObject = pages.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-pages/#other-properties","title":"Other properties","text":"

See base sizer object, container-lite.

"},{"location":"ui-pages/#events","title":"Events","text":"
  • Set page invisible, triggered when page is swapped out.
    pages.on('pageinvisible', function(pageObject, key, pages) {\n// ...\n}, scope);\n
    • pageObject : Game object of page.
    • key : Page name.
    • pages : Pages object
  • Set page visible, triggered when page is shown.
    pages.on('pagevisible', function(pageObject, key, pages) {\n// ...\n}, scope);\n
    • pageObject : Game object of page.
    • key : Page name.
    • pages : Pages object
"},{"location":"ui-perspectivecard/","title":"Perspective card","text":""},{"location":"ui-perspectivecard/#introduction","title":"Introduction","text":"

A container with front and back faces.

  • Author: Rex
  • Game object

WebGL only

It only works in WebGL render mode.

"},{"location":"ui-perspectivecard/#live-demos","title":"Live demos","text":"
  • Flip
  • Rotation
"},{"location":"ui-perspectivecard/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-perspectivecard/#install-plugin","title":"Install plugin","text":""},{"location":"ui-perspectivecard/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add card object
    var card = scene.rexUI.add.perspectiveCard(config);\n
"},{"location":"ui-perspectivecard/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add card object
    var card = scene.rexUI.add.perspectiveCard(config);\n
"},{"location":"ui-perspectivecard/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { PerspectiveCard } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add card object
    var card = new PerspectiveCard(scene, config);\nscene.add.existing(card);\n
"},{"location":"ui-perspectivecard/#add-card-object","title":"Add card object","text":"
var sizer = scene.rexUI.add.perspectiveCard({    // x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nback: backGameObject,\nfront: frontGameObject,\n// face: 0,\n// orientation: 0,\n// snapshotPadding: 0,\n\n// flip : {\n//     frontToBack: 0,\n//     backToFront: 1,\n//     duration: 1000,\n//     ease: 'Cubic',\n//     delay: 0,\n// }\n\n// space: { left: 0, right:0, top:0, bottom:0 },\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • front, back : Any game object for front or back face.
  • face : Show front or back face.
    • 'front', or 0 : Show front face.
    • 'back', or 1 : Show back face.
  • orientation : Flipping orientation.
    • 'horizontal','h', 'x', or 0 : Flipping left-to-right, or right-to-left.
    • 'vertical','v', 'y', or 1 : Flipping top-to-bottom, or bottom-to-top.
  • snapshotPadding : Padding around face when taking a snapshot of a face.
  • flip : Configuration of flipping behavior.
    • flip.frontToBack, flip.backToFront : Flipping direction.
      • 'right', 'left-to-right', or 0 : Flipping from right to left.
      • 'left', 'right-to-left', or 1 : Flipping from left to right.
    • flip.duration : Duration of flipping, in millisecond.
    • flip.delay : Initial delay.
    • flip.ease : Ease function. Default value is 'Cubic'.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-perspectivecard/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPerspectiveCard extends PerspectiveCard {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta);\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var card = new MyPerspectiveCard(scene, config);\n
"},{"location":"ui-perspectivecard/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

card.layout();\n

See also - dirty

"},{"location":"ui-perspectivecard/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = card.getElement('background');\n
    • Front face game object
      var frontFace = card.getElement('front');\n
    • Back face game object
      var backFace = card.getElement('back');\n
  • Get by name
    var gameObject = card.getElement('#' + name);\n// var gameObject = card.getElement('#' + name, recursive);\n
    or
    var gameObject = card.getByName(name);\n// var gameObject = card.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-perspectivecard/#face","title":"Face","text":"
  • Get
    var face = card.face;\n
    • face:
      • 0 : Show front face.
      • 1 : Show back face.
  • Set
    card.setFace(face)\n
    • face
      • 'front', or 0 : Show front face.
      • 'back', or 1 : Show back face.
  • Toggle
    card.toggleFace()\n
"},{"location":"ui-perspectivecard/#face-instances","title":"Face instances","text":"
  • Front face
    var frontFace = card.frontFace;\n// var frontFace = card.faces.front;\n
  • Back face
    var backFace = card.backFace;\n// var backFace = card.faces.back;\n
"},{"location":"ui-perspectivecard/#flip-behavior","title":"Flip behavior","text":""},{"location":"ui-perspectivecard/#start-flipping","title":"Start flipping","text":"
card.flip.flip();\n// card.flip.flip(duration, repeat);\n
  • duration : Overwrite default duration value.
  • repeat : Number of flipping time (repeat + 1) during duration. Default value is 0.

or

  • Flip-right
    card.flip.flipRight();\n// card.flip.flipRight(duration, repeat);\n
  • Flip-left
    card.flip.flipLeft();\n// card.flip.flipLeft(duration, repeat);\n

Note

  • When flipping start:
    • Snapshot face game objects to perspective-card mesh
    • Set face game objects to invisible, and perspective-card mesh to visible
  • When flipping complete:
    • Revert visible of Face game objects and perspective-card mesh
"},{"location":"ui-perspectivecard/#stop-flipping","title":"Stop flipping","text":"
card.flip.stop();\n
"},{"location":"ui-perspectivecard/#set-duration","title":"Set duration","text":"
card.flip.setDuration(duration);\n// card.flip.duration = duration;\n
"},{"location":"ui-perspectivecard/#set-ease","title":"Set ease","text":"
card.flip.setEase(ease);\n// card.flip.ease = ease;\n
"},{"location":"ui-perspectivecard/#events","title":"Events","text":"
  • On flipping start
    card.flip.on('start', function(){\n// ...\n});\n
  • On flipping complete
    card.flip.on('complete', function(){\n// ...\n});\n
"},{"location":"ui-perspectivecard/#status","title":"Status","text":"
  • Is flipping
    var isRunning = card.flip.isRunning;\n
"},{"location":"ui-perspectivecard/#rotation","title":"Rotation","text":"
  • Get rotation angle
    var angleX = card.angleX; // Angle in degrees\nvar angleY = card.angleY; // Angle in degrees\nvar angleZ = card.angleZ; // Angle in degrees\n
    or
    var rotationX = card.rotationX; // Angle in radians\nvar rotationY = card.rotationY; // Angle in radians\nvar rotationZ = card.rotationZ; // Angle in radians\n
  • Set rotation angle
    card.angleX = angleX; // Angle in degrees\ncard.angleY = angleY; // Angle in degrees\ncard.angleZ = angleZ; // Angle in degrees\n
    or
    card.rotationX = rotationX; // Angle in radians\ncard.rotationY = rotationY; // Angle in radians\ncard.rotationZ = rotationZ; // Angle in radians\n

Warning

Can't be used with flipping mode.

"},{"location":"ui-perspectivecard/#other-properties","title":"Other properties","text":"

See overlapSizer.

"},{"location":"ui-scrollablepanel/","title":"Scroll-able panel","text":""},{"location":"ui-scrollablepanel/#introduction","title":"Introduction","text":"

A container with a panel, slider, and scroller.

  • Author: Rex
  • Game object
"},{"location":"ui-scrollablepanel/#live-demos","title":"Live demos","text":"
  • Scroll-able panel + grid sizer
  • Scroll-able panel + table by fix-width sizer
  • Scroll-able panel + fix-width sizer
  • Scroll-able panel + built-in container
    • Container panel
    • Container child
  • Button click
  • Dropdown, scrollable list
  • Add child
  • Scroll to child
  • Drag item
  • Destroy
  • XY sliders
  • Min-width panel
  • Drag, resize panel
    • Single scroller
    • ScrollerX, scrollerY
  • Drag&drop items between panels :
    • With scroller
    • Without scroller
  • Nested scroll-able panel
  • Typing on Label
"},{"location":"ui-scrollablepanel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-scrollablepanel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-scrollablepanel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add scrollable-panel object
    var panel = scene.rexUI.add.scrollablePanel(config);\n
"},{"location":"ui-scrollablepanel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add scrollable-panel object
    var panel = scene.rexUI.add.scrollablePanel(config);\n
"},{"location":"ui-scrollablepanel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ScrollablePanel } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add scrollable-panel object
    var panel = new ScrollablePanel(scene, config);\nscene.add.existing(panel);\n
"},{"location":"ui-scrollablepanel/#add-scroll-able-panel-object","title":"Add scroll-able panel object","text":"
var panel = scene.rexUI.add.scrollablePanel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// scrollMode: 0,\n\n// Elements\nbackground: backgroundGameObject,\n\npanel: {\nchild: panelGameObject,\nmask: {\npadding: 0, // or {left, right, top, bottom}\n// updateMode: 0,\n}\n}.\n\nslider: {\n// background: sliderBackgroundGameObject,\ntrack: trackGameObject,\n/* \n        track: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\nthumb: thumbGameObject,\n/* \n        thumb: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\n// input: 'drag',\n// position: 'right',\n\n// hideUnscrollableSlider: false,\n// adaptThumbSize: false,\n// minThumbSize: undefined,\n\n// buttons: {\n//     top: topButtonGameObject, \n//     bottom: bottomButtonGameObject,\n//     left: leftButtonGameObject, \n//     right: rightButtonGameObject,\n//     step: 0.01,\n// }\n},\n\n// sliderX: {...},\n// sliderY: {...},\n\n// scrollDetectionMode: 0,\n\n// scroller: {\n//     threshold: 10,\n//     slidingDeceleration: 5000,\n//     backDeceleration: 2000,\n//     pointerOutRelease: true,\n//     rectBoundsInteractive: true,\n//     dragRate: 1,\n// },\n\n// scrollerX: {...},\n// scrollerY: {...},\n\nmouseWheelScroller: false,\n// mouseWheelScroller: {\n//     focus: true,\n//     speed: 0.1\n// },\n\n// mouseWheelScrollerX: {...},\n// mouseWheelScrollerY: {...},\n\nclampChildOY: false,\n// clampChildOX: false,\n\nheader: headerGameObject,\nfooter: footerGameObject,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\npanel: 0,\n// panel: {\n//    top: 0,\n//    bottom: 0,\n//    left: 0,\n//    right: 0,\n//},\n\nslider: 0,\n// slider: {\n//     top: 0,\n//     bottom: 0,\n//     left: 0,\n//     right: 0,\n// },\n// sliderX: 0,\n// sliderY: 0,\n\nheader: 0,\nfooter: 0,\n},\n\nexpand: {\nheader: true,\nfooter: true,\npanel: true,\n},\n\nalign: {\nheader: 'center',\nfooter: 'center',\npanel: 'center',\n},\n\n// name: '',\n// draggable: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • scrollMode : Scroll panel vertically, or horizontally.
    • 0, 'vertical', or 'v', 'y' : Scroll panel vertically. Default value.
    • 1, 'horizontal', or 'h'. 'x' : Scroll panel horizontally.
    • 2, or 'xy' : Two-sliders mode, scroll panel vertically and horizontally.
  • background : Game object of background, optional. This background game object will be resized to fit the size of scroll-able panel.
  • panel : Configuration of panel game object.
    • panel.child : Panel game object.
    • panel.mask : Configuration of panel's mask.
      • panel.mask.padding :
        • A number : Extra left/right/top/bottom padding spacing of this rectangle mask. Default value is 0.
        • A plain object {left, right, top, bottom}
      • panel.mask.updateMode : When to update mask
        • 0, or 'update' : Apply mask only when scrolling. Default behavior.
        • 1, or 'everyTick' : Apply mask every tick. Use this mode if children game objects of panel are moved after scrolling and still been masked.
      • false : No mask
  • slider : Componments of slider, optional.
    • slider.background :
      • Game object of background, optional. This background game object will be resized to fit the size of slider.
      • A plain object to create round rectangle shape
        { radius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.track :
      • Game object of track, optional. This track game object will be resized to fit the size of slider, with space.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.indicator :
      • Game object of indicator, optional.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.thumb :
      • Game object of thumb, optional.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.input :
      • 'pan', 'drag', or 0 : Control slider by panning/dragging thumb game object. Default setting.
      • 'click', or 1 : Control slider by touching track game object.
      • 'none', or -1 : Disable sider controlling.
    • slider.position : Position of this slider.
      • 0, 'right', 'bottom' : Slider at right/bottom side. Default value.
      • 1, 'left', 'top' : Slider at left/top side.
    • slider.hideUnscrollableSlider :
      • false : Slider is always visible no matter it is scrollable or not. Default behavior.
      • true : Set slider to invisible if it is unscrollable.
    • slider.adaptThumbSize :
      • false : Don't adjust height/width of thumb. Default behavior.
      • true : Adjust height/width of thumb according to ratio of visible child.
        • Minimum height/width of thumb = slider.minThumbSize. If content is larger then a page.
        • Maximum height/width of thumb = height/width of slider.track. If content is less then a page.
    • slider.minThumbSize : Minimum height/width of thumb used in slider.adaptThumbSize mode.
    • slider.buttons : Press button to scroll content in each tick.
      • slider.buttons.top, slider.buttons.bottom : Top and bottom buttons.
      • slider.buttons.left, slider.buttons.right : Left and right buttons
      • slider.buttons.step : Scrolling step in each tick. Default value is 0.01.
    • Set to false to skip creating slider.
  • sliderX, sliderY : Componments of sliderX and sliderY, for two-sliders mode.
  • scrollDetectionMode :
    • 0 : Dectct drag-scrolling, mouse-wheel-scrolling by game object's touch event. Default behavior.
    • 1 : Dectct drag-scrolling, mouse-wheel-scrolling by rectangle bounds.
  • scroller : Configuration of scroller behavior.
    • scroller.threshold : Minimal movement to scroll. Set 0 to scroll immediately.
    • scroller.slidingDeceleration : Deceleration of slow down when dragging released.
      • Set false to disable it.
    • scroller.backDeceleration : Deceleration of pull back when out of bounds.
      • Set false to disable it.
    • scroller.pointerOutRelease : Set to true to release input control when pointer out of gameObject.
    • scroller.rectBoundsInteractive :
      • false : Detect scrolling by game object's touch input.
      • true : Detect scrolling by rectangle bounds of game object. Default behavior.
    • scroller.dragRate : Rate of dragging distance/dragging speed. Default value is 1.
    • Set to false to skip creating scroller.
  • scrollerX, scrollerY : Configuration of scrollerX, scrollerY behavior, for two-sliders mode.
  • mouseWheelScroller : Configuration of mouse-wheel-scroller behavior.
    • mouseWheelScroller.focus :
      • false, or 0 : Without checking if cursor is over game object or not.
      • true, or 1 : Cursor is inside the rectangle bounds of game object. Default behavior.
      • 2 : Cursor is over game object.
    • mouseWheelScroller.speed : Scrolling speed, default value is 0.1.
    • Set to false to skip creating mouse-wheel-scroller. Default behavior.
  • mouseWheelScrollerX, mouseWheelScrollerY : Configuration of mouse-wheel-scrollerX, or mouse-wheel-scrollerY behavior, for two-sliders mode.
  • clampChildOY : Set true to clamp scrolling.
  • clampChildOX : Set true to clamp scrolling, for two-sliders mode.
  • header : Game object of header, optional.
  • footer : Game object of footer, optional.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.panel :
      • A number: Space between panel object and slider object.
      • An object: Padding of panel object.
        • If scrollMode is 0 (vertical) :
          • space.panel.top, space.panel.bottom : Top, bottom padding space of panel object.
          • space.panel.right : Space between panel object and slider object.
        • If scrollMode is 1 (horizontal) :
          • space.panel.left, space.panel.right : Left, right padding space of panel object.
          • space.panel.bottom : Space between panel object and slider object.
        • If two-sliders mode (scrollMode is 2):
          • space.panel.top, space.panel.bottom, space.panel.left, space.panel.right : Top, bottom, left, right padding space of panel object.
    • space.slider :
      • 0 : No space around slider.
      • space.slider.left, space.slider.right, space.slider.top, space.slider.bottom : Space around slider.
    • space.sliderX, space.sliderX : Space configuration of sliderX, sliderX, for two-sliders mode.
      • 0 : No space around slider.
    • space.header : Space between header and panel.
    • space.footer : Space between footer and panel.
  • expand : Expand width or height of element
    • expand.header : Set true to expand width or height of header game object. Default value is true.
    • expand.footer : Set true to expand width or height of footer game object. Default value is true.
    • expand.panel : Set true to expand width or height of panel game object. Default value is true.
  • align : Align element
    • align.header
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
      • 'top', or Phaser.Display.Align.ALIGN.TOP_CENTER : Align game object at top-center.
      • 'bottom', or Phaser.Display.Align.ALIGN.BOTTOM_CENTER : Align game object at bottom-center.
    • align.footer
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
      • 'top', or Phaser.Display.Align.ALIGN.TOP_CENTER : Align game object at top-center.
      • 'bottom', or Phaser.Display.Align.ALIGN.BOTTOM_CENTER : Align game object at bottom-center.
    • align.panel
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
      • 'top', or Phaser.Display.Align.ALIGN.TOP_CENTER : Align game object at top-center.
      • 'bottom', or Phaser.Display.Align.ALIGN.BOTTOM_CENTER : Align game object at bottom-center.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
"},{"location":"ui-scrollablepanel/#scroll-mode","title":"Scroll mode","text":"

If scrollMode parameter is not given :

  • Set scrollMode to 2, if configuration has sliderX, sliderY, or scrollerX, scrollerY parameters.
  • Set scrollMode to 0, if configuration has sliderY, or scrollerY parameters.
  • Set scrollMode to 1, if configuration has sliderX, or scrollerX parameters.
"},{"location":"ui-scrollablepanel/#child-bounds","title":"Child bounds","text":"

Scrollable panel will mask child if child's bounds (child.getBounds()) is across mask area.

Bitmaptext game object does not have getBounds method. User can inject it by

const Components = Phaser.GameObjects.Components;\nPhaser.Class.mixin(\nPhaser.GameObjects.BitmapText,\n[\nComponents.ComputedSize,\nComponents.GetBounds\n]\n);\n
"},{"location":"ui-scrollablepanel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyPanel extends RexPlugins.UI.ScrollablePanel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var panel = new MyPanel(scene, config);\n
"},{"location":"ui-scrollablepanel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

panel.layout();\n

See also - dirty

"},{"location":"ui-scrollablepanel/#scroll-content","title":"Scroll content","text":"
  • Set
    panel.childOY = oy;\n// panel.setChildOY(oy);\n
  • Set and clamp
    panel.setChildOY(oy, true);\n
  • Add
    panel.addChildOY(oy);\n
  • Add and clamp
    panel.addChildOY(oy, true);\n
  • Get
    var childOY = panel.childOY;\n
  • Top OY
    var topOY = panel.topChildOY;\n
  • Bottom OY
    var bottomOY = panel.bottomChildOY;\n
  • Is overflow (height of content is larger than display height)
    var isOverflow = panel.isOverflow;\n
"},{"location":"ui-scrollablepanel/#scroll-by-percentage","title":"Scroll by percentage","text":"
  • Set
    panel.t = t;  // t: 0~1\n// panel.setT(t);  \n
  • Set and clamp
    panel.setT(t, true);\n
  • Get
    var t = panel.t;\n
"},{"location":"ui-scrollablepanel/#scroll-to-topbottom","title":"Scroll to top/bottom","text":"
  • Scroll to top
    panel.scrollToTop();\n
    • Equal to panel.t = 0;
  • Scroll to bottom
    panel.scrollToBottom();\n
    • Equal to panel.t = 1;
"},{"location":"ui-scrollablepanel/#scroll-to-child","title":"Scroll to child","text":"
panel.scrollToChild(child, align);\n
  • align :
    • undefined : Align child to top(left), or bottom(right) of panel. Default value.
    • 'top', 'center', 'bottom' : Align child to top/center/bottom of panel.
    • 'left', 'center', 'right' : Align child to left/center/right of panel.
"},{"location":"ui-scrollablepanel/#enabledisable-scrolling","title":"Enable/disable scrolling","text":"
  • Slider
    • Set enable state
      panel.setSliderEnable(enabled);\n
      or
      panel.sliderEnable = enabled;\n
    • Get enable state
      var enable = panel.sliderEnable;\n
  • Scroller
    • Set enable state
      panel.setScrollerEnable(enabled);\n
      or
      panel.scrollerEnable = enabled;\n
    • Get enable state
      var enable = panel.scrollerEnable;\n
  • Mouse-Wheel-Scroller
    • Set enable state
      panel.setMouseWheelScrollerEnable(enabled);\n
      or
      panel.mouseWheelScrollerEnable = enabled;\n
    • Get enable state
      var enable = panel.mouseWheelScrollerEnable;\n
"},{"location":"ui-scrollablepanel/#event","title":"Event","text":"
  • Scroll
    panel.on('scroll', function(panel) {\n// ...\n})\n
  • Slider
    • Slider drag start
      panel.getElement('slider').on('inputstart', function(panel) {\n// ...\n})\n
    • Slider drag end
      panel.getElement('slider').on('inputend', function(panel) {\n// ...\n})\n
  • Scroller
    • Scroller drag start
      panel.getElement('scroller').on('dragstart', function(panel) {\n// ...\n})\n
    • Scroller drag end
      panel.getElement('scroller').on('dragend', function(panel) {\n// ...\n})\n
"},{"location":"ui-scrollablepanel/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-scrollablepanel/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = panel.getElement('background');\n
    • Child-panel game object
      var childPanel = panel.getElement('panel');\n
    • Child-panel mask game object, which is a graphics game object.
      var maskGameObject = panel.getElement('mask');\n
    • Layer of panel, assigned at config panel.mask.layer.
      var layer = panel.getElement('panelLayer');\n
    • Header game object
      var childPanel = panel.getElement('header');\n
    • Footer game object
      var childPanel = panel.getElement('footer');\n
    • Slider
      • Slider top
        var slider = panel.getElement('slider');\n
      • Track
        var track = panel.getElement('slider.track');\n
      • Thumb
        var thumb = panel.getElement('slider.thumb');\n
    • Scroller
      var scroller = panel.getElement('scroller');\n
    • Scrollable-block, registering scroller and children-interactive on it.
      var scrollableBlock = panel.getElement('scrollableBlock');\n
  • Get by name
    var gameObject = panel.getElement('#' + name);\n// var gameObject = panel.getElement('#' + name, recursive);\n
    or
    var gameObject = panel.getByName(name);\n// var gameObject = panel.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-scrollablepanel/#input-events","title":"Input events","text":"

Two possible solution to register input events to children of scrollable panel.

"},{"location":"ui-scrollablepanel/#individual-input-events","title":"Individual input events","text":"

When scene.input.topOnly is true (default value), input events of children elements will block the drag-scrolling of scrollable panel. (Assmue that the children elememts are above scrollable panel)

  • Set scene.input.topOnly to false to enable drag-scrolling and input events of children elememts both.
    • Or Set scrollDetectionMode: 1 in config of constructor, to using rectangle-bounds input detection.
  • Test if pointer is inside the mask of panel via panel.isInTouching('mask'), during input events' callback.
  • To recognize pointer-down and dragging-start, use press's pressstart event.
"},{"location":"ui-scrollablepanel/#set-children-interactive","title":"Set children interactive","text":"

Applies click, tap, press, swipe behaviors on this scrollable panel, to detect input events of children.

panel.setChildrenInteractive({\n// targetMode: 'parent',\ntargets: targetSizers,\n\n// dropZone: false,\n\n// click: {mode: 'release', clickInterval: 100},\n\n// over: undefined,\n\n// press: {time: 251, threshold: 9},\n\n// tap: {time: 250, tapInterval: 200, threshold: 9, tapOffset: 10, \n//       taps: undefined, minTaps: undefined, maxTaps: undefined,},\n\n// swipe: {threshold: 10, velocityThreshold: 1000, dir: '8dir'},\n\n// inputEventPrefix: 'child.',\n})\n
  • targetMode :
    • 'parent' : targetSizers is an array of hit-targrts' parentSizers. Will run hit-test on parentSizers first, then run hit-test on children of parentSizer. Default behavior.
    • 'direct' : targetSizers is an array of hit-targrts. Will run hit-test directly on these hit-targrts.
  • targetSizers : Array of hit-targrts' parentSizers, or array of hit-targrts. See targetMode parameter.
  • dropZone :
    • true : Enable drop Zone on scrollable area.
    • false : Do nothing.

See Base-sizer/Set children interactive

"},{"location":"ui-scrollablepanel/#events","title":"Events","text":"

See Base-sizer/Set children interactive/Events

"},{"location":"ui-scrollablepanel/#steps-of-building-a-scrollable-panel","title":"Steps of building a scrollable panel","text":"
  1. Build child panel from bottom to top
    • Child panel might be composed of sizers (sizer/fix-width sizer/grid sizer)
    • Return child sizer from method
  2. Build scrollable panel
  3. Add interactive events
"},{"location":"ui-scrollbar/","title":"Scroll bar","text":""},{"location":"ui-scrollbar/#introduction","title":"Introduction","text":"

A container with slider, two buttons, and background.

  • Author: Rex
  • Game object
"},{"location":"ui-scrollbar/#live-demos","title":"Live demos","text":"
  • Scroll bar
"},{"location":"ui-scrollbar/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-scrollbar/#install-plugin","title":"Install plugin","text":""},{"location":"ui-scrollbar/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin(\n\"rexuiplugin\",\n\"https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js\",\n\"rexUI\",\n\"rexUI\"\n);\n
  • Add scroll bar object
    var scrollBar = scene.rexUI.add.scrollBar(config);\n
"},{"location":"ui-scrollbar/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from \"phaser3-rex-plugins/templates/ui/ui-plugin.js\";\nvar config = {\n// ...\nplugins: {\nscene: [\n{\nkey: \"rexUI\",\nplugin: UIPlugin,\nmapping: \"rexUI\",\n},\n// ...\n],\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add scroll bar object
    var scrollBar = scene.rexUI.add.scrollBar(config);\n
"},{"location":"ui-scrollbar/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ScrollBar } from \"phaser3-rex-plugins/templates/ui/ui-components.js\";\n
  • Add scroll bar object
    var sizer = new ScrollBar(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-scrollbar/#add-scroll-bar-object","title":"Add scroll bar object","text":"
var scrollBar = scene.rexUI.add.scrollBar({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\norientation: 0,\n\nbackground: backgroundGameObject,    slider: {\nbackground: backgroundGameObject,\n/* \n        background: { \n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\ntrack: trackGameObject,\n/* \n        track: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */    indicator: indicatorGameObject,\n/* \n        indicator: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\nthumb: thumbGameObject,\n/* \n        thumb: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\ninput: 'drag',\ngap: undefined,        easeValue: {\nduration: 0,\nease: 'Linear'\n},\n},\n\nbuttons: {\ntop: topButtonGameObject, bottom: bottomButtonGameObject,\nleft: leftButtonGameObject, right: rightButtonGameObject,\nstep: 0.01,\n}\n\nvaluechangeCallback: function(newValue, oldValue, scrollBar) {\n// scrollBar.text = Math.round(Phaser.Math.Linear(0, 100, newValue));\n}\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\nitem: 0\n},\n\nenable: true,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation : Main orientation of the sizer.
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Arrange game objects from left ot right.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Arrange game objects from top to bottom.
  • background : Game object of background, optional. This background game object will be resized to fit the size of scrollBar.
  • slider : Slider game object which composed of
    • slider.width : Fixed width of slider, optional. Width of slider will be extended if this value is not set.
    • slider.background :
      • Game object of background, optional. This background game object will be resized to fit the size of slider.
      • A plain object to create round rectangle shape
        { radius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.track :
      • Game object of track, optional. This track game object will be resized to fit the size of slider, with space.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.indicator :
      • Game object of indicator, optional.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.thumb :
      • Game object of thumb, optional.
      • A plain object to create round rectangle shape
        { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
    • slider.input :
      • 'pan', 'drag', or 0 : Control knob by panning/dragging thumb game object. Default setting.
      • 'click', or 1 : Control slider by touching track game object.
      • 'none', or -1 : Disable sider controlling.
    • slider.gap : Snap a value to nearest grid slice, using rounding.
      • undefined : Disable this feature.
    • slider.easeValue : Easing value when input is 'click'.
      • slider.easeValue.duration : Duration of value easing, default is 0 (no easing).
      • slider.easeValue.ease : Ease function, default is 'Linear'.
  • buttons : Press button to scroll content in each tick.
    • buttons.top, buttons.bottom : Top and bottom buttons.
    • buttons.left, buttons.right : Left and right buttons
    • buttons.step : Scrolling step in each tick. Default value is 0.01.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds
    • space.item : Space between 2 children game objects.
  • valuechangeCallback : callback function when value changed.
  • enable : Set false to disable controlling.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
"},{"location":"ui-scrollbar/#custom-class","title":"Custom class","text":"
  • Define class
    class MyScrollBar extends RexPlugins.UI.ScrollBar {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var scrollBar = new MyScrollBar(scene, config);\n
"},{"location":"ui-scrollbar/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

scrollBar.layout();\n

See also - dirty

"},{"location":"ui-scrollbar/#get-element","title":"Get element","text":"
  • Get element
  • Background game object
    var background = scrollBar.getElement(\"background\");\n
  • Slider game object
    • Slider background
      var sliderBackground = scrollBar.getElement(\"slider.background\");\n
    • Slider track
      var sliderTrack = scrollBar.getElement(\"slider.track\");\n
    • Slider indicator
      var sliderIndicator = scrollBar.getElement(\"slider.indicator\");\n
    • Slider thumb
      var sliderThumb = scrollBar.getElement(\"slider.thumb\");\n
  • Button game objects
    var buttons = scrollBar.getElement(\"buttons\");\n
    • buttons : Array of button game objects.
      • buttons[0] : Left or top button.
      • buttons[1] : Right or bottom button.
  • Get by name
    var gameObject = scrollBar.getElement(\"#\" + name);\n// var gameObject = scrollBar.getElement('#' + name, recursive);\n
    or
    var gameObject = scrollBar.getByName(\"#\" + name);\n// var gameObject = scrollBar.getByName(name, recursive);\n
  • recursive : Set true to search all children recursively.
"},{"location":"ui-scrollbar/#enable","title":"Enable","text":"
  • Get
    var enable = scrollBar.enable;\n
  • Set
    scrollBar.setEanble(enable);\n
    or
    scrollBar.enable = enable;\n
"},{"location":"ui-scrollbar/#value","title":"Value","text":"

Change value will also change the position of slider thumb and width of slider indicator.

  • Get value
    var value = scrollBar.getValue(min, max); // value : min ~ max\n
    or
    var value = scrollBar.getValue(); // value: 0 ~ 1\n
    or
    var value = scrollBar.value; // value: 0 ~ 1\n
  • Set value
    scrollBar.setValue(value, min, max); // value: min ~ max\n
    or
    scrollBar.setValue(value); // value: 0 ~ 1\n
    or
    scrollBar.value = value; // value: 0 ~ 1\n
  • Increase value
    scrollBar.addValue(inc, min, max); // inc: min ~ max\n
    or
    scrollBar.addValue(inc); // inc: 0 ~ 1\n
    or
    scrollBar.value += inc; // inc: 0 ~ 1\n
"},{"location":"ui-scrollbar/#ease-value","title":"Ease value","text":"
  • Ease value to
    scrollBar.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    scrollBar.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    scrollBar.stopEaseValue();\n
  • Set ease duration
    scrollBar.setEaseValueDuration(duration);\n
  • Set ease function
    scrollBar.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"ui-scrollbar/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-scrollbar/#events","title":"Events","text":"
  • On value changed
    scrollBar.on('valuechange',\nfunction (newValue, oldValue, scrollBar) {\n// scrollBar.text = Math.round(Phaser.Math.Linear(0, 100, newValue));\n},\nscope\n);\n
  • On input start
    scrollBar.on('inputstart', function(pointer) {\n\n}, scope);\n
  • On input end
    scrollBar.on('inputend', function(pointer) {\n\n}, scope);\n
"},{"location":"ui-simpledropdownlist/","title":"Simple drop down list","text":""},{"location":"ui-simpledropdownlist/#introduction","title":"Introduction","text":"

Using plain object to create drop down list.

  • Author: Rex
  • Game object
"},{"location":"ui-simpledropdownlist/#live-demos","title":"Live demos","text":"
  • Drop-down list
  • Drop-down scrollable-list
"},{"location":"ui-simpledropdownlist/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-simpledropdownlist/#install-plugin","title":"Install plugin","text":""},{"location":"ui-simpledropdownlist/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add drop-down list object
    var dropDownList = scene.rexUI.add.simpleDropDownList(config);\n
"},{"location":"ui-simpledropdownlist/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add drop-down list object
    var dropDownList = scene.rexUI.add.simpleDropDownList(config);\n
"},{"location":"ui-simpledropdownlist/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { DropDownList } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add dropDownList object
    var dropDownList = new SimpleDropDownList(scene, config);\nscene.add.existing(dropDownList);\n
"},{"location":"ui-simpledropdownlist/#add-drop-down-list-object","title":"Add drop-down list object","text":"
var dropDownList = scene.rexUI.add.simpleDropDownList({\nlabel: labelStyle,\nbutton: buttonStyle,\n\ntrack: backgroundStyle,\nthumb: backgroundStyle,\n\nlist: {\n// easeIn: 500,\n// transitIn: undefined,\n// transitIn: function(listPanel, duration) {  },\n\n// easeOut: 100,\n// transitOut: undefined,\n// transitOut: function(listPanel, duration) {  },\n\n// wrap: false,\n// maxHeight: undefined,\n// width: undefined, \n// height: undefined,\n// alignParent: 'text',\n// alignSide: '',\n// expandDirection: 0,\n// bounds: undefined,\n\n// space: {\n//     left: 0, right: 0, top: 0, bottom: 0, item: 0,\n//     line: 0\n// },\n\n// draggable: false        \n}\n\n}, creators);\n
  • label :
    • Styles of simple-label
  • button : Use label parameter if button parameter is not given.
    • Styles of simple-label
  • track, thumb :
    • Styles of background
  • list : Configuration of list panel.
    • list.easeIn : Pop-up duration in ms. Default value is 500.
    • list.transitIn : Tween behavior of opening list panel.
      • undefined : Expand list panel by pop-up, default behavior.
      • Custom callback
        function(listPanel, duration) {\n\n}\n
    • list.easeOut : Scale-down duration in ms. Default value is 100.
    • list.transitOut : Tween behavior of closing list panel.
      • undefined : Closing list panel by scale-down, default behavior.
      • Custom callback
        function(listPanel, duration) {\n\n}\n
    • list.wrap :
      • true : fixwidth-sizer layout, a row within buttons.
      • false : sizer layout, a row within a button. Default behavior.
    • list.maxHeight : If height of button list is larger than this maxHeight, put this button list into scrollable panel.
      • undefined, or 0 : Ignore this behavior.
      • > 0 and list.createThumbCallback parameter is given : If height of button list is larger than this maxHeight, put this button list into scrollable panel.
    • list.width : Minimum width.
      • undefined : Minimum width of panel will equal to width of parent label. Default value.
      • A number : Width of panel. Required fields when list.wrap is true.
    • list.height : Minimum height.
      • undefined : Create button list or wrap button list. Default value.
      • > 0 and thumb parameter is given : Create scrollable button list or wrap button list.
    • list.alignParent : Align x position to label.
      • 'icon' : Align x position to icon game object of parent label.
      • 'text' : Align x position to text game object of parent label. Default behavior
      • 'label', or null : Align x position to parent label.
    • list.alignSide : Align list to label's left or right side.
      • undefined, or 'left' : Align list's left side to label's left side. Default behavior.
      • 'right : Align list's right side to label's right side. Default behavior.
    • list.expandDirection :
      • 0, 'down' : Expand list down. i.e. list panel will put below parent label.
      • 1, 'up' : Expand list up. i.e. list panel will put above parent label.
    • list.bounds : Put list panel below parent label if bottom of list panel is inside bounds (Rectangle)
      • undefined : Use viewport as bounds
      • Rectangle
    • list.space : space properties of list panel.
      • left, right, top, bottom, item : For sizer layout. (list.wrap is false)
      • left, right, top, bottom, item, line : For fixwidth-sizer layout. (list.wrap is true)
    • list.draggable : Set true to drag top-most object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-simpledropdownlist/#custom-class","title":"Custom class","text":"
  • Define class
    class MyDropDownList extends RexPlugins.UI.SimpleDropDownList {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var dropDownList = new MyDropDownList(scene, config);\n
"},{"location":"ui-simpledropdownlist/#options","title":"Options","text":"
  • Set
    dropDownList.setOptions(options);\n
    or
    dropDownList.options = options;\n
    • options : Array of strings, or objects contains these properties.
      {\ntext: string,\nvalue: any\n}\n
  • Get
    var options = dropDownList.options;\n
"},{"location":"ui-simpledropdownlist/#other-properties","title":"Other properties","text":"

See drop-down list, label, sizer object, base sizer object, container-lite.

"},{"location":"ui-simpledropdownlist/#events","title":"Events","text":"

See Events section of drop-down list

"},{"location":"ui-simplelabel/","title":"Simple label","text":""},{"location":"ui-simplelabel/#introduction","title":"Introduction","text":"

Using plain object to create label.

  • Author: Rex
  • Game object
"},{"location":"ui-simplelabel/#live-demos","title":"Live demos","text":"
  • Style
  • Bitmaptext
  • Nine-slice background
  • Bar-rectangle background
  • Wrap text
  • TextArea
  • Buttons
"},{"location":"ui-simplelabel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-simplelabel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-simplelabel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add label object
    var label = scene.rexUI.add.simpleLabel(style).resetDisplayContent(config);\n//var label = scene.rexUI.add.simpleLabel(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-simplelabel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add label object
    var label = scene.rexUI.add.simpleLabel(style).resetDisplayContent(config);\n//var label = scene.rexUI.add.simpleLabel(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-simplelabel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { SimpleLabel } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add label object
    var label = new SimpleLabel(scene, style);\n// var label = new SimpleLabel(scene, style, creators);\nscene.add.existing(label);\nlabel.resetDisplayContent(config)\n
"},{"location":"ui-simplelabel/#add-label-object","title":"Add label object","text":"
var label = scene.rexUI.add.simpleLabel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundStyle,\n// background: null,\n\nicon: iconStyle,\n// icon: null,\n\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntext: textStyle,\n// text: null,\n\n// wrapText: false,\n// adjustTextFontSize: false,\n// expandTextWidth: false,\n// expandTextHeight: false,\n\naction: actionStyle,\n// action: null,\n\n// squareFitAction: false,\n// actionMask: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n\nalign: undefined,  // 'left' | 'top' | 'right' | 'bottom' | 'center\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • background :
    • Style of Background : Create Round-rectangle, Bar-rectangle, Nine-slice, or Image as background element.
    • null : Don't create any game object.
  • text :
    • Style of Text : Create Text, BBCodeText, BitmapText, SimpleLabel, or TextArea as text element.
    • null : Don't create any game object.
  • icon, action :
    • Style of Image : Create Image, Nine-slice, or Round-rectangle as image, action element.
    • null : Don't create any game object.
"},{"location":"ui-simplelabel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLabel extends RexPlugins.UI.SimpleLabel {\nconstructor(scene, config, creators) {\nsuper(scene, config, creators);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var label = new MyLabel(scene, config, creators);\n
"},{"location":"ui-simplelabel/#reset-display-content","title":"Reset display content","text":"

See label

"},{"location":"ui-simplelabel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

label.layout();\n

See also - dirty

"},{"location":"ui-simplelabel/#set-state","title":"Set state","text":"

Override/restore properties of elements.

"},{"location":"ui-simplelabel/#active-state","title":"Active state","text":"
  • Enable active state
    label.setActiveState();\n// label.setActiveState(true);\n
    • Override properties of background declared in config with prefix 'active.' parameters.
  • Disable active state
    label.setActiveState(false);\n
    • Restore properties of background.
"},{"location":"ui-simplelabel/#hover-state","title":"Hover state","text":"
  • Enable active state
    label.setHoverState();\n// label.setHoverState(true);\n
    • Override properties of background declared in config with prefix 'hover.' parameters
  • Disable active state
    label.setHoverState(false);\n
    • Restore properties of background.
"},{"location":"ui-simplelabel/#disable-state","title":"Disable state","text":"
  • Enable disable state
    label.setDisableState();\n// label.setDisableState(true);\n
    • Override properties of background declared in config with prefix 'disable.' parameters
  • Disable disable state
    label.setDisableState(false);\n
    • Restore properties of background.
"},{"location":"ui-simplelabel/#get-element","title":"Get element","text":"

See label

"},{"location":"ui-simplelabel/#other-properties","title":"Other properties","text":"

See label, sizer object, base sizer object, container-lite.

"},{"location":"ui-simpletextbox/","title":"Simple text box","text":""},{"location":"ui-simpletextbox/#introduction","title":"Introduction","text":"

Using plain object to create textBox.

  • Author: Rex
  • Game object
"},{"location":"ui-simpletextbox/#live-demos","title":"Live demos","text":"
  • Inner sizer
"},{"location":"ui-simpletextbox/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-simpletextbox/#install-plugin","title":"Install plugin","text":""},{"location":"ui-simpletextbox/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add textBox object
    var textBox = scene.rexUI.add.simpleTextBox(style).resetDisplayContent(config);\n//var textBox = scene.rexUI.add.simpleTextBox(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-simpletextbox/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add textBox object
    var textBox = scene.rexUI.add.simpleTextBox(style).resetDisplayContent(config);\n//var textBox = scene.rexUI.add.simpleTextBox(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-simpletextbox/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { SimpleTextBox } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add textBox object
    var textBox = new SimpleTextBox(scene, style);\n// var textBox = new SimpleTextBox(scene, style, creators);\nscene.add.existing(textBox);\ntextBox.resetDisplayContent(config)\n
"},{"location":"ui-simpletextbox/#add-textbox-object","title":"Add textBox object","text":"
var textBox = scene.rexUI.add.simpleTextBox({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nlayoutMode: 0,\n\n// rtl: false,\n\nbackground: backgroundStyle,\n// background: null,\n\ninnerBackground: backgroundStyle,\n// innerBackground: null,\n\nicon: iconStyle,\n// icon: null,\n\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntitle: textStyle,\n// title: null,\n// wrapTitle: false,\n// adjustTitleFontSize: false,\n// expandTitleWidth: false,\n// expandTitleHeight: false,\n\ntext: testStyle,\n// text: null,\n// wrapText: false,\n// adjustTextFontSize: false,\n// expandTextWidth: false,\n// expandTextHeight: false,\n\nseparator: separatorStyle,\n// separator: null,\n\naction: actionStyle,\n// action: null,\n\n// squareFitAction: false,\n// actionMask: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n\nalign: {\ntitle: 'left',\ntext: 'left',\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ninnerLeft: 0, innerRight: 0, innerTop: 0, innerBottom: 0,\n\ntitle: 0, titleLeft: 0, titleRight: 0,\nicon: 0, iconTop: 0, iconBottom: 0,\ntext: 0, textLeft: 0, textRight: 0,\nseparator: 0, separatorLeft: 0, separatorRight: 0,\nactionTop: 0, actionBottom: 0,\n},\n\n// page: { \n//    maxLines: undefined,\n//    pageBreak: '\\f\\n',\n// },\n// typing: { \n//    wrap: false,\n//    speed: 333,    \n// },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • background, innerBackground :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as background element.
    • null : Don't create any game object.
  • title :
    • Style of Text : Create Text, BBCodeText, BitmapText, SimpleLabel, or TextArea as title element.
    • null : Don't create any game object.
  • text :
    • Style of Text : Create Text, BBCodeText, BitmapText as text element.
      • Don't use SimpleLabel, or TextArea as text element.
    • null : Don't create any game object.
  • separator :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as separator element.
    • null : Don't create any game object.
  • icon, action :
    • Style of Image : Create Image, Nine-slice, or Round-rectangle as image, action element.
    • null : Don't create any game object.
  • wrapTitle : Enable WrapExpandText feature.
    • false, 0 : No WrapExpandText feature. Default behavior.
    • true, 1, 'word' : Word WrapExpandText.
    • 2, 'char' : Character WrapExpandText.
  • adjustTitleFontSize : Enable FontSizeExpandText feature.
    • false : No FontSizeExpandText feature. Default behavior.
    • true : Enable FontSizeExpandText feature. Can't work with wrapText: true.
      • Text-width and text-height will be expanding.
      • Use BBCodeText (scene.rexUI.add.BBCodeText) with {valign: 'center'} style.
  • wrapText : Enable WrapExpandText feature.
    • false, 0 : No WrapExpandText feature. Default behavior.
    • true, 1, 'word' : Word WrapExpandText.
    • 2, 'char' : Character WrapExpandText.
  • adjustTextFontSize : Enable FontSizeExpandText feature.
    • false : No FontSizeExpandText feature. Default behavior.
    • true : Enable FontSizeExpandText feature. Can't work with wrapText: true.
      • Text-width and text-height will be expanding.
      • Use BBCodeText (scene.rexUI.add.BBCodeText) with {valign: 'center'} style.
"},{"location":"ui-simpletextbox/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTextBox extends RexPlugins.UI.SimpleTextBox {\nconstructor(scene, config, creators) {\nsuper(scene, config, creators);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var textBox = new MyTextBox(scene, config, creators);\n
"},{"location":"ui-simpletextbox/#reset-display-content","title":"Reset display content","text":"

See title-label

"},{"location":"ui-simpletextbox/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

textBox.layout();\n

See also - dirty

"},{"location":"ui-simpletextbox/#typing","title":"Typing","text":"

See textBox

"},{"location":"ui-simpletextbox/#get-element","title":"Get element","text":"

See textBox

"},{"location":"ui-simpletextbox/#events","title":"Events","text":"

See textBox

"},{"location":"ui-simpletextbox/#other-properties","title":"Other properties","text":"

See textBox, sizer object, base sizer object, container-lite.

"},{"location":"ui-simpletitlelabel/","title":"Simple title label","text":""},{"location":"ui-simpletitlelabel/#introduction","title":"Introduction","text":"

Using plain object to create title-label.

  • Author: Rex
  • Game object
"},{"location":"ui-simpletitlelabel/#live-demos","title":"Live demos","text":"
  • Style
"},{"location":"ui-simpletitlelabel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-simpletitlelabel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-simpletitlelabel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add label object
    var label = scene.rexUI.add.simpleLabel(style).resetDisplayContent(config);\n//var label = scene.rexUI.add.simpleLabel(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-simpletitlelabel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add label object
    var label = scene.rexUI.add.simpleLabel(style).resetDisplayContent(config);\n//var label = scene.rexUI.add.simpleLabel(style, creators).resetDisplayContent(config);\n
"},{"location":"ui-simpletitlelabel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { SimpleTitleLabel } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add label object
    var label = new SimpleTitleLabel(scene, style);\n// var label = new SimpleTitleLabel(scene, style, creators);\nscene.add.existing(label);\nlabel.resetDisplayContent(config)\n
"},{"location":"ui-simpletitlelabel/#add-label-object","title":"Add label object","text":"
var label = scene.rexUI.add.simpleLabel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nlayoutMode: 0,\n\n// rtl: false,\n\nbackground: backgroundStyle,\n// background: null,\n\ninnerBackground: backgroundStyle,\n// innerBackground: null,\n\nicon: iconStyle,\n// icon: null,\n\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntitle: textStyle,\n// title: null,\n// wrapTitle: false,\n// adjustTitleFontSize: false,\n// expandTitleWidth: false,\n// expandTitleHeight: false,\n\ntext: testStyle,\n// text: null,\n// wrapText: false,\n// adjustTextFontSize: false,\n// expandTextWidth: false,\n// expandTextHeight: false,\n\nseparator: separatorStyle,\n// separator: null,\n\naction: actionStyle,\n// action: null,\n\n// squareFitAction: false,\n// actionMask: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n\nalign: {\ntitle: 'left',\ntext: 'left',\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ninnerLeft: 0, innerRight: 0, innerTop: 0, innerBottom: 0,\n\ntitle: 0, titleLeft: 0, titleRight: 0,\nicon: 0, iconTop: 0, iconBottom: 0,\ntext: 0, textLeft: 0, textRight: 0,\nseparator: 0, separatorLeft: 0, separatorRight: 0,\nactionTop: 0, actionBottom: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • background, innerBackground :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as background element.
    • null : Don't create any game object.
  • title :
    • Style of Text : Create Text, BBCodeText, BitmapText, SimpleLabel, or TextArea as title element.
    • null : Don't create any game object.
  • text :
    • Style of Text : Create Text, BBCodeText, BitmapText, SimpleLabel, or TextArea as text element.
    • null : Don't create any game object.
  • separator :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as separator element.
    • null : Don't create any game object.
  • icon, action :
    • Style of Image : Create Image, Nine-slice, or Round-rectangle as image, action element.
    • null : Don't create any game object.
"},{"location":"ui-simpletitlelabel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyLabel extends RexPlugins.UI.SimpleTitleLabel {\nconstructor(scene, config, creators) {\nsuper(scene, config, creators);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var label = new MyLabel(scene, config, creators);\n
"},{"location":"ui-simpletitlelabel/#reset-display-content","title":"Reset display content","text":"

See title-label

"},{"location":"ui-simpletitlelabel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

label.layout();\n

See also - dirty

"},{"location":"ui-simpletitlelabel/#set-state","title":"Set state","text":"

Override/restore properties of elements.

"},{"location":"ui-simpletitlelabel/#active-state","title":"Active state","text":"
  • Enable active state
    label.setActiveState();\n// label.setActiveState(true);\n
    • Override properties of background declared in config with prefix 'active.' parameters.
  • Disable active state
    label.setActiveState(false);\n
    • Restore properties of background.
"},{"location":"ui-simpletitlelabel/#hover-state","title":"Hover state","text":"
  • Enable active state
    label.setHoverState();\n// label.setHoverState(true);\n
    • Override properties of background declared in config with prefix 'hover.' parameters
  • Disable active state
    label.setHoverState(false);\n
    • Restore properties of background.
"},{"location":"ui-simpletitlelabel/#disable-state","title":"Disable state","text":"
  • Enable disable state
    label.setDisableState();\n// label.setDisableState(true);\n
    • Override properties of background declared in config with prefix 'disable.' parameters
  • Disable disable state
    label.setDisableState(false);\n
    • Restore properties of background.
"},{"location":"ui-simpletitlelabel/#get-element","title":"Get element","text":"

See title-label

"},{"location":"ui-simpletitlelabel/#other-properties","title":"Other properties","text":"

See title-label, sizer object, base sizer object, container-lite.

"},{"location":"ui-sizer/","title":"Sizer","text":""},{"location":"ui-sizer/#introduction","title":"Introduction","text":"

Layout children game objects.

It is inspired from wxSizer.

  • Author: Rex
  • Game object
"},{"location":"ui-sizer/#live-demos","title":"Live demos","text":"
  • Nested sizer
    • Demo 1
    • Demo 2
    • Demo 3
  • Proportion
  • DOM child
  • Set children interactive
  • Drag drop child
  • Bring child to top
  • Fit-ratio
  • Sort
"},{"location":"ui-sizer/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-sizer/#install-plugin","title":"Install plugin","text":""},{"location":"ui-sizer/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add sizer object
    var sizer = scene.rexUI.add.sizer(config);\n
"},{"location":"ui-sizer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add sizer object
    var sizer = scene.rexUI.add.sizer(config);\n
"},{"location":"ui-sizer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Sizer } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add sizer object
    var sizer = new Sizer(scene, config);\nscene.add.existing(sizer);\n
"},{"location":"ui-sizer/#add-sizer-object","title":"Add sizer object","text":"
var sizer = scene.rexUI.add.sizer({\norientation: 0,\n// rtl: false,\n// startChildIndex: 0,\n\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0, item:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n

or

var sizer = scene.rexUI.add.sizer(x, y, {\norientation: 0,\n// rtl: false,\n// startChildIndex: 0,\n\n// width: undefined,\n// height: undefined,\n// anchor: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0, item:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n

or

var sizer = scene.rexUI.add.sizer(x, y, width, height, {\norientation: 0,\n// rtl: false,\n// startChildIndex: 0,\n// anchor: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0, item:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n

or

var sizer = scene.rexUI.add.sizer(x, y, width, height, orientation, {\n// rtl: false,\n// startChildIndex: 0,\n// anchor: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// space: { left: 0, right:0, top:0, bottom:0, item:0 }\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation : Orientation of the sizer.
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Arrange game objects from left ot right. Default value is 0.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Arrange game objects from top to bottom.
  • rtl :
    • false : Layout children from left to right. Default behavior.
    • true : Layout children from right to left.
  • startChildIndex : A number, start index of first layout child. Default value is 0.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between 2 children game objects.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-sizer/#custom-class","title":"Custom class","text":"
  • Define class
    class MySizer extends RexPlugins.UI.Sizer {\nconstructor(scene, x, y, minWidth, minHeight, orientation, config) {\nsuper(scene, x, y, minWidth, minHeight, orientation, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var sizer = new MySizer(scene, x, y, minWidth, minHeight, orientation);\n
"},{"location":"ui-sizer/#add-background","title":"Add background","text":"
sizer.addBackground(child);\n

or

sizer.addBackground(child, {left: 0, right: 0, top: 0, bottom: 0}, key);\n
  • left, right, top, bottom : Extra padded space. Default is 0.
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
"},{"location":"ui-sizer/#add-child","title":"Add child","text":"

Add a game obejct to sizer

sizer.add(child);\n

or

sizer.add(child,\n{\nproportion: 0,\nalign: 'center',\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nexpand: false,\nkey: undefined,\nindex: undefined,\nminWidth: undefined,\nminHeight: undefined,\nfitRatio: 0,  // true\n}\n);\n

or

sizer.add(child, proportion, align, padding, expand, key, index);\n// sizer.add(child, proportion, align, padding, expand, key, index);\n
  • child : A game object.
  • proportion :
    • 0, or 'min' : Place next game object closely. Default value.
    • > 0 : Stretch game object via proportion value.
    • null : Don't arrange this child.
  • align :
    • For horizontal orientation sizer :
      • 'center', or Phaser.Display.Align.CENTER : Align game object at vertical-center. Default value.
      • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game object at top-center.
      • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at bottom-center.
      • Use addSpace() to align child at horizontal-center.
    • For vertical orientation sizer :
      • 'center', or Phaser.Display.Align.CENTER : Align game object at horizontal-center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
      • Use addSpace() to align child at vertical-center.
  • padding : Extra padded space. Default is 0.
    • A number for left/right/top/bottom bounds,
    • Or a plain object.
      {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0\n}\n
  • expand : Set true to
    • Expand height when orientation is 0 (left-to-right), or
    • Expand width when orientation is 1 (top-to-bottom)
  • key : Add this child into childMap, which could be read back by sizer.getElement(key).
    • undefined : Don't add this child. Default value.
  • index : Insert child to.
    • undefined : Insert child at last.
  • minWidth : Minimum width of normal (non-sizer) game object, used when orientation is x, and proportion is not 0, or orientation is y, and expand is true
    • Default value is current display width.
  • minHeight : Minimum height of normal (non-sizer) game object, used when orientation is y, and proportion is not 0, or orientation is x, and expand is true
    • Default value is current display height.
  • fitRatio : Resize child to fit sizer height/width before layout children, when proportion is set to 0.
    • 0, or false : Ignore this feature. Default behavior.
    • true : Fit ratio (width/height) from game object's display size.
    • > 0 : Fit ratio (width/height). 1 is square.
"},{"location":"ui-sizer/#insert-child","title":"Insert child","text":"
sizer.insert(index, child, {\nproportion: 0,\nalign: 'center',\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nexpand: false,\nkey: undefined,\nminWidth: undefined,\nminHeight: undefined,\nfitRatio: 0,\n}\n);\n

or

sizer.insert(index, child, proportion, align, padding, expand, key);\n
"},{"location":"ui-sizer/#insert-at-position","title":"Insert at position","text":"
sizer.insertAtPosition(x, y, child, {\nproportion: 0,\nalign: 'center',\npadding: {left: 0, right: 0, top: 0, bottom: 0},\nexpand: false,\nkey: undefined,\nminWidth: undefined,\nminHeight: undefined,\nfitRatio: 0,\n}\n);\n

or

sizer.insertAtPosition(x, y, index, child, proportion, align, padding, expand, key);\n
"},{"location":"ui-sizer/#add-space","title":"Add space","text":"
  • Add a stretchable space.
    sizer.addSpace();\n// sizer.addSpace(proportion);\n
  • Insert a stretchable space.
    sizer.insertSpace(index);\n// sizer.insertSpace(index, proportion);\n

Use cases :

  • Align child at center
    sizer\n.addSpace()\n.add(child)\n.addSpace()\n
  • Align 2 children at left and right side
    sizer\n.add(childLeft)\n.addSpace()\n.add(childRight)\n
"},{"location":"ui-sizer/#change-childrens-align-mode","title":"Change children's align mode","text":"
sizer\n.setChildrenAlignMode(mode)\n.layout();\n
  • mode : Alignment of icon, text, action game objects.
    • undefined, or 'left', or 'top' : Align game objects at left, or top.
      • Remove first and last space children.
    • 'center' : Align game objects at center.
      • Add two spaces as first and last children.
    • 'right', or 'bottom' : Align game objects at right, or bottom.
      • Add space as first child.
"},{"location":"ui-sizer/#layout-children","title":"Layout children","text":"

Arrange position of all children.

sizer.layout();\n

See also - dirty

"},{"location":"ui-sizer/#hide","title":"Hide","text":"
  • Set invisible, won't layout it
    sizer.hide();\n
    or
    sizer.hide(gameObject);\n
  • Set visible, will layout it
    sizer.show();\n
    or
    sizer.show(gameObject);\n
"},{"location":"ui-sizer/#remove-child","title":"Remove child","text":"
  • Remove a child
    sizer.remove(child);\n
  • Remove and destroy a child
    sizer.remove(child, true);\n
  • Remove all children
    sizer.removeAll();\n
  • Remove and destroy all children
    sizer.removeAll(true);\n
  • Remove all children and backgrounds
    sizer.clear();\n
  • Remove and destroy all children and backgrounds
    sizer.clear(true);\n
  • Remove from parent sizer
    sizer.removeFromParentSizer();\n
"},{"location":"ui-sizer/#sort-children","title":"Sort children","text":"
  • Sort by data
    sizer.sortChildrenByData(key, descending).layout();\n
    • key : Data key
    • descending :
      • true : Descending order
      • false : Ascending order, default behavior.
  • Sort by property of child
    sizer.sortChildrenByProperty(key, descending).layout();\n
    • key : Property key
    • descending :
      • true : Descending order
      • false : Ascending order, default behavior.
  • Sort by callback
    sizer.sortChildren(function(childA, childB){\n// var valueA = childA.getData(key);\n// var valueB = childB.getData(key);\n// return valueB - valueA\n}).layout();\n
    • childA, childB : 2 children of this size
"},{"location":"ui-sizer/#get-element","title":"Get element","text":"
  • Get element
    • All children items
      var items = sizer.getElement('items');\n
  • Get by name
    var gameObject = sizer.getElement('#' + name);\n// var gameObject = sizer.getElement('#' + name, recursive);\n
    or
    var gameObject = sizer.getByName(name);\n// var gameObject = sizer.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-sizer/#get-child-index","title":"Get child index","text":"
var index = sizer.getChildIndex(child);\n
  • index : A number, or null.
"},{"location":"ui-sizer/#rtl","title":"RTL","text":"
  • Set rtl in config of constructor
  • Set rtl : sizer.setRTL(enable)
  • Get rtl : var rtl = sizer.rtl
"},{"location":"ui-sizer/#alignment-of-child","title":"Alignment of child","text":"
  • Set alignment of child in config of adding child
  • Set alignment of child : sizer.setChildAlign(child, align)
    • align :
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
      • 'top', or Phaser.Display.Align.RIGHT_CENTER : Align game object at top-center.
      • 'bottom', or Phaser.Display.Align.BOTTOM_CENTER : Align game object at bottom-center.
  • Get alignment of child : var align = sizer.getChildAlign(child)
"},{"location":"ui-sizer/#proportion-of-child","title":"Proportion of child","text":"
  • Set proportion of child in config of adding child
  • Set proportion of child : sizer.setChildProportion(child, proportion)
  • Get proportion of child : var align = sizer.getChildProportion(child)
"},{"location":"ui-sizer/#expand-of-child","title":"Expand of child","text":"
  • Set expand of child in config of adding child
  • Set expand of child : sizer.setChildExpand(child, expand)
  • Get expand of child : var expand = sizer.getChildExpand(child)
"},{"location":"ui-sizer/#other-properties","title":"Other properties","text":"

See base sizer object, container-lite.

"},{"location":"ui-slider/","title":"Slider","text":""},{"location":"ui-slider/#introduction","title":"Introduction","text":"

A container with a track, indicator, thumb and background.

  • Author: Rex
  • Game object
"},{"location":"ui-slider/#live-demos","title":"Live demos","text":"
  • Slider bar
  • Color picker
  • Crop resize
  • Gap
"},{"location":"ui-slider/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-slider/#install-plugin","title":"Install plugin","text":""},{"location":"ui-slider/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add slider object
    var slider = scene.rexUI.add.slider(config);\n
"},{"location":"ui-slider/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add slider object
    var slider = scene.rexUI.add.slider(config);\n
"},{"location":"ui-slider/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Slider } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add slider object
    var slider = new Slider(scene, config);\nscene.add.existing(slider);\n
"},{"location":"ui-slider/#add-slider-object","title":"Add slider object","text":"
var slider = scene.rexUI.add.slider({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\nreverseAxis: false,\n\nbackground: backgroundGameObject,\n/* \n    background: { \n        radius: 0, \n        color: undefined, alpha: 1,\n        strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n        shape: undefined\n    }\n    */\n\ntrack: trackGameObject,\n/* \n    track: { \n        width: 1, height: 1,\n        radius: 0, \n        color: undefined, alpha: 1,\n        strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n        shape: undefined\n    }\n    */    indicator: indicatorGameObject,\n/* \n    indicator: { \n        width: 1, height: 1,\n        radius: 0, \n        color: undefined, alpha: 1,\n        strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n        shape: undefined\n    }\n    */\n\nthumb: thumbGameObject,\n/* \n    thumb: { \n        width: 1, height: 1,\n        radius: 0, \n        color: undefined, alpha: 1,\n        strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n        shape: undefined\n    }\n    */\nthumbOffsetX: 0,\nthumbOffsetY: 0,\n\ninput: 'drag',\n\nvalue: 0,\ngap: undefined,\neaseValue: {\nduration: 0,\nease: 'Linear'\n},    valuechangeCallback: function(newValue, oldValue, slider) {\n},\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n\nenable: true,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Horizontal slider.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Vertical slider.
  • reverseAxis :
    • false : Map left/top to 0, and right/bottom to 1. Default behavior.
    • true : Map left/top to 1, and right/bottom to 0.
  • background :
    • Game object of background, optional. This background game object will be resized to fit the size of slider.
    • A plain object to create round rectangle shape
      { radius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
  • track :
    • Game object of track, optional. This track game object will be resized to fit the size of slider, with space.
    • A plain object to create round rectangle shape
      { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
  • indicator :
    • Game object of indicator, optional.
    • A plain object to create round rectangle shape
      { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
  • thumb :
    • Game object of thumb, optional.
    • A plain object to create round rectangle shape
      { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n}\n
  • thumbOffsetX, thumbOffsetY : Shift thumb, default value is 0.
  • input :
    • 'pan', 'drag', or 0 : Control slider by panning/dragging thumb game object. Default setting.
    • 'click', or 1 : Control slider by touching track game object.
    • 'none', or -1 : Disable sider controlling.
  • value : Initial value (0 ~ 1).
  • gap : Snap a value to nearest grid slice, using rounding.
    • undefined : Disalbe this feature.
  • easeValue : Easing value when input is 'click'.
    • easeValue.duration : Duration of value easing, default is 0 (no easing).
    • easeValue.ease : Ease function, default is 'Linear'.
  • valuechangeCallback : callback function when value changed.
    function(newValue, oldValue, slider) {\n}\n
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
  • enable : Set false to disable controlling.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-slider/#custom-class","title":"Custom class","text":"
  • Define class
    class MySlider extends RexPlugins.UI.Slider {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var slider = new MySlider(scene, config);\n
"},{"location":"ui-slider/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

slider.layout();\n

See also - dirty

"},{"location":"ui-slider/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = slider.getElement('background');\n
    • Track game object
      var track = slider.getElement('track');\n
    • Indicator game object
      var track = slider.getElement('indicator');\n
    • Thumb track game object
      var action = slider.getElement('thumb');\n
  • Get by name
    var gameObject = slider.getElement('#' + name);\n// var gameObject = slider.getElement('#' + name, recursive);\n
    or
    var gameObject = slider.getByName(name);\n// var gameObject = slider.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-slider/#enable","title":"Enable","text":"
  • Get
    var enable = slider.enable;\n
  • Set
    slider.setEanble(enable);\n
    or
    slider.enable = enable;\n
"},{"location":"ui-slider/#value","title":"Value","text":"

Change value will also change the position of slider thumb and width of slider indicator.

  • Get value
    var value = slider.getValue(min, max); // value : min ~ max\n
    or
    var value = slider.getValue(); // value: 0 ~ 1\n
    or
    var value = slider.value; // value: 0 ~ 1\n
  • Set value
    slider.setValue(value, min, max); // value: min ~ max\n
    or
    slider.setValue(value); // value: 0 ~ 1\n
    or
    slider.value = value; // value: 0 ~ 1\n
  • Increase value
    slider.addValue(inc, min, max); // inc: min ~ max\n
    or
    slider.addValue(inc); // inc: 0 ~ 1\n
    or
    slider.value += inc; // inc: 0 ~ 1\n
"},{"location":"ui-slider/#ease-value","title":"Ease value","text":"
  • Ease value to
    slider.easeValueTo(value, min, max);  // value: min ~ max\n
    or
    slider.easeValueTo(value);  // value: 0 ~ 1\n
  • Stop ease
    slider.stopEaseValue();\n
  • Set ease duration
    slider.setEaseValueDuration(duration);\n
  • Set ease function
    slider.setEaseValueFunction(ease);\n
    • ease : Ease function.
"},{"location":"ui-slider/#gap","title":"Gap","text":"
  • Set
    slider.setGap(gap);  // gap: 0~1\n
    or
    slider.setGap(gap, min, max);  // gap: min~max\n
  • Get
    var gap = slider.gap;  // gap: 0~1\n
"},{"location":"ui-slider/#events","title":"Events","text":"
  • On value changed
    slider.on('valuechange', function(newValue, oldValue, slider){\n//\n}, scope);\n
  • On input start
    slider.on('inputstart', function(pointer) {\n\n}, scope);\n
  • On input end
    slider.on('inputend', function(pointer) {\n\n}, scope);\n
"},{"location":"ui-slider/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-splitpanels/","title":"Split panels","text":""},{"location":"ui-splitpanels/#introduction","title":"Introduction","text":"

A container with left(top) panel, right(bottom) panel, splitter, and background. Drag splitter to resize with left(top) panel, right(bottom) panel.

  • Author: Rex
  • Game object
"},{"location":"ui-splitpanels/#live-demos","title":"Live demos","text":"
  • Split-panels
"},{"location":"ui-splitpanels/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-splitpanels/#install-plugin","title":"Install plugin","text":""},{"location":"ui-splitpanels/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add split-panels object
    var splitPanels = scene.rexUI.add.splitPanels(config);\n
"},{"location":"ui-splitpanels/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add split-panels object
    var splitPanels = scene.rexUI.add.splitPanels(config);\n
"},{"location":"ui-splitpanels/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { SplitPanels } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add split-panels object
    var splitPanels = new SplitPanels(scene, config);\nscene.add.existing(splitPanels);\n
"},{"location":"ui-splitpanels/#add-split-panels-object","title":"Add split-panels object","text":"
var splitPanels = scene.rexUI.add.splitPanels({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nbackground: backgroundGameObject,\n\nleftPanel: leftPanelGameObject,\n// topPanel: topPanelGameObject,\n\nrightPanel: rightPanelGameObject,\n// bottomPanel: topPanelGameObject,\n\nsplitter: splitterGameObject,\n\nminLeftPanelWidth: 0,\nminTopPanelHeight: 0,\n\nminRightPanelWidth: 0,\nminBottomPanelHeight: 0,\n\nsplitRatio: 0.5\n\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0, item: 0,\n\nleftPanelTop: 0, leftPanelBottom: 0, leftPanelLeft: 0, leftPanelRight: 0,\n// topPanelTop: 0, topPanelBottom: 0, topPanelLeft: 0, topPanelRight: 0,\n\nrightPanelTop: 0, rightPanelBottom: 0, rightPanelLeft: 0, rightPanelRight: 0,\n// bottomPanelTop: 0, bottomPanelBottom: 0, bottomPanelLeft: 0, bottomPanelRight: 0,\n\nsplitterPanelTop: 0, splitterPanelBottom: 0, splitterPanelLeft: 0, splitterPanelRight: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • leftPanel(topPanel), rightPanel(bottomPanel) : First and second panel children.
  • splitter : Game object of splitter.
  • minLeftPanelWidth(minTopPanelHeight), minRightPanelWidth(minBottomPanelHeight) : Minimum width/height of first and second children.
    • 0 : Width/height does not have constraint. Default behavior.
  • splitRatio : Position of splitter. 0~1. Default value is 0.5.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between first child and splitter, splitter and second child.
    • space.leftPanelTop(space.topPanelTop), space.leftPanelBottom(space.topPanelBottom), space.leftPanelLeft(space.topPanelLeft), space.leftPanelRight(space.topPanelRight) : Space around first game object.
    • space.rightPanelTop(space.bottomPanelTop), space.rightPanelBottom(space.bottomPanelBottom), space.rightPanelLeft(space.bottomPanelLeft), space.rightPanelRight(space.bottomPanelRight) : Space around second game object.
    • space.splitterTop, space.splitterBottom, space.splitterLeft, space.splitterRight : Space around splitter game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-splitpanels/#custom-class","title":"Custom class","text":"
  • Define class
    class MySplitPanels extends RexPlugins.UI.SplitPanels {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var splitPanels = new MySplitPanels(scene, config);\n
"},{"location":"ui-splitpanels/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

splitPanels.layout();\n

See also - dirty

"},{"location":"ui-splitpanels/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = splitPanels.getElement('background');\n
    • First game object
      var leftPanel = splitPanels.getElement('leftPanel');\n// var topPanel = splitPanels.getElement('topPanel');\n
    • Second game object
      var rightPanel = splitPanels.getElement('rightPanel');\n// var bottomPanel = splitPanels.getElement('bottomPanel');\n
    • Splitter game object
      var splitter = splitPanels.getElement('splitter');\n
  • Get by name
    var gameObject = splitPanels.getElement('#' + name);\n// var gameObject = splitPanels.getElement('#' + name, recursive);\n
    or
    var gameObject = splitPanels.getByName(name);\n// var gameObject = splitPanels.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-splitpanels/#split-ratio","title":"Split ratio","text":"
  • Get
    var splitRatio = splitPanels.splitRatio;\n
  • Set
    splitPanels.setSplitRatio(value);\n
    or
    splitPanels.splitRatio = value;\n
"},{"location":"ui-splitpanels/#minimum-child-size","title":"Minimum child size","text":"
  • Get
    var minLeftPanelWidth = splitPanels.minLeftPanelWidth;\n// var minTopPanelHeight = splitPanels.minTopPanelHeight;\n\nvar minRightPanelWidth = splitPanels.minRightPanelWidth;\n// var minBottomPanelHeight = splitPanels.minBottomPanelHeight;\n
  • Set
    splitPanels.setMinLeftPanelWidth(value);\n// splitPanels.setMinTopPanelHeight(value);\n\nsplitPanels.setMinRightPanelWidth(value);\n// splitPanels.setMinBottomPanelHeight(value);\n
    or
    splitPanels.minLeftPanelWidth = value;\n// splitPanels.minTopPanelHeight = value;\n\nsplitPanels.minRightPanelWidth = value;\n// splitPanels.minBottomPanelHeight = value;\n
"},{"location":"ui-splitpanels/#enable","title":"Enable","text":"
  • Get
    var enable = splitPanels.splitterEnable;\n
  • Set
    slider.setSplitterEnable(enable);\n
    or
    slider.splitterEnable = enable;\n
"},{"location":"ui-splitpanels/#events","title":"Events","text":"
  • On drag splitter start
    splitPanels.on('splitter.dragstart', function(splitter, splitRatio){\n//\n}, scope);\n
  • On drag splitter end
    splitPanels.on('splitter.dragend', function(splitter, splitRatio){\n//\n}, scope);\n
  • On dragging splitter
    splitPanels.on('splitter.drag', function(splitter, splitRatio){\n//\n}, scope);\n
  • On pointer-over splitter
    splitPanels.on('splitter.over', function(splitter, splitRatio){\n//\n}, scope);\n
  • On pointer-out splitter
    splitPanels.on('splitter.out', function(splitter, splitRatio){\n//\n}, scope);\n
"},{"location":"ui-splitpanels/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-style/","title":"Style","text":""},{"location":"ui-style/#introduction","title":"Introduction","text":"

Style in plain object for creating image, or text.

"},{"location":"ui-style/#style-of-background","title":"Style of Background","text":"

Create Round-rectangle, Nine-slice, Nine-patch, or Image for background.

  • Create Round-rectangle, if style has color, or strokeColor key. Default type of Background.
  • Create Line-progress, if style has bar key.
  • Create Nine-slice, if style has leftWidth key.
  • Create Nine-patch, if style has leftWidth and stretchMode key.
  • Create Image, if style has key key.
"},{"location":"ui-style/#style-of-image","title":"Style of Image","text":"

Create Image, Nine-slice, Nine-patch, or Round-rectangle for image.

  • Create Image, if style has key key. Default type of Background.
  • Create Nine-slice, if style has leftWidth key.
  • Create Nine-patch, if style has leftWidth and stretchMode key.
  • Create Round-rectangle, if style has color, or strokeColor key.
"},{"location":"ui-style/#style-of-text","title":"Style of Text","text":"

Create Text, BBCodetext, BitmapText, SimpleLabel, or TextArea for text.

  • Text, by style, default type of Text.
  • BBCodetext, by style.
  • BitmapText, by style.
  • SimpleLabel, by style.
  • TextArea, by style.
"},{"location":"ui-style/#style-of-image-game-object","title":"Style of Image game object","text":"
{\n// $type: 'image',\n\nkey:\n// frame:\n// tint: 0xffffff,\n// alpha: 1,\n// scale: 1,\n// flipX: false,\n// flipY: false,\n// origin:\n// originX: \n// originY:\n\n// effects: true,\n// Style override in active state\n// 'active.key': undefined,\n// 'active.frame': undefined,\n// 'active.tint': undefined,\n// 'active.alpha': undefined,\n// 'active.scale': undefined,\n// 'active.glowColor': null,\n// ...\n\n// Style override in hover state\n// 'hover.key': undefined,\n// 'hover.frame': undefined,\n// 'hover.tint': undefined,\n// 'hover.alpha': undefined,\n// 'hover.scale': undefined,\n// 'hover.glowColor': null,\n// ...\n\n// Style override in disable state\n// 'disable.key': undefined,\n// 'disable.frame': undefined,\n// 'disable.tint': undefined,\n// 'disable.alpha': undefined,\n// 'disable.scale': undefined,\n// 'disable.glowColor': null,\n// ...    \n}\n
"},{"location":"ui-style/#style-of-nine-slice","title":"Style of Nine-slice","text":"
{\n// $type: 'nineSlice',\n\nkey: ,\nframe: ,\nleftWidth: , rightWidth: ,\ntopHeight: , bottomHeight: ,\n// tint: 0xffffff,\n// alpha: 1,\n// scale: 1,\n// flipX: false,\n// flipY: false,\n// origin:\n// originX: \n// originY:\n// width: 0,\n// height: 0,\n\n// effects: true,\n\n// Style override in active state\n// 'active.key': undefined,\n// 'active.frame': undefined,\n// 'active.tint': undefined,\n// 'active.alpha': undefined,\n// 'active.scale': undefined,\n// 'active.glowColor': null,\n// ...\n\n// Style override in hover state\n// 'hover.key': undefined,\n// 'hover.frame': undefined,\n// 'hover.tint': undefined,\n// 'hover.alpha': undefined,\n// 'hover.scale': undefined,\n// 'hover.glowColor': null,\n// ...\n\n// Style override in disable state\n// 'disable.key': undefined,\n// 'disable.frame': undefined,\n// 'disable.tint': undefined,\n// 'disable.alpha': undefined,\n// 'disable.scale': undefined,\n// 'disable.glowColor': null,\n// ...  \n}\n
"},{"location":"ui-style/#style-of-nine-patch","title":"Style of Nine-patch","text":"
{\n// $type: 'nineSlice',\n\nkey: ,\nframe: ,\nleftWidth: , rightWidth: ,\ntopHeight: , bottomHeight: ,\nstretchMode: ,\n// tint: 0xffffff,\n// alpha: 1,\n// scale: 1,\n// flipX: false,\n// flipY: false,\n// origin:\n// originX: \n// originY:\n// width: 0,\n// height: 0,\n\n// effects: true,\n\n// Style override in active state\n// 'active.key': undefined,\n// 'active.frame': undefined,\n// 'active.tint': undefined,\n// 'active.alpha': undefined,\n// 'active.scale': undefined,\n// 'active.glowColor': null,\n// ...\n\n// Style override in hover state\n// 'hover.key': undefined,\n// 'hover.frame': undefined,\n// 'hover.tint': undefined,\n// 'hover.alpha': undefined,\n// 'hover.scale': undefined,\n// 'hover.glowColor': null,\n// ...\n\n// Style override in disable state\n// 'disable.key': undefined,\n// 'disable.frame': undefined,\n// 'disable.tint': undefined,\n// 'disable.alpha': undefined,\n// 'disable.scale': undefined,\n// 'disable.glowColor': null,\n// ...  \n}\n
"},{"location":"ui-style/#style-of-round-rectangle","title":"Style of Round-rectangle","text":"
{\n// $type: 'roundRectangle',\n\ncolor: 0xffffff,\n// alpha: 1,\n// origin:\n// originX: \n// originY:\nstrokeColor: 0xffffff,\n// strokeAlpha: 1,\n// strokeWidth: 2,\n// radius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n// width: 0,\n// height: 0,\n\n// Style override in active state\n// 'active.color': undefined,\n// 'active.alpha': undefined,\n// 'active.strokeColor': undefined,\n// 'active.strokeAlpha': undefined,\n// 'active.strokeWidth': undefined,\n// 'active.radius': undefined,\n// 'active.xxx': ...\n\n// Style override in hover state\n// 'hover.color': undefined,\n// 'hover.alpha': undefined,\n// 'hover.strokeColor': undefined,\n// 'hover.strokeAlpha': undefined,\n// 'hover.strokeWidth': undefined,\n// 'hover.radius': undefined,\n// 'hover.xxx': ...\n\n// Style override in disable state\n// 'disable.color': undefined,\n// 'disable.alpha': undefined,\n// 'disable.strokeColor': undefined,\n// 'disable.strokeAlpha': undefined,\n// 'disable.strokeWidth': undefined,\n// 'disable.radius': undefined,\n// 'disable.xxx': ...\n}\n
"},{"location":"ui-style/#style-of-bar-rectangle","title":"Style of bar-rectangle","text":"

Bar-rectangle = Line-progress

{\n// $type: 'bar',\n\nbarColor: 0xffffff,\n// easeDuration: 200,\n// ease: 'Quad',\n// rtl: false,\n\n// alpha: 1,\n// origin:\n// originX: \n// originY:\n// color: 0xffffff,\n// strokeColor: 0xffffff,\n// strokeAlpha: 1,\n// strokeWidth: 2,    \n// width: 0,\n// height: 0,\n\n// Style override in active state\n// 'active.barColor': undefined,\n// 'active.color': undefined,\n// 'active.alpha': undefined,\n// 'active.strokeColor': undefined,\n// 'active.strokeAlpha': undefined,\n// 'active.strokeWidth': undefined,\n// 'active.radius': undefined,\n// 'active.xxx': ...\n\n// Style override in hover state\n// 'hover.barColor': undefined,\n// 'hover.color': undefined,\n// 'hover.alpha': undefined,\n// 'hover.strokeColor': undefined,\n// 'hover.strokeAlpha': undefined,\n// 'hover.strokeWidth': undefined,\n// 'hover.radius': undefined,\n// 'hover.xxx': ...,\n// 'hover.bar: true,\n\n// Style override in disable state\n// 'disable.barColor': undefined,\n// 'disable.color': undefined,\n// 'disable.alpha': undefined,\n// 'disable.strokeColor': undefined,\n// 'disable.strokeAlpha': undefined,\n// 'disable.strokeWidth': undefined,\n// 'disable.radius': undefined,\n// 'disable.xxx': ...\n}\n
"},{"location":"ui-style/#style-of-text-game-object","title":"Style of Text game object","text":"
{\n// $type: 'text',\n\n// Normal text-style\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},\nalign: 'left',  // 'left'|'center'|'right'|'justify'\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\nmaxLines: 0,\nlineSpacing: 0,\nfixedWidth: 0,\nfixedHeight: 0,\nrtl: false,\ntestString: '|M\u00c9qgy',\nwordWrap: {\nwidth: null,\ncallback: null,\ncallbackScope: null,\nuseAdvancedWrap: false\n},\nmetrics: false,\n// metrics: {\n//     ascent: 0,\n//     descent: 0,\n//     fontSize: 0\n// },\n\n// tint: 0xffffff,\n// alpha: 1,\n// scale: 1,\n// flipX: false,\n// flipY: false,\n// origin:\n// originX: \n// originY:\n\n// Style override in active state\n'active.fontFamily': undefined,\n'active.fontSize': undefined,\n'active.fontStyle': undefined,\n'active.backgroundColor': undefined,\n'active.color': undefined,\n'active.fill': undefined,\n'active.stroke': undefined,\n'active.strokeThickness': undefined,\n\n// Style override in hover state\n'hover.fontFamily': undefined,\n'hover.fontSize': undefined,\n'hover.fontStyle': undefined,\n'hover.backgroundColor': undefined,\n'hover.color': undefined,\n'hover.fill': undefined,\n'hover.stroke': undefined,\n'hover.strokeThickness': undefined,\n\n// Style override in disable state\n'disable.fontFamily': undefined,\n'disable.fontSize': undefined,\n'disable.fontStyle': undefined,\n'disable.backgroundColor': undefined,\n'disable.color': undefined,\n'disable.fill': undefined,\n'disable.stroke': undefined,\n'disable.strokeThickness': undefined,\n}\n
"},{"location":"ui-style/#style-of-bbcodetext","title":"Style of BBCodeText","text":"
{\n$type: 'bbcodetext', // or 'bbcode'\n\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},\nalign: 'left',  // 'left'|'center'|'right'|'justify'\npadding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\nmaxLines: 0,\nlineSpacing: 0,\nfixedWidth: 0,\nfixedHeight: 0,\nrtl: false,\ntestString: '|M\u00c9qgy',\nwrap: {\nmode: 'none'     // 0|'none'|1|'word'|2|'char'|'character'|3|'mix'\nwidth: null\n},\n// wordWrap: { width: 0 },   // Compatible with Text game object\nmetrics: false,\n// metrics: {\n//     ascent: 0,\n//     descent: 0,\n//     fontSize: 0\n// },\n\n// tint: 0xffffff,\n// alpha: 1,\n// scale: 1,\n// flipX: false,\n// flipY: false,\n// origin:\n// originX: \n// originY:\n}\n
"},{"location":"ui-style/#style-of-bitmaptext","title":"Style of BitmapText","text":"
{\n// $type: 'bitmaptext',  // or 'bitmap'\n\nfont: '',\nfontSize: undefined,\nalign: undefined,\ntint: undefined,\nletterSpacing: undefined,\nlineSpacing: undefined,\n\n// tint: 0xffffff,\n// alpha: 1,\n// scale: 1,\n// origin:\n// originX: \n// originY:\n\n// Style override in active state\n'active.font': undefined,\n'active.fontSize': undefined,\n'active.tint': undefined,\n'active.letterSpacing': undefined,\n'active.lineSpacing': undefined,\n\n// Style override in hover state\n'hover.font': undefined,\n'hover.fontSize': undefined,\n'hover.tint': undefined,\n'hover.letterSpacing': undefined,\n'hover.lineSpacing': undefined,\n\n// Style override in disable state\n'disable.font': undefined,\n'disable.fontSize': undefined,\n'disable.tint': undefined,\n'disable.letterSpacing': undefined,\n'disable.lineSpacing': undefined,\n}\n
"},{"location":"ui-style/#style-of-simplelabel","title":"Style of SimpleLabel","text":"
{\n$type: 'label',\n\n// width: undefined,\n// height: undefined,\n// origin:\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\nbackground: backgroundStyle,\n\nicon: iconStyle,\n\n// iconMask: false,\n// squareFitIcon: false,\n// iconSize: undefined, iconWidth: undefined, iconHeight: undefined,\n\ntext: testStyle,\n// wrapText: false,  // false|'word'|'char',\n// adjustTextFontSize: false,\n// expandTextWidth: false,\n// expandTextHeight: false,\n\naction: actionStyle,\n\n// squareFitAction: false,\n// actionMask: false,\n// actionSize: undefined, actionWidth: undefined, actionHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n\nalign: undefined,  // 'left' | 'top' | 'right' | 'bottom' | 'center\n}    
  • background :
    • Style of Background : Create Round-rectangle, Nine-slice, or Image as background element.
    • null : Don't create any game object.
  • text :
    • Style of Text : Create Text, BBCodeText, BitmapText, SimpleLabel, or TextArea as text element.
    • null : Don't create any game object.
  • icon, action :
    • Style of Image : Create Image, Nine-slice, or Round-rectangle as image, action element.
    • null : Don't create any game object.
"},{"location":"ui-style/#style-of-textarea","title":"Style of TextArea","text":"

{\n$type: 'textarea',\n\nspace: { left: 0, right: 0, top: 0, bottom: 0, text: 0, },\n\n// width:\n// height:\n// origin:\n// originX:\n// originY:\n\nbackground: backgroundStyle,\n\ntext: textStyle,\n\n// textWidth: undefined,\n// textHeight: undefined,\n// textMask: false,\n// alwaysScrollable: false,\n\nslider: {\ntrack: backgroundStyle,\n\nthumb: backgroundStyle,\n\n// input: 'drag',\n// position: 'right',\n\n// hideUnscrollableSlider: false,\n// adaptThumbSize: false,\n// minThumbSize: undefined,\n},\n// slider: null,\n\n// scroller: {\n//     threshold: 10,\n//     slidingDeceleration: 5000,\n//     backDeceleration: 2000,\n//     pointerOutRelease: true,\n//     dragRate: 1,\n// },\n\nmouseWheelScroller: false,\n// mouseWheelScroller: {\n//     focus: true,\n//     speed: 0.1\n// },\n\nclampChildOY: false,\n}\n
- background : - Style of Background : Create round-rectangle, nine-slice, or image as background element. - null : Don't create any game object. - text : - Style of Text : Create text, BBCodeText, BitmapText, or SimpleLabel as text element. - null : Don't create any game object. - slider : - slider.track : - Style of Background : Create round-rectangle, nine-slice, or image as track element. - null : Don't create any game object. - slider.thumb : - Style of Background : Create round-rectangle, nine-slice, or image as thumb element. - null : Don't create any game object. - null, or false : Don't create any game object for slider.

"},{"location":"ui-style/#style-of-canvasinput","title":"Style of CanvasInput","text":"

CanvasInput

{\nwidth: undefined, height: undefined,\n\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null,\n\n// Style when focus\n// 'focus.color': ...\n// 'focus.color2': ...\n// 'focus.stroke': ...\n},\nfocusStyle: undefined,\n\ninnerBounds: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBY: undefined,\noffsetX: 0,\noffsetY: 0,\n\n// Style when cursor move on\n// 'cursor.color': ...\n// 'cursor.backgroundColor': ...\n// 'cursor.xxx': ...\n},\ncursorStyle: undefined,\n}\n
"},{"location":"ui-style/#style-of-triangle","title":"Style of triangle","text":"
{\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n
"},{"location":"ui-tabpages/","title":"Tab pages","text":""},{"location":"ui-tabpages/#introduction","title":"Introduction","text":"

A container with tabs and pages, only current page is visible.

  • Author: Rex
  • Game object
"},{"location":"ui-tabpages/#live-demos","title":"Live demos","text":"
  • Tabpage
"},{"location":"ui-tabpages/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-tabpages/#install-plugin","title":"Install plugin","text":""},{"location":"ui-tabpages/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add tab-pages object
    var tabPages = scene.rexUI.add.tabPages(config);\n
"},{"location":"ui-tabpages/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add tab-pages object
    var tabPages = scene.rexUI.add.tabPages(config);\n
"},{"location":"ui-tabpages/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { TabPages } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add tab-pages object
    var tabPages = new TabPages(scene, config);\nscene.add.existing(tabPages);\n
"},{"location":"ui-tabpages/#add-tab-pages-object","title":"Add tab-pages object","text":"
var tabPages = scene.rexUI.add.tabPages({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// background: backgroundGameObject,\n\ntabsPosition: 'top',\n// tabPosition: 'top',\n\nwrapTabs: false,\n\ntabs: {\n// width:\n// height:\n// rtl:\n\n// background: backgroundGameObject,        \nalign:\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n},\nspace: { left: 0, right:0, top:0, bottom:0, item:0 }\n},\n\npages: {\nspace: { left: 0, right:0, top:0, bottom:0 },\nfadeIn: 0,\n},\n\nexpand: {\ntabs: false,\n},\n\nalign: {\ntabs: 'left',\n},\n\n// space: { left:0, right:0, top:0, bottom:0, item:0 },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • tabsPosition (or tabPosition) : Put tabs at top, bottom, left, right of pages.
    • 'top', 'bottom', 'left', 'right' : Default value is 'top'.
  • wrapTabs :
    • false : Uses Buttons as Tabs, default behavior.
    • true :
      • Using FixWidthButtons as Tabs, if tabPosition is 'top' or 'bottom'.
      • Using Buttons as Tabs, if tabPosition is 'left' or 'right'
  • tabs : Configuration of tabs, which is a buttons game object.
    • tabs.width, tabs.height : Minimum width, minimum height of tabs, to preserve space if tabs is empty, optional.
    • tabs.rtl :
      • true : Layout buttons from right to left.
      • false : Layout buttons from left to right. Default behavior.
    • tabs.background : Game object of background, optional. This background game object will be resized to fit the size of grid table.
    • tabs.space :
      • tabs.space.top, tabs.space.bottom, tabs.space.left, tabs.space.right : Padding around bottons.
      • tabs.space.item : Space between 2 button game objects.
    • tabs.click: Configuration of button clicking.
      • tabs.click.mode :
        • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
        • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
      • tabs.click.clickInterval : Interval between 2 'click' events, in ms.
  • pages : Configuration of pages
    • pages.space : Pads spaces.
      • pages.space.left, pages.space.right, pages.space.top, pages.space.bottom : Space of bounds.
    • pages.fadeIn : Fade-in duration of current page.
      • 0 : No fade-in effect. Default behavior.
  • expand :
    • expand.tabs : Set true to expand width/height of tabs. Default value is false.
  • align :
    • align.tabs :
      • 'left'. 'right', 'center' : Align tabs to left/right/center side when tabPosition is 'top' or 'bottom'.
      • 'top'. 'bottom', 'center' : Align tabs to top/bottom/center side when tabPosition is 'left' or 'right'.
  • space :
    • An object: Padding of button game objects.
      • space.top, space.bottom, space.left, space.right : Padding around bottons.
      • space.item : Space between tabs and pages.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-tabpages/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTabPages extends RexPlugins.UI.TabPages {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var tabPages = new MyTabPages(scene, config);\n
"},{"location":"ui-tabpages/#add-page","title":"Add page","text":"

Add a tab/page to last of tabs/pages.

tabPages.addPage(key, tabGameObject, pageGameObject).layout();\n

or

tabPages.addPage({\n// key: undefined,\ntab: tabGameObject,\npage: pageGameObject\n}).layout();\n
  • key : Unique string name of this page.
    • undefined : Create an UUID for key.
  • tab : A game object, will put it into tabs.
  • page : A game object, will put it into pages.

Note

Invoke tabPages.layout() after adding pages.

"},{"location":"ui-tabpages/#swap-to-page","title":"Swap to page","text":"
  • Swap to related page when clicking tab.
  • Swap to page by key/index
    tabPages.swapPage(key);\n
    tabPages.swapPage(index);\n
    • key : Unique string name of the page.
    • index : Index number in tabs.
  • Swap to first page
    tabPages.swapFirstPage();\n
  • Swap to last page
    tabPages.swapLastPage();\n
  • Swap page without fade-in transition
    tabPages.swapPage(key, 0);\n
    tabPages.swapPage(index, 0);\n
    tabPages.swapFirstPage(0);\n
    tabPages.swapLastPage(0);\n
"},{"location":"ui-tabpages/#remove-page","title":"Remove page","text":"
  • Remove page
    tabPages.removePage(key);\n
    tabPages.removePage(index);\n
  • Remove and destroy page
    tabPages.removePage(key, true);\n
    tabPages.removePage(index, true);\n
  • Remove all pages
    tabPages.removeAllPages();\n
  • Remove and destroy all pages
    tabPages.removeAllPages(true);\n
"},{"location":"ui-tabpages/#change-tabs-position","title":"Change tabs position","text":"
tabPages.setTabPosition(position);\n
  • position : 'top', 'bottom', 'left', 'right'
"},{"location":"ui-tabpages/#padding-of-tabs","title":"Padding of tabs","text":"
  • Change padding
    tabPages.setTabsPadding(key, value).layout();\n
    or
    tabPages.setTabsPadding({\nleft: leftPadding, right: rightPadding,\ntop: topPadding,\nbottom: bottomPadding\n}).layout();\n
    • key : 'left', 'right', 'top', 'bottom', 'item'
  • Get padding
    var value = tabPages.getTabsPadding(key);\n
    • key : 'left', 'right', 'top', 'bottom', 'item'
"},{"location":"ui-tabpages/#get-element","title":"Get element","text":"
  • Get element
    • Pages
      var gameObject = tabPages.getElement('pages');\n
    • Tabs, a buttons
      var gameObject = tabPages.getElement('tabs');\n
    • Page by key/index
      var gameObject = tabPages.getPage(key);\n
      var gameObject = tabPages.getPage(index);\n
      • key : Unique string name of the page.
      • index : Index number in tabs.
    • Tab by key/index
      var gameObjects = tabPages.getTab(key);\n
      var gameObjects = tabPages.getTab(index);\n
      • key : Unique string name of the page.
      • index : Index number in tabs.
  • Get by name
    var gameObject = tabPages.getElement('#' + name);\n// var gameObject = pages.getElement('#' + name, recursive);\n
    or
    var gameObject = tabPages.getByName(name);\n// var gameObject = tabPages.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-tabpages/#other-properties","title":"Other properties","text":"

See sizer, base sizer object, container-lite, Pages, Buttons

"},{"location":"ui-tabpages/#events","title":"Events","text":"
  • When swapping to a page by clicking tab, or tabPages.swapPage(key)
    pages.on('tab.focus', function(tab, key) {\n// ...\n}, scope);\npages.on('page.focus', function(page, key) {\n// ...\n}, scope);\n
    pages.on('tab.blur', function(tab, key) {\n// ...\n}, scope);\npages.on('page.blur', function(page, key) {\n// ...\n}, scope);    
    • tab : Game object of tab.
    • page : Game object of page.
    • key : Unique string name of the page.
"},{"location":"ui-tabs/","title":"Tabs","text":""},{"location":"ui-tabs/#introduction","title":"Introduction","text":"

A container with 4 groups of buttons around a center panel.

  • Author: Rex
  • Game object
"},{"location":"ui-tabs/#live-demos","title":"Live demos","text":"
  • Tabs
  • Expand buttons
  • Tabs-table
"},{"location":"ui-tabs/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-tabs/#install-plugin","title":"Install plugin","text":""},{"location":"ui-tabs/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add tabs object
    var tabs = scene.rexUI.add.tabs(config);\n
"},{"location":"ui-tabs/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add tabs object
    var tabs = scene.rexUI.add.tabs(config);\n
"},{"location":"ui-tabs/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Tabs } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add tabs object
    var tabs = new Tabs(scene, config);\nscene.add.existing(tabs);\n
"},{"location":"ui-tabs/#add-tabs-object","title":"Add Tabs object","text":"
var tabs = scene.rexUI.add.tabs({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\nbackground: backgroundGameObject,\npanel: panelGameObject,\n\nleftButtons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\nrightButtons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\ntopButtons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\nbottomButtons: [\nbuttonGameObject,\nbuttonGameObject,\n// ...\n],\nleftButtonsBackground: leftButtonsBackgroundGameObject,\nrightButtonsBackground: rightButtonsBackgroundGameObject,\ntopButtonsBackground: topButtonsBackgroundGameObject,\nbottomButtonsBackground: bottomButtonsBackgroundGameObject,\n\nexpand: {\npanel: false,\nleftButtons: false,\nrightButtons: false,\ntopButtons: false,\nbottomButtons: false,\n},\n\nalign: {\nleftButtons: 'top',\nrightButtons: 'top',\ntopButtons: 'left',\nbottomButtons: 'left',\n},\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nleftButtonsOffset: 0,\nrightButtonsOffset: 0,\ntopButtonsOffset: 0,\nbottomButtonsOffset: 0,\n\nleftButton: 0,\nrightButton: 0,\ntopButton: 0,\nbottomButton: 0\n},\n\nclick: {\nmode: 'pointerup',\nclickInterval: 100\n}\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of grid table.
  • panel : Game object of center panel.
  • leftButtons, rightButtons, topButtons, bottomButtons : Array of button game object.
    • [] : Assign an empty array if user will add button later.
  • leftButtonsBackground, rightButtonsBackground, topButtonsBackground, bottomButtonsBackground : Game object of leftButtons' background, rightButtons' background, topButtons' background, bottomButtons' background, optional.
  • expand : Expand size of panel or buttons
    • expand.panel : Expand size of panel. Default value is false.
    • expand.leftButtons, expand.rightButtons : Expand height of leftButtons, rightButtons. Default value is false.
    • expand.topButtons, expand.bottomButtons : Expand width of topButtons, bottomButtons. Default value is false.
  • align : Alignment of buttons
    • align.leftButtons, align.rightButtons : 'top', 'bottom', or 'center'. Default value is 'top'.
    • align.topButtons, align.bottomButtons : 'left', 'right', or 'center'. Default value is 'left'.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds
    • space.leftButtonsOffset, space.rightButtonsOffset : Top offset of buttons group.
    • space.topButtonsOffset, space.bottomButtonsOffset : Left offset of buttons group.
    • space.leftButton, space.rightButton, space.topButton, space.bottomButton : Space between 2 button game objects.
  • click: Configuration of button clicking.
    • click.mode :
      • 'pointerdown', 'press', or 0 : Fire 'click' event when touch pressed.
      • 'pointerup', 'release', or 1 : Fire 'click' event when touch released after pressed.
    • click.clickInterval : Interval between 2 'click' events, in ms.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-tabs/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTabs extends RexPlugins.UI.Tabs {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var tabs = new MyTabs(scene, config);\n
"},{"location":"ui-tabs/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

tabs.layout();\n

See also - dirty

"},{"location":"ui-tabs/#other-properties","title":"Other properties","text":"

See grid sizer object, base-sizer object.

"},{"location":"ui-tabs/#events","title":"Events","text":"
  • Click button
    tabs.on('button.click', function(button, groupName, index, pointer) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
  • Pointer-over button
    tabs.on('button.over', function(button, groupName, index, pointer) {\n// ...\n}, scope);\n
    • button : Triggered button game object
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
  • Pointer-out button
    tabs.on('button.out', function(button, groupName, index, pointer) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : Index of triggered button game object.
    • pointer : Pointer object.
  • Enable button's input
    tabs.on('button.enable', function(button, groupName, index) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : Index of triggered button game object.
  • Disable button's input
    tabs.on('button.disalbe', function(button, groupName, index) {\n// ...\n}, scope);\n
    • button : Triggered button game object.
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : Index of triggered button game object.
"},{"location":"ui-tabs/#emit-button-click-event","title":"Emit button click event","text":"
  • Emit button click event in a given group
    tabs.emitButtonClick(groupName, index);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, or a button game object.
  • Emit left/right/top/bottom button click event
    tabs.emitLeftButtonClick(index);\ntabs.emitRightButtonClick(index);\ntabs.emitTopButtonClick(index);\ntabs.emitBottomButtonClick(index);\n
    • index : A number index, or a button game object.
"},{"location":"ui-tabs/#enabledisable-input-of-button","title":"Enable/disable input of button","text":"
  • Enable button input in a given group
    tabs.setButtonEnable(groupName, index);\n// tabs.setButtonEnable(groupName, index, true);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, or a button game object.
  • Enable left/right/top/bottom button
    tabs.setLeftButtonEnable(index);\ntabs.setRightButtonEnable(index);\ntabs.setTopButtonEnable(index);\ntabs.setBottomButtonEnable(index);\n
    • index : A number index, or a button game object.
  • Disable button input in a given group
    tabs.setButtonEnable(groupName, index, false);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, or a button game object.
  • Disable choice/action/toolbar/left-toolbar button's input
    tabs.setLeftButtonEnable(index, false);\ntabs.setRightButtonEnable(index, false);\ntabs.setTopButtonEnable(index, false);\ntabs.setBottomButtonEnable(index, false);\n
    • index : A number index, or a button game object.
  • Toggle button input in a given group
    tabs.toggleButtonEnable(groupName, index);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, or a button game object.
  • Toggle choice/action/toolbar/left-toolbar button's input
    tabs.toggleLeftButtonEnable(index);\ntabs.toggleRightButtonEnable(index);\ntabs.toggleTopButtonEnable(index);\ntabs.toggleBottomButtonEnable(index);\n
    • index : A number index, or a button game object.
  • Get button input enable in a given group
    var enabled = tabs.getButtonEnable(groupName, index);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, or a button game object.
  • Get choice/action/toolbar/left-toolbar button's input enable
    var enabled = tabs.getLeftButtonEnable(index);\nvar enabled = tabs.getRightButtonEnable(index);\nvar enabled = tabs.getTopButtonEnable(index);\nvar enabled = tabs.getBottomButtonEnable(index);\n
    • index : A number index, or a button game object.
"},{"location":"ui-tabs/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = tabs.getElement('background');\n
    • Panel game object
      var panel = tabs.getElement('panel');\n
    • Buttons
      • Button game object in a group
        var buttons = tabs.getButton(groupName, index)\n
        • groupName : 'left', 'right', 'top', or 'bottom'.
        • index : A number index.
      • Left button game object
        var buttons = tabs.getElement('leftButtons');\n
        or
        var button = tabs.getLeftButton(index);\n
        or
        var buttons = tabs.getElement('leftButtons[0]');\n
        • First button of left buttons.
      • Right button game object
        var buttons = tabs.getElement('rightButtons');\n
        or
        var button = tabs.getRightButton(index);\n
        or
        var buttons = tabs.getElement('rightButtons[0]');\n
        • First button of right buttons.
      • Top button game object
        var buttons = tabs.getElement('topButtons');\n
        or
        var button = tabs.getTopButton(index);\n
        or
        var buttons = tabs.getElement('topButtons[0]');\n
        • First button of top buttons.
      • Bottom button game object
        var buttons = tabs.getElement('bottomButtons');\n
        or
        var button = tabs.getBottomButton(index);\n
        or
        var buttons = tabs.getElement('bottomButtons[0]');\n
        • First button of bottom buttons.
  • Get by name
    var gameObject = tabs.getElement('#' + name);\n// var gameObject = tabs.getElement('#' + name, recursive);\n
    or
    var gameObject = tabs.getByName(name);\n// var gameObject = tabs.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-tabs/#add-button","title":"Add button","text":"
  • Add button in a group
    tabs.addButton(groupName, gameObject);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • gameObject : A game object, or an array of game objects.
  • Add left/right/top/bottom button
    tabs.addLeftButton(gameObject);\ntabs.addRightButton(gameObject);\ntabs.addTopButton(gameObject);\ntabs.addBottomButton(gameObject);\n
    • gameObject : A game object, or an array of game objects.
"},{"location":"ui-tabs/#remove-button","title":"Remove button","text":"
  • Remove a button from a group
    tabls.removeButton(groupName, index, destroyChild);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, a string name, or a button game object.
    • destroyChild : Set true to destroy button game object.
  • Remove left/right/top/bottom button
    tabs.removeLeftButton(index, destroyChild);\ntabs.removeRightButton(index, destroyChild);\ntabs.removeTopButton(index, destroyChild);\ntabs.removeBottomButton(index, destroyChild);\n
    • index : A number index, a string name, or a button game object.
    • destroyChild : Set true to destroy button game object.
  • Remove all buttons of a group
    tabls.clearButtons(groupName, destroyChild);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • destroyChild : Set true to destroy button game objects.
  • Remove all left/right/top/bottom buttons
    tabs.clearLeftButtons(destroyChild);\ntabs.clearRightButtons(destroyChild);\ntabs.clearTopButtons(destroyChild);\ntabs.clearBottomButtosn(destroyChild);\n
    • destroyChild : Set true to destroy button game objects.
"},{"location":"ui-tabs/#showhide-button","title":"Show/hide button","text":"

Hidden elements won't be counted when layouting. Call tabs.layout(), or topSizer.layout() after show/hide any button.

  • Show button in a group
    tabs.showButton(groupName, index);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, a string name, or a button game object.
  • Show left/right/top/bottom button
    tabs.showLeftButton(index);\ntabs.showRightButton(index);\ntabs.showTopButton(index);\ntabs.showBottomButton(index);\n
    • index : A number index, a string name, or a button game object.
  • Hide button in a group
    tabs.hideButton(groupName, index);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, a string name, or a button game object.
  • Hide left/right/top/bottom button.
    tabs.hideLeftButton(index);\ntabs.hideRightButton(index);\ntabs.hideTopButton(index);\ntabs.hideBottomButton(index);\n
    • index : A number index, a string name, or a button game object.
"},{"location":"ui-tabs/#for-each-button","title":"For each button","text":"
  • For each button in a group
    var enabled = tabs.forEachButton(groupName, index);\n
    • groupName : 'left', 'right', 'top', or 'bottom'.
    • index : A number index, or a button game object.
  • For each button in left/right/top/bottom group
    tabs.forEachLeftButton(callback, scope);\ntabs.forEachRightButton(callback, scope);\ntabs.forEachTopButton(callback, scope);\ntabs.forEachBottomButton(callback, scope);\n
    • callback :
      function(button, index, buttons) {\n// ...\n}\n
"},{"location":"ui-text-helper/","title":"Ui text helper","text":""},{"location":"ui-text-helper/#introduction","title":"Introduction","text":"

Some helper methods for Text object, bbcode text object, tag text object, Bitmap text object game objects

  • Author: Rex
  • Methods
"},{"location":"ui-text-helper/#live-demos","title":"Live demos","text":"
  • Wrap-expand-text
  • Wrap-expand-bitmaptext
  • Fontsize-expand-text
  • Resize Fontsize-expand-text
"},{"location":"ui-text-helper/#usage","title":"Usage","text":"
  • Wrap-expand-text
  • Fontsize-expand-text
"},{"location":"ui-text-helper/#wrap-expand-text","title":"Wrap expand text","text":"
sizer\n.add(\nthis.rexUI.wrapExpandText(this.add.text(0, 0, content)),\n{\n// proportion: 1,\n// expand: true\n}\n)\n
  • proportion: 1 or/and expand: true : Expand width of text
"},{"location":"ui-text-helper/#fontsize-expand-text","title":"Fontsize expand text","text":"
sizer\n.add(\nthis.rexUI.fontSizeExpandText(this.add.text(0, 0, content)),\n{\n// proportion: 1,\n// expand: true\n}\n)\n
  • proportion: 1 or/and expand: true : Expand width of text
"},{"location":"ui-textarea/","title":"Text area","text":""},{"location":"ui-textarea/#introduction","title":"Introduction","text":"

A container with a text, slider, and scroller.

  • Author: Rex
  • Game object
"},{"location":"ui-textarea/#live-demos","title":"Live demos","text":"
  • Text-area
  • Bitmap text
  • Hide unscrollable slider
  • Append text
  • Scroll to line
  • Modal dialog
  • Min height
"},{"location":"ui-textarea/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-textarea/#install-plugin","title":"Install plugin","text":""},{"location":"ui-textarea/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add text-area object
    var textArea = scene.rexUI.add.textArea(config);\n
"},{"location":"ui-textarea/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text-area object
    var textArea = scene.rexUI.add.textArea(config);\n
"},{"location":"ui-textarea/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { TextArea } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add text-area object
    var textArea = new TextArea(scene, config);\nscene.add.existing(textArea);\n
"},{"location":"ui-textarea/#add-text-area-object","title":"Add text-area object","text":"
var textArea = scene.rexUI.add.textArea({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\nbackground: backgroundGameObject,\n\ntext: textGameObject,\n// textWidth: undefined,\n// textHeight: undefined,\n// textMask: false,\n// alwaysScrollable: false,\n\nslider: {\n// background: sliderBackgroundGameObject,\ntrack: trackGameObject,\n/* \n        track: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\n\n// indicator: indicatorGameObject,\nthumb: thumbGameObject,\n/* \n        thumb: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\n// input: 'drag',\n// position: 'right',\n\n// hideUnscrollableSlider: false,\n// adaptThumbSize: false,\n// minThumbSize: undefined,\n\n// buttons: {\n//     top: topButtonGameObject, bottom: bottomButtonGameObject,\n//     left: leftButtonGameObject, right: rightButtonGameObject,\n//     step: 0.01,\n// }\n},\n\n// scroller: {\n//     threshold: 10,\n//     slidingDeceleration: 5000,\n//     backDeceleration: 2000,\n//     pointerOutRelease: true,\n//     rectBoundsInteractive: true,\n//     dragRate: 1,\n// },\n\nmouseWheelScroller: false,\n// mouseWheelScroller: {\n//     focus: true,\n//     speed: 0.1\n// },\n\nclampChildOY: false,\n\nheader: headerGameObject,\nfooter: footerGameObject,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\ntext: 0,\n// text: {\n//    top: 0,\n//    bottom: 0,\n//    left: 0,\n//    right: 0,\n//},\n\nslider: 0,\n// slider: {\n//     top: 0,\n//     bottom: 0,\n//     left: 0,\n//     right: 0,\n// },\n\nheader: 0,\nfooter: 0,\n},\n\nexpand: {\nheader: true,\nfooter: true,\n},\n\nalign: {\nheader: 'center',\nfooter: 'center',\n},\n\ncontent: '',\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of text area.
  • text : Text object, bbcode text object, tag text object, or bitmap text object
  • textWidth : Fixed width of text game object. Set undefined to ignore this feature.
  • textHeight : Fixed height of text game object. Set undefined to ignore this feature.
  • textMask :
    • false : Crop text game object. Default behavior if text game object has setCrop method.
    • true : Apply mask on text to crop text game object. Default behavior if text game object does not have setCrop method (ex. bitmaptext game object).
  • slider : Componments of slider, optional.
    • slider.background : Game object of slider background, optional.
    • slider.track : Game object of track.
    • slider.thumb : Game object of thumb.
    • slider.input :
      • 'pan', 'drag', or 0 : Control slider by panning/dragging thumb game object. Default setting.
      • 'click', or 1 : Control slider by touching track game object.
      • 'none', or -1 : Disable sider controlling.
    • slider.position : Position of this slider.
      • 0, 'right', 'bottom' : Slider at right/bottom side. Default value.
      • 1, 'left', 'top' : Slider at left/top side.
    • slider.hideUnscrollableSlider :
      • false : Slider is always visible no matter it is scrollable or not. Default behavior.
      • true : Set slider to invisible if it is unscrollable.
    • slider.adaptThumbSize :
      • false : Don't adjust height/width of thumb. Default behavior.
      • true : Adjust height/width of thumb according to ratio of visible child.
        • Minimum height/width of thumb = slider.minThumbSize. If content is larger then a page.
        • Maximum height/width of thumb = height/width of slider.track. If content is less then a page.
    • slider.minThumbSize : Minimum height/width of thumb used in slider.adaptThumbSize mode.
    • slider.buttons : Press button to scroll content in each tick.
      • slider.buttons.top, slider.buttons.bottom : Top and bottom buttons.
      • slider.buttons.left, slider.buttons.right : Left and right buttons
      • slider.buttons.step : Scrolling step in each tick. Default value is 0.01.
    • Set to false to skip creating slider.
  • scroller : Configuration of scroller behavior.
    • scroller.threshold : Minimal movement to scroll. Set 0 to scroll immediately.
    • scroller.slidingDeceleration : Deceleration of slow down when dragging released.
      • Set false to disable it.
    • scroller.backDeceleration : Deceleration of pull back when out of bounds.
      • Set false to disable it.
    • scroller.pointerOutRelease : Set to true to release input control when pointer out of gameObject.
    • scroller.rectBoundsInteractive :
      • false : Detect scrolling by game object's touch input.
      • true : Detect scrolling by rectangle bounds of game object. Default behavior.
    • scroller.dragRate : Rate of dragging distance/dragging speed. Default value is 1.
    • Set to false to skip creating scroller.
  • mouseWheelScroller : Configuration of mouse-wheel-scroller behavior.
    • mouseWheelScroller.focus :
      • false, or 0 : Without checking if cursor is over game object or not.
      • true, or 1 : Cursor is inside the rectangle bounds of game object. Default behavior.
      • 2 : Cursor is over game object.
    • mouseWheelScroller.speed : Scrolling speed, default value is 0.1.
    • Set to false to skip creating mouse-wheel-scroller. Default behavior.
  • clampChildOY : Set true to clamp scrolling.
  • alwaysScrollable :
    • false : Can't scroll if content is less then 1 page. Default behavior.
    • true : Can scroll in all cases
  • header : Game object of header, optional.
  • footer : Game object of footer, optional.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.text :
      • A number: Space between text object and slider object.
      • An object: Padding of text object.
        • space.text.top, space.text.bottom : Top, bottom padding space of text object.
        • space.text.right : Space between text object and slider object.
    • space.slider :
      • 0 : No space around slider.
      • space.slider.left, space.slider.right, space.slider.top, space.slider.bottom : Space around slider.
    • space.header : Space between header and text object.
    • space.footer : Space between footer and text object.
  • expand : Expand width or height of element
    • expand.header : Set true to expand width or height of header game object.
    • expand.footer : Set true to expand width or height of footer game object.
  • align : Align element
    • align.header
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • align.footer
  • content : Content of this text area.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-textarea/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTextArea extends RexPlugins.UI.TextArea {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var textArea = new MyTextArea(scene, config);\n
"},{"location":"ui-textarea/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

textArea.layout();\n

See also - dirty

"},{"location":"ui-textarea/#content","title":"Content","text":"
  • Set
    textArea.setText(text);\n
  • Append
    textArea.appendText(text);\n
  • Get
    var text = textArea.text;\n
"},{"location":"ui-textarea/#scroll-content","title":"Scroll content","text":"
  • Scroll down lines
    textArea.scrollLine(lineCount);\n
  • Set
    textArea.childOY = oy;\n// textArea.setChildOY(oy);\n
  • Set and clamp
    textArea.setChildOY(oy, true);\n
  • Add
    textArea.addChildOY(oy);\n
  • Add and clamp
    textArea.addChildOY(oy, true);\n
  • Get
    var childOY = textArea.childOY;\n
  • Top OY
    var topOY = textArea.topChildOY;\n
  • Bottom OY
    var bottomOY = textArea.bottomChildOY;\n
  • Is overflow (height of content is larger than display height)
    var isOverflow = textArea.isOverflow;\n
"},{"location":"ui-textarea/#scroll-by-percentage","title":"Scroll by percentage","text":"
  • Set
    textArea.t = t;  // t: 0~1\n// textArea.setT(t);  \n
  • Set and clamp
    textArea.setT(t, true);\n
  • Get
    var t = textArea.t;\n
"},{"location":"ui-textarea/#scroll-to-topbottom","title":"Scroll to top/bottom","text":"
  • Scroll to top
    textArea.scrollToTop();\n
    • Equal to textArea.t = 0;
  • Scroll to bottom
    textArea.scrollToBottom();\n
    • Equal to textArea.t = 1;
"},{"location":"ui-textarea/#scroll-to-line","title":"Scroll to line","text":"
  • Scroll to next line
    textArea.scrollToNextLine();\n
  • Scroll to next n line
    textArea.scrollToNextLine(n);\n
  • Scroll to line
    textArea.scrollToLine(lineIndex);\n
  • Get current line index
    var lineIndex = textArea.lineIndex;\n
"},{"location":"ui-textarea/#enabledisable-scrolling","title":"Enable/disable scrolling","text":"
  • Slider
    • Set enable state
      textArea.setSliderEnable(enabled);\n
      or
      textArea.sliderEnable = enabled;\n
    • Get enable state
      var enable = textArea.sliderEnable;\n
  • Scroller
    • Set enable state
      textArea.setScrollerEnable(enabled);\n
      or
      textArea.scrollerEnable = enabled;\n
    • Get enable state
      var enable = textArea.scrollerEnable;\n
  • Mouse-Wheel-Scroller
    • Set enable state
      textArea.setMouseWheelScrollerEnable(enabled);\n
      or
      textArea.mouseWheelScrollerEnable = enabled;\n
    • Get enable state
      var enable = textArea.mouseWheelScrollerEnable;\n
"},{"location":"ui-textarea/#event","title":"Event","text":"
  • Scroll
    textArea.on('scroll', function(textArea) {\n// ...\n})\n
  • Slider
    • Slider drag start
      textArea.getElement('slider').on('inputstart', function(panel) {\n// ...\n})\n
    • Slider drag end
      textArea.getElement('slider').on('inputend', function(panel) {\n// ...\n})\n
  • Scroller
    • Scroller drag start
      textArea.getElement('scroller').on('dragstart', function(panel) {\n// ...\n})\n
    • Scroller drag end
      textArea.getElement('scroller').on('dragend', function(panel) {\n// ...\n})\n
"},{"location":"ui-textarea/#lines-count","title":"Lines count","text":"
var linesCount = textArea.linesCount;\n
"},{"location":"ui-textarea/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-textarea/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = textArea.getElement('background');\n
    • Text game object
      var text = textArea.getElement('text');\n
    • Slider
      • Track
        var track = textArea.getElement('slider.track');\n
      • Thumb
        var thumb = textArea.getElement('slider.thumb');\n
    • Scroller
      var scroller = textArea.getElement('scroller');\n
  • Get by name
    var gameObject = textArea.getElement('#' + name);\n// var gameObject = textArea.getElement('#' + name, recursive);\n
    or
    var gameObject = textArea.getByName(name);\n// var gameObject = textArea.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-textareainput/","title":"Text area input","text":""},{"location":"ui-textareainput/#introduction","title":"Introduction","text":"

A container with a canvasInput, and slider.

  • Author: Rex
  • Game object
"},{"location":"ui-textareainput/#live-demos","title":"Live demos","text":"
  • Text-area
"},{"location":"ui-textareainput/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-textareainput/#install-plugin","title":"Install plugin","text":""},{"location":"ui-textareainput/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add text-area-input object
    var textAreaInput = scene.rexUI.add.textAreaInput(config);\n
"},{"location":"ui-textareainput/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text-area-input object
    var textAreaInput = scene.rexUI.add.textAreaInput(config);\n
"},{"location":"ui-textareainput/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { TextAreaInput } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add text-area-input object
    var textAreaInput = new TextAreaInput(scene, config);\nscene.add.existing(textAreaInput);\n
"},{"location":"ui-textareainput/#add-text-area-input-object","title":"Add text-area-input object","text":"
var textAreaInput = scene.rexUI.add.textAreaInput({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\n// Elements\nbackground: backgroundGameObject,\n\ntext: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null,\n\n// Style when focus\n// 'focus.color': ...\n// 'focus.color2': ...\n// 'focus.stroke': ...\n},\nfocusStyle: undefined,\n\ninnerBounds: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBY: undefined,\noffsetX: 0,\noffsetY: 0,\n\n// Style when cursor move on\n// 'cursor.color': ...\n// 'cursor.backgroundColor': ...\n// 'cursor.xxx': ...\n},\ncursorStyle: undefined,\n\nchildrenInteractive: false,\n\ntext: '',\n\nwrap: {\nlineHeight: undefined,\nuseDefaultLineHeight: true,\nmaxLines: 1,\nwrapWidth: undefined,\nletterSpacing: 0,\nhAlign: 0,\nvAlign: 'center',  // For single line text input\nwrapMode: 'char',  // For single line text input\n},\n\ntextArea: true,\n\n// Parameters of hidden-text-editor   \n// inputType: 'text',  // 'text'|'password'|'textarea'|...                \n\n// readOnly: false,\n// maxLength: undefined,\n// minLength: undefined,\n// selectAll: false,\n\n// enterClose: true,\n\n// Callbacks\n// onOpen: function (textObject, hiddenInputText) {\n// },\n\n// onClose: function (textObject, hiddenInputText) {\n// },\n\n// onUpdate: function (text, textObject, hiddenInputText) {\n//     return text;\n// },\n\n// onAddChar: function(child, index, canvasInput) {\n//    child.modifyStyle({...})\n// },\n\n// onCursorOut: function(child, cursorIndex, canvasInput) {\n//     child.modifyStyle({\n//         \n//     });\n// },\n\n// onCursorIn: function(child, cursorIndex, canvasInput) {\n//     child.modifyStyle({\n//         \n//     });\n// },\n\n// parseTextCallback: function(text) {\n//     return text;\n// }.        \n},\n// alwaysScrollable: false,\n\nslider: {\n// background: sliderBackgroundGameObject,\ntrack: trackGameObject,\n/* \n        track: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\n\n// indicator: indicatorGameObject,\nthumb: thumbGameObject,\n/* \n        thumb: { \n            width: 1, height: 1,\n            radius: 0, \n            color: undefined, alpha: 1,\n            strokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\n            shape: undefined\n        }\n        */\n\n// input: 'drag',\n// position: 'right',\n\n// hideUnscrollableSlider: false,\n// adaptThumbSize: false,\n// minThumbSize: undefined,\n\n// buttons: {\n//     top: topButtonGameObject, bottom: bottomButtonGameObject,\n//     left: leftButtonGameObject, right: rightButtonGameObject,\n//     step: 0.01,\n// }\n},\n\n// scroller: false,  // No scrollor support\n\nmouseWheelScroller: false,\n// mouseWheelScroller: {\n//     focus: true,\n//     speed: 0.1\n// },\n\nclampChildOY: false,\n\nheader: headerGameObject,\nfooter: footerGameObject,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\ntext: 0,\n// text: {\n//    top: 0,\n//    bottom: 0,\n//    left: 0,\n//    right: 0,\n//},\n\nslider: 0,\n// slider: {\n//     top: 0,\n//     bottom: 0,\n//     left: 0,\n//     right: 0,\n// },\n\nheader: 0,\nfooter: 0,\n},\n\nexpand: {\nheader: true,\nfooter: true,\n},\n\nalign: {\nheader: 'center',\nfooter: 'center',\n},\n\ncontent: '',\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • background : Game object of background, optional. This background game object will be resized to fit the size of text area.
  • text : Configuration of CanvasInput, or a CanvasInput game object.
  • slider : Componments of slider, optional.
    • slider.background : Game object of slider background, optional.
    • slider.track : Game object of track.
    • slider.thumb : Game object of thumb.
    • slider.input :
      • 'pan', 'drag', or 0 : Control slider by panning/dragging thumb game object. Default setting.
      • 'click', or 1 : Control slider by touching track game object.
      • 'none', or -1 : Disable sider controlling.
    • slider.position : Position of this slider.
      • 0, 'right', 'bottom' : Slider at right/bottom side. Default value.
      • 1, 'left', 'top' : Slider at left/top side.
    • slider.hideUnscrollableSlider :
      • false : Slider is always visible no matter it is scrollable or not. Default behavior.
      • true : Set slider to invisible if it is unscrollable.
    • slider.adaptThumbSize :
      • false : Don't adjust height/width of thumb. Default behavior.
      • true : Adjust height/width of thumb according to ratio of visible child.
        • Minimum height/width of thumb = slider.minThumbSize. If content is larger then a page.
        • Maximum height/width of thumb = height/width of slider.track. If content is less then a page.
    • slider.minThumbSize : Minimum height/width of thumb used in slider.adaptThumbSize mode.
    • slider.buttons : Press button to scroll content in each tick.
      • slider.buttons.top, slider.buttons.bottom : Top and bottom buttons.
      • slider.buttons.left, slider.buttons.right : Left and right buttons
      • slider.buttons.step : Scrolling step in each tick. Default value is 0.01.
    • Set to false to skip creating slider.
  • scroller : No scroller supported (false).
  • mouseWheelScroller : Configuration of mouse-wheel-scroller behavior.
    • mouseWheelScroller.focus :
      • true : Only scrolling when cursor is over textAreaInput. Default behavior.
      • false : Scrolling without checking cursor.
    • mouseWheelScroller.speed : Scrolling speed, default value is 0.1.
    • Set to false to skip creating mouse-wheel-scroller. Default behavior.
  • clampChildOY : Set true to clamp scrolling.
  • alwaysScrollable :
    • false : Can't scroll if content is less then 1 page. Default behavior.
    • true : Can scroll in all cases
  • header : Game object of header, optional.
  • footer : Game object of footer, optional.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.text :
      • A number: Space between text object and slider object.
      • An object: Padding of text object.
        • space.text.top, space.text.bottom : Top, bottom padding space of text object.
        • space.text.right : Space between text object and slider object.
    • space.slider :
      • 0 : No space around slider.
      • space.slider.left, space.slider.right, space.slider.top, space.slider.bottom : Space around slider.
    • space.header : Space between header and text object.
    • space.footer : Space between footer and text object.
  • expand : Expand width or height of element
    • expand.header : Set true to expand width or height of header game object.
    • expand.footer : Set true to expand width or height of footer game object.
  • align : Align element
    • align.header
      • 'center', or Phaser.Display.Align.CENTER : Align game object at center. Default value.
      • 'left', or Phaser.Display.Align.LEFT_CENTER : Align game object at left-center.
      • 'right', or Phaser.Display.Align.RIGHT_CENTER : Align game object at right-center.
    • align.footer
  • content : Content of this text area.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-textareainput/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTextAreaInput extends RexPlugins.UI.TextAreaInput {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var textAreaInput = new MyTextAreaInput(scene, config);\n
"},{"location":"ui-textareainput/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

textAreaInput.layout();\n

See also - dirty

"},{"location":"ui-textareainput/#content","title":"Content","text":"
  • Set
    textAreaInput.setText(text);\n
  • Append
    textAreaInput.appendText(text);\n
  • Get
    var text = textAreaInput.text;\n
"},{"location":"ui-textareainput/#scroll-content","title":"Scroll content","text":"
  • Scroll down lines
    textAreaInput.scrollLine(lineCount);\n
  • Set
    textAreaInput.childOY = oy;\n// textAreaInput.setChildOY(oy);\n
  • Set and clamp
    textAreaInput.setChildOY(oy, true);\n
  • Add
    textAreaInput.addChildOY(oy);\n
  • Add and clamp
    textAreaInput.addChildOY(oy, true);\n
  • Get
    var childOY = textAreaInput.childOY;\n
  • Top OY
    var topOY = textAreaInput.topChildOY;\n
  • Bottom OY
    var bottomOY = textAreaInput.bottomChildOY;\n
  • Is overflow (height of content is larger than display height)
    var isOverflow = textAreaInput.isOverflow;\n
"},{"location":"ui-textareainput/#scroll-by-percentage","title":"Scroll by percentage","text":"
  • Set
    textAreaInput.t = t;  // t: 0~1\n// textAreaInput.setT(t);  \n
  • Set and clamp
    textAreaInput.setT(t, true);\n
  • Get
    var t = textAreaInput.t;\n
"},{"location":"ui-textareainput/#scroll-to-topbottom","title":"Scroll to top/bottom","text":"
  • Scroll to top
    textAreaInput.scrollToTop();\n
    • Equal to textAreaInput.t = 0;
  • Scroll to bottom
    textAreaInput.scrollToBottom();\n
    • Equal to textAreaInput.t = 1;
"},{"location":"ui-textareainput/#scroll-to-line","title":"Scroll to line","text":"
  • Scroll to next line
    textAreaInput.scrollToNextLine();\n
  • Scroll to next n line
    textAreaInput.scrollToNextLine(n);\n
  • Scroll to line
    textAreaInput.scrollToLine(lineIndex);\n
  • Get current line index
    var lineIndex = textAreaInput.lineIndex;\n
"},{"location":"ui-textareainput/#enabledisable-scrolling","title":"Enable/disable scrolling","text":"
  • Slider
    • Set enable state
      textAreaInput.setSliderEnable(enabled);\n
      or
      textAreaInput.sliderEnable = enabled;\n
    • Get enable state
      var enable = textAreaInput.sliderEnable;\n
  • Scroller
    • Set enable state
      textAreaInput.setScrollerEnable(enabled);\n
      or
      textAreaInput.scrollerEnable = enabled;\n
    • Get enable state
      var enable = textAreaInput.scrollerEnable;\n
"},{"location":"ui-textareainput/#read-only","title":"Read only","text":"
  • Enable read only
    textAreaInput.setReadOnly();\n// textAreaInput.setReadOnly(true);\n
    or
    textAreaInput.readOnly = true;\n
  • Disable read only
    textAreaInput.setReadOnly(false);\n
    or
    textAreaInput.readOnly = false;\n
  • Get read only
    var readOnlyEanble = txt.readOnly;\n
"},{"location":"ui-textareainput/#event","title":"Event","text":"
  • On close text-editor
    textAreaInput.on('close', function(text, textAreaInput) {\n\n})\n
  • Text changed
    textAreaInput.on('textchange', function(text, textAreaInput){\n// ...\n})\n
  • Scroll
    textAreaInput.on('scroll', function(textAreaInput) {\n// ...\n})\n
  • Slider
    • Slider drag start
      textAreaInput.getElement('slider').on('inputstart', function(panel) {\n// ...\n})\n
    • Slider drag end
      textAreaInput.getElement('slider').on('inputend', function(panel) {\n// ...\n})\n
  • Scroller
    • Scroller drag start
      textAreaInput.getElement('scroller').on('dragstart', function(panel) {\n// ...\n})\n
    • Scroller drag end
      textAreaInput.getElement('scroller').on('dragend', function(panel) {\n// ...\n})\n
"},{"location":"ui-textareainput/#lines-count","title":"Lines count","text":"
var linesCount = textAreaInput.linesCount;\n
"},{"location":"ui-textareainput/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-textareainput/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = textAreaInput.getElement('background');\n
    • Text game object
      var text = textAreaInput.getElement('text');\n
    • Slider
      • Track
        var track = textAreaInput.getElement('slider.track');\n
      • Thumb
        var thumb = textAreaInput.getElement('slider.thumb');\n
  • Get by name
    var gameObject = textAreaInput.getElement('#' + name);\n// var gameObject = textAreaInput.getElement('#' + name, recursive);\n
    or
    var gameObject = textAreaInput.getByName(name);\n// var gameObject = textAreaInput.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-textbox/","title":"Text box","text":""},{"location":"ui-textbox/#introduction","title":"Introduction","text":"

A container with an icon, (typing and paging) text, and background.

  • Author: Rex
  • Game object
"},{"location":"ui-textbox/#live-demos","title":"Live demos","text":"
  • Text box
  • Inner sizer
  • Speech bubble background
  • Bitmap text
  • Page break
  • Show last page
"},{"location":"ui-textbox/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-textbox/#install-plugin","title":"Install plugin","text":""},{"location":"ui-textbox/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add text-box object
    var textBox = scene.rexUI.add.textBox(config);\n
"},{"location":"ui-textbox/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add text-box object
    var textBox = scene.rexUI.add.textBox(config);\n
"},{"location":"ui-textbox/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { TextBox } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add text-box object
    var textBox = new TextBox(scene, config);\nscene.add.existing(textBox);\n
"},{"location":"ui-textbox/#add-textbox-object","title":"Add textbox object","text":"
var textBox = scene.rexUI.add.textBox({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nlayoutMode: 0,\n\nrtl: false,\n\ntypingMode: 0,\n\nbackground: backgroundGameObject,\n\ninnerBackground: backgroundGameObject,\n\ntitle: titleGameObject,\n\nseparator: separatorGameObject,\n\nicon: iconGameObject,\niconMask: false,\n\ntext: textGameObject,\nexpandTextWidth: false,\nexpandTextHeight: false,\n\naction: actionGameObject,\nactionMask: false,\n\nalign: {\ntitle: 'left',\ntext: 'left',\nicon: 'center',\naction: 'center'\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ninnerLeft: 0, innerRight: 0, innerTop: 0, innerBottom: 0,\n\ntitle: 0, titleLeft: 0, titleRight: 0,\nicon: 0, iconTop: 0, iconBottom: 0,\ntext: 0, textLeft: 0, textRight: 0,\nactionTop: 0, actionBottom: 0,\n},\n\n// page: { \n//    maxLines: undefined,\n//    pageBreak: '\\f\\n',\n// },\n// typing: { \n//    wrap: false,\n//    speed: 333,    \n// },\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • layoutMode :
    • 0 : title, separator, and text will be layout vertically, then layout with icon, action horizontally.
    • 1 : icon, text, and action will be layout horizontally, then layout with title, separator vertically. Default behavior.
  • rtl :
    • false : Layout children (icon, text, action) from left to right. Default behavior.
    • true : Layout children (icon, text, action) from right to left.
  • typingMode :
    • 0, 'page' : Typing content page by page. Default behavior.
    • 1, 'line' : Typing content line by line until finished.
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • innerBackground : Game object of background inside innerSizer, optional.
    • In mode 0, innerSizer contains title, separator, and text.
    • In mode 1, innerSizer contains icon, text, and action.
  • title : Game object of title, optional.
  • separator : Game object of separator, optional.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
  • text : Text object, bbcode text object, tag text object, or bitmap text object, required.
    • Max lines and wrapped width
      • Built-in text object : maxLines and wrap width (wordWrap.width).
      • BBcode text object : maxLines and wrap width (wrap.width).
      • Tag text object : maxLines and wrap width (wrap.width).
      • Bitmap text object : Set maxLines at page.maxLines in configuration of page behavior, and wrap width at text.setMaxWidth(width).
    • Fixed width and fixed height
      • Built-in text object : fixedWidth and fixedHeight, set to 0 to disable this feature.
      • BBcode text object : fixedWidth and fixedHeight, set to 0 to disable this feature.
      • Tag text object : fixedWidth and fixedHeight, set to 0 to disable this feature.
  • expandTextWidth :
    • true : Expand fixedWidth and wrapWidth when layout, to change width of text game object to fit this textbox.
  • expandTextHeight :
    • true : Expand fixedHeight when layout, to change height of text game object to fit this textbox.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
  • align : Alignment of title, text, icon, action game objects.
    • align.title, align.text : 'left', 'center', or 'right'. Default vale is 'left'.
    • align.icon, align.action : 'top', 'center', or 'bottom'. Default vale is 'center'.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.innerLeft, space.innerRight, space.innerTop, space.innerBottom : Space parameter of inner sizer.
    • space.title : Space between title game object and separator game object.
    • space.titleLeft, space.titleRight : Space at left or right side of title game object.
    • space.icon : Space between icon game object and text game object.
    • space.iconTop, space.iconBottom : Space around icon game object.
    • space.text : Space between text game object and action icon game object.
    • space.textLeft, space.textRight : Space at left or right side of text game object.
    • space.actionTop, space.actionBottom : Space around action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • page : Configuration of page behavior
    • page.maxLines : Max lines of a page. If not given in text game object.
    • page.pageBreak : Symbol of page-break. Default value is '\\f\\n'.
  • typing : Configuration of type behavior
    • typing.wrap :
      • false : Don't insert \\n, default behavior.
      • true : Insert \\n to wrap content according to style of text, to prevent typing jittering.
    • typing.speed : Typing speed in ms, default value is 333.
"},{"location":"ui-textbox/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTextBox extends RexPlugins.UI.TextBox {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var textBox = new MyTextBox(scene, config);\n
"},{"location":"ui-textbox/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

textBox.layout();\n

See also - dirty

"},{"location":"ui-textbox/#typing","title":"Typing","text":"
  • Start typing
    textBox.start(content, typingSpeed);\n
    • content : Content string.
    • speed : Typing speed in ms.
      • undefined : Use previous typing speed.
  • Append and continue typing
    textBox.more(content, typingSpeed);\n
    • content : Content string.
    • speed : Typing speed in ms.
      • undefined : Use previous typing speed.
  • Stop typing
    textBox.stop();\n
    • Will fire 'stop' event.
  • Stop typing and show all text
    textBox.stop(true);\n
    • Will fire 'stop', 'type', 'pageend' event.
  • Stop typing and show all text at last page
    textBox.showLastPage();\n
    • Will fire 'type', 'pageend', 'complete' events.
  • Pause typing
    textBox.pause();\n
    • Will fire 'pause' event.
  • Resume typing
    textBox.resume();\n
    • Will fire 'resume' event.
  • Is typing
    var isTyping = textBox.isTyping;\n
"},{"location":"ui-textbox/#typing-speed","title":"Typing speed","text":"
  • Change typing speed
    textBox.setTypingSpeed(speed);\n
    • speed : Typing speed in ms.
  • Get typing speed
    var speed = textBox.typingSpeed;\n
"},{"location":"ui-textbox/#page","title":"Page","text":"
  • Type next page
    textBox.typeNextPage();\n
  • Is page end, after typing complete
    var isPageEnd = textBox.isPageEnd;\n
  • Is last page
    var isLastPage = textBox.isLastPage;\n
  • Is first page
    var isFirstPage = textBox.isFirstPage;\n
  • Current page index
    var pageIndex = textBox.pageIndex;\n
  • Number of pages
    var pageIndex = textBox.pageCount;\n
"},{"location":"ui-textbox/#icon-texture","title":"Icon texture","text":"
  • Set texture
    textBox.setTexture(key);\n// label.setTexture(key, frame);\n
  • Get texture key, frame name
    var textureKey = textBox.texture.key;\nvar frameName = textBox.frame.name;\n
"},{"location":"ui-textbox/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = textBox.getElement('background');\n
    • InnerSizer
      var innerSizer = textBox.getElement('innerSizer');\n
      • In mode 0, innerSizer contains title, separator, and text.
      • In mode 1, innerSizer contains icon, text, and action.
    • Background game object inside innerSizer
      var innerBackground = textBox.getElement('innerBackground');\n
    • Title game object
      var textObject = textBox.getElement('title');\n
    • Separator game object
      var textObject = textBox.getElement('separator');\n
    • Icon game object
      var icon = textBox.getElement('icon');\n
    • Text game object
      var textObject = textBox.getElement('text');\n
    • Action icon game object
      var action = textBox.getElement('action');\n
  • Get by name
    var gameObject = textBox.getElement('#' + name);\n// var gameObject = textBox.getElement('#' + name, recursive);\n
    or
    var gameObject = textBox.getByName(name);\n// var gameObject = textBox.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-textbox/#events","title":"Events","text":"
  • On typing start.
    textBox.on('start', function() {\n// ...\n}, scope);\n
  • On changing content of text game object, will also re-layout textbox :
    textBox.on('type', function() {\n// ...\n}, scope);\n
  • On typing a character :
    textBox.on('typechar', function(char) {\n// ...\n}, scope);\n
  • On Typing the last character of current page.
    textBox.on('pageend', function() {\nif (textBox.isLastPage) {\n// ...            \n}\n}, scope);\n
  • On typing all pages complete, equal to 'pageend' event with textBox.isLastPage.
    textBox.on('complete', function() {\n// ...\n}, scope);\n
  • On typing paused by textBox.pause().
    textBox.on('pause', function() {\n// ...\n}, scope);\n
  • On typing resume by textBox.resume().
    textBox.on('resume', function() {\n// ...\n}, scope);\n
  • On typing stop by textBox.stop().
    textBox.on('stop', function() {\n// ...\n}, scope);\n
"},{"location":"ui-textbox/#other-properties","title":"Other properties","text":"

See title label, sizer object, base sizer object, container-lite.

"},{"location":"ui-titlelabel/","title":"Title label","text":""},{"location":"ui-titlelabel/#introduction","title":"Introduction","text":"

A container with title, text in two rows, and an icon, background.

  • Author: Rex
  • Game object
"},{"location":"ui-titlelabel/#live-demos","title":"Live demos","text":"
  • Title-label
  • Layout modes
"},{"location":"ui-titlelabel/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-titlelabel/#install-plugin","title":"Install plugin","text":""},{"location":"ui-titlelabel/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add label object
    var label = scene.rexUI.add.titleLabel(config);\n
"},{"location":"ui-titlelabel/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add label object
    var label = scene.rexUI.add.titleLabel(config);\n
"},{"location":"ui-titlelabel/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { TitleLabel } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add label object
    var label = new TitleLabel(scene, config);\nscene.add.existing(label);\n
"},{"location":"ui-titlelabel/#add-label-object","title":"Add label object","text":"
var label = scene.rexUI.add.titleLabel({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\nlayoutMode: 0,\n\n// rtl: false,\n\nbackground: backgroundGameObject,\n\ninnerBackground: backgroundGameObject,\n\ntitle: titleGameObject,\n// wrapTitle: false,\n// adjustTitleFontSize: false,\n// expandTitleWidth: false,\n// expandTitleHeight: false,\n\nseparator: separatorGameObject,\n\nicon: iconGameObject,\niconMask: false,\n\ntext: textGameObject,\n// wrapText: false,\n// adjustTextFontSize: false,\n// expandTextWidth: false,\n// expandTextHeight: false,\n\naction: actionGameObject,\nactionMask: false,\n\nalign: {\ntitle: 'left',\ntext: 'left',\nicon: 'center',\naction: 'center'\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ninnerLeft: 0, innerRight: 0, innerTop: 0, innerBottom: 0,\n\ntitle: 0, titleLeft: 0, titleRight: 0,\nicon: 0, iconTop: 0, iconBottom: 0,\ntext: 0, textLeft: 0, textRight: 0,\nseparator: 0, separatorLeft: 0, separatorRight: 0,\nactionTop: 0, actionBottom: 0,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • layoutMode :
    • 0 : title, separator, and text will be layout vertically, then layout with icon, action horizontally.
    • 1 : icon, text, and action will be layout horizontally, then layout with title, separator vertically.
  • rtl :
    • false : Layout children (icon, text, action) from left to right. Default behavior.
    • true : Layout children (icon, text, action) from right to left.
  • background : Game object of background, optional. This background game object will be resized to fit the size of label.
  • innerBackground : Game object of background inside innerSizer, optional.
    • In mode 0, innerSizer contains title, separator, and text.
    • In mode 1, innerSizer contains icon, text, and action.
  • title : Game object of title, optional.
  • wrapTitle : Enable WrapExpandText feature.
    • false, 0 : No WrapExpandText feature. Default behavior.
    • true, 1, 'word' : Word WrapExpandText.
    • 2, 'char' : Character WrapExpandText.
  • adjustTitleFontSize : Enable FontSizeExpandText feature.
    • false : No FontSizeExpandText feature. Default behavior.
    • true : Enable FontSizeExpandText feature. Can't work with wrapTitle: true.
      • Text-width and text-height will be expanding.
      • Use BBCodeText (scene.rexUI.add.BBCodeText) with {valign: 'center'} style.
  • expandTitleWidth :
    • false : Keep width of title to original size. Default behavior.
    • true : Expand width of title object. Will set display width by default.
      • Must set to true if using scene.rexUI.wrapExpandText method with any text game object.
      • Can't work with squareFitIcon: true.
  • expandTitleHeight : Set true to expand height of title object.
  • separator : Game object of separator, optional.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • text : Game object of text.
  • wrapText : Enable WrapExpandText feature.
    • false, 0 : No WrapExpandText feature. Default behavior.
    • true, 1, 'word' : Word WrapExpandText.
    • 2, 'char' : Character WrapExpandText.
  • adjustTextFontSize : Enable FontSizeExpandText feature.
    • false : No FontSizeExpandText feature. Default behavior.
    • true : Enable FontSizeExpandText feature. Can't work with wrapText: true.
      • Text-width and text-height will be expanding.
      • Use BBCodeText (scene.rexUI.add.BBCodeText) with {valign: 'center'} style.- expandTextWidth :
    • false : Keep width of text to original size. Default behavior.
    • true : Expand width of text object. Will set display width by default.
      • Must set to true if using scene.rexUI.wrapExpandText method with any text game object.
      • Can't work with squareFitIcon: true.
  • expandTextHeight : Set true to expand height of text object.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
    • Phaser 3 engine does not support nested mask, uses circle mask image instead.
  • align : Alignment of title, text, icon, action game objects.
    • align.title, align.text : 'left', 'center', or 'right'. Default vale is 'left'.
    • align.icon, align.action : 'top', 'center', or 'bottom'. Default vale is 'center'.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.innerLeft, space.innerRight, space.innerTop, space.innerBottom : Space parameter of inner sizer.
    • space.title : Space between title game object and separator game object.
    • space.titleLeft, space.titleRight : Space at left or right side of title game object.
    • space.icon : Space between icon game object and text game object.
    • space.iconTop, space.iconBottom : Space around icon game object.
    • space.text : Space between text game object and action icon game object.
    • space.textLeft, space.textRight : Space at left or right side of text game object.
    • space.actionTop, space.actionBottom : Space around action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-titlelabel/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTitleLabel extends RexPlugins.UI.TitleLabel {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var label = new MyTitleLabel(scene, config);\n
"},{"location":"ui-titlelabel/#layout-modes","title":"Layout modes","text":""},{"location":"ui-titlelabel/#mode-0","title":"Mode 0","text":"

title, separator, and text will be layout vertically inside innerSizer, then layout with icon, action horizontally.

Icon Title Action Separator Text"},{"location":"ui-titlelabel/#mode-1","title":"Mode 1","text":"

icon, text, and action will be layout horizontally inside innerSizer, then layout with title, separator vertically.

Title Separator Icon Text Action"},{"location":"ui-titlelabel/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

label.layout();\n

See also - dirty

"},{"location":"ui-titlelabel/#get-element","title":"Get element","text":"
  • Get element
    • Background game object
      var background = label.getElement('background');\n
    • InnerSizer
      var innerSizer = label.getElement('innerSizer');\n
      • In mode 0, innerSizer contains title, separator, and text.
      • In mode 1, innerSizer contains icon, text, and action.
    • Background game object inside innerSizer
      var innerBackground = label.getElement('innerBackground');\n
    • Title game object
      var textObject = label.getElement('title');\n
    • Separator game object
      var textObject = label.getElement('separator');\n
    • Icon game object
      var icon = label.getElement('icon');\n
    • Text game object
      var textObject = label.getElement('text');\n
    • Action icon game object
      var action = label.getElement('action');\n
  • Get by name
    var gameObject = label.getElement('#' + name);\n// var gameObject = label.getElement('#' + name, recursive);\n
    or
    var gameObject = label.getByName(name);\n// var gameObject = label.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-titlelabel/#title","title":"Title","text":"
  • Get title string
    var s = label.title;\n
  • Set title string
    label.setTitle(s);\n
    or
    label.title = s;\n
"},{"location":"ui-titlelabel/#text","title":"Text","text":"
  • Get text string
    var s = label.text;\n
  • Set text string
    label.setText(s);\n
    or
    label.text = s;\n
"},{"location":"ui-titlelabel/#icon-texture","title":"Icon texture","text":"
  • Set texture
    label.setTexture(key);\n// label.setTexture(key, frame);\n
  • Set texture via texture object
    label.setTexture(texture);\n// label.setTexture(texture, frame);\n
  • Get texture, frame.
    var texture = label.texture;\nvar frame = label.frame;\n
  • Get texture key, frame name.
    var textureKey = label.texture.key;\nvar frameName = label.frame.name;\n
"},{"location":"ui-titlelabel/#reset-display-content","title":"Reset display content","text":"
label.resetDisplayContent({\ntitle: '',\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n})\n

or

label.resetDisplayContent(text);\n
  • title : Set title's text string.
  • text : Set text string.
  • icon, iconFrame
    • A string : Set texture of icon game object.
    • undefined, or null : Hide icon game object.
    • true : Show icon game object without change its texture.
  • iconSize : Set display size of icon game object.
  • action, actionFrame
    • A string : Set texture of icon game object.
    • undefined, or null : Hide action game object.
    • true : Show action game object without change its texture.
  • actionSize : Set display size of action game object.

Run label.layout() after this method, to layout children again.

"},{"location":"ui-titlelabel/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-toast/","title":"Toast","text":""},{"location":"ui-toast/#introduction","title":"Introduction","text":"

Show text message for a short while.

  • Author: Rex
  • Game object
"},{"location":"ui-toast/#live-demos","title":"Live demos","text":"
  • Toast
  • Depth
    • Set depth
    • Bring to top
    • Add to layer
"},{"location":"ui-toast/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-toast/#install-plugin","title":"Install plugin","text":""},{"location":"ui-toast/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add toast object
    var toast = scene.rexUI.add.toast(config);\n
"},{"location":"ui-toast/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add toast object
    var toast = scene.rexUI.add.toast(config);\n
"},{"location":"ui-toast/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Toast } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add toast object
    var toast = new Toast(scene, config);\nscene.add.existing(toast);\n
"},{"location":"ui-toast/#add-toast-object","title":"Add toast object","text":"
var toast = scene.rexUI.add.toast({\nx: 0,\ny: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n\nbackground: backgroundGameObject,\nicon: iconGameObject,\niconMask: false,\ntext: textGameObject,\naction: actionGameObject,\nactionMask: false,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nicon: 0,\ntext: 0,\n},\n\nduration: {\nin: 200,\nhold: 1200,\nout: 200,\n},\n\n// transitIn: 0,\n// transitOut: 0,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • background : Game object of background, optional. This background game object will be resized to fit the size of toast.
  • icon : Game object of icon, optional.
  • iconMask : Set true to add a circle mask on icon game object.
  • text : Game object of text.
  • action : Game object of action icon, optional.
  • actionMask : Set true to add a circle mask on action icon game object.
  • space : Pads spaces
    • space.left, space.right, space.top, space.bottom : Space of bounds
    • space.icon : Space between icon game object and text game object.
    • space.text : Space between text game object and action icon game object.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • duration : Duration of displaying message
    • duration.in : Duration of transit-in stage.
    • duration.hold : Duration of hold stage.
    • duration.out : Duration of transit-out stage.
  • transitIn : Transit-in action.
    • 0, or 'popUp' : Pop-up.
    • 1, or 'fadeIn' : Fade-in.
    • A callback : Custom transit-in function
      function(toast, duration) {\n// ...\n}\n
    • false, null : No transitIn.
  • transitOut : Transit-out action.
    • 0, or 'scaleDown' : Scale-down.
    • 1, or 'fadeOut' : Fade-out.
    • A callback : Custom transit-out function
      function(toast, duration) {\n// ...\n}\n
    • false, null : No transitOut.

Toast object will be invisible at beginning.

"},{"location":"ui-toast/#custom-class","title":"Custom class","text":"
  • Define class
    class MyToast extends RexPlugins.UI.Toast {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var toast = new MyToast(scene, config);\n
"},{"location":"ui-toast/#show-message","title":"Show message","text":"
toast.showMessage(message);\n
  • message : A string, or a callback.
    • A string. Apply this content to text game object.
    • Callback. Invoke this callback to configurate toast object.
      function(toast) {\n// var icon = toast.getElement('icon');\n// var text = toast.getElement('text');\n// var action = toast.getElement('action');\n}\n

Toast displays message follows these steps : transit-in, hold, transit-out. New message will be pending until toast is back to idle.

"},{"location":"ui-toast/#clear-messages","title":"Clear messages","text":"
toast.removeAllMessages();\n
"},{"location":"ui-toast/#is-showing-message","title":"Is showing message","text":"
var isShowing = toast.isShowingMessage;\n
"},{"location":"ui-toast/#display-time","title":"Display time","text":"
  • Transit-in time (duration.in)
    • Get
      var time = toast.transitInTime;\n
    • Set
      toast.setTransitInTime(time);\n
  • Display time (duration.hold)
    • Get
      var time = toast.displayTime;\n
    • Set
      toast.setDisplayTime(time);\n
  • Transit-out time (duration.out)
    • Get
      var time = toast.transitOutTime;\n
    • Set
      toast.setTransitOutTime(time);\n
"},{"location":"ui-toast/#transit-action","title":"Transit action","text":"
  • Set transit-in action
    toast.setTransitInCallback(callback);\n
    • callback : Transit-in action
      • 0, or 'popUp' : Pop-up.
      • 1, or 'fadeIn' : Fade-in.
      • A callback : Custom transit-in function
        function(toast, duration) {\n// ...\n}\n
  • Set transit-out action
    toast.setTransitOutCallback(callback);\n
    • callback : Transit-out action
      • 0, or 'scaleDown' : Scale-down.
      • 1, or 'fadeOut' : Fade-out.
      • A callback : Custom transit-out function
        function(toast, duration) {\n// ...\n}\n
"},{"location":"ui-toast/#event","title":"Event","text":"
  • Transit-in
    toast.on('transitin', function(toast, transitInTime) {\n// ...\n})\n
  • Transit-out
    toast.on('transitout', function(toast, transitOutTime) {\n// ...\n})\n
"},{"location":"ui-toast/#other-properties","title":"Other properties","text":"

See label object, sizer object, base sizer object, container-lite.

"},{"location":"ui-toastqueue/","title":"Toast queue","text":""},{"location":"ui-toastqueue/#introduction","title":"Introduction","text":"

Queue messages for a short while.

  • Author: Rex
  • Game object
"},{"location":"ui-toastqueue/#live-demos","title":"Live demos","text":"
  • Toast queue
"},{"location":"ui-toastqueue/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-toastqueue/#install-plugin","title":"Install plugin","text":""},{"location":"ui-toastqueue/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add toast-queue object
    var toastQueue = scene.rexUI.add.toastQueue(config);\n
"},{"location":"ui-toastqueue/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add toast-queue object
    var toastQueue = scene.rexUI.add.toastQueue(config);\n
"},{"location":"ui-toastqueue/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { ToastQueue } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add toast-queue object
    var toastQueue = new ToastQueue(scene, config);\nscene.add.existing(toastQueue);\n
"},{"location":"ui-toastqueue/#add-toast-queue-object","title":"Add toast-queue object","text":"
var toastQueue = scene.rexUI.add.toastQueue({\nx: 0,\ny: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 1,\n\nspace: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n\nitem: 0,\n},\n\ncreateMessageLabelCallback(scene, message, toastQueue) {\n// return gameObject;\n},\n\nqueueDirection: 1, // 'bottom-to-top', or 'top-to-bottom'\n\nduration: {\nin: 200,\nhold: 2000,\nout: 200,\n},\n\n// transitIn: undefined,\n// transitOut: undefined,\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between 2 children game objects.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
  • createMessageLabelCallback : Callback for creating message label game object
    function(scene, message, toastQueue) {\n// \nreturn gameObject;\n}\n
    • message : message parameter passing from showMessage method.
    • toastQueue : This toast-queue game object.
  • queueDirection : Direction of message queue
    • 1, or 'bottom-to-top' : Message queue from bottom to top. Default value.
    • 0, or 'top-to-bottom' : Message queue from top to bottom.
  • duration : Duration of displaying message
    • duration.in : Duration of transit-in stage.
    • duration.hold : Duration of hold stage.
    • duration.out : Duration of transit-out stage.
  • transitIn : Transit-in action.
    • undefined (not gived) : Pop up message label.
    • A callback : Custom transit-in function
      function(messageLabel, duration, toastQueue) {\n// ...\n}\n
    • false, null : No transitOut.
  • transitOut : Transit-out action.
    • undefined (not gived) : Fade out message label.
    • A callback : Custom transit-out function
      function(messageLabel, duration, toastQueue) {\n// ...\n}\n
    • false, null : No transitOut.

Message Label will be destroyed when

  • Clicking, or
  • Timeout
"},{"location":"ui-toastqueue/#custom-class","title":"Custom class","text":"
  • Define class
    class MyToastQueue extends RexPlugins.UI.ToastQueue {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var toastQueue = new MyToastQueue(scene, config);\n
"},{"location":"ui-toastqueue/#show-message","title":"Show message","text":"
toastQueue.showMessage(message);\n
  • message : A string, or an object. Will pass to createMessageLabelCallback callback.
"},{"location":"ui-toastqueue/#clear-messages","title":"Clear messages","text":"
toastQueuetoast.removeAllMessages();\n

Invoke transition-out of all message labels.

"},{"location":"ui-toastqueue/#display-time","title":"Display time","text":"
  • Transit-in time (duration.in)
    • Get
      var time = toastQueue.transitInTime;\n
    • Set
      toastQueue.setTransitInTime(time);\n
  • Display time (duration.hold)
    • Get
      var time = toastQueue.displayTime;\n
    • Set
      toastQueue.setDisplayTime(time);\n
  • Transit-out time (duration.out)
    • Get
      var time = toastQueue.transitOutTime;\n
    • Set
      toastQueue.setTransitOutTime(time);\n
"},{"location":"ui-toastqueue/#transit-action","title":"Transit action","text":"
  • Set transit-in action
    toastQueue.setTransitInCallback(callback);\n
    • callback : Transit-in action
      function(messageLabel, duration, toastQueue) {\n// ...\n}\n
  • Set transit-out action
    toastQueue.setTransitOutCallback(callback);\n
    • callback : Transit-out action
      function(messageLabel, duration, toastQueue) {\n// ...\n}\n
"},{"location":"ui-toastqueue/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"ui-trees/","title":"Trees","text":""},{"location":"ui-trees/#introduction","title":"Introduction","text":"

A container with trees and leaf-nodes.

  • Author: Rex
  • Game object
"},{"location":"ui-trees/#live-demos","title":"Live demos","text":"
  • Tree
  • Display json
"},{"location":"ui-trees/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-trees/#install-plugin","title":"Install plugin","text":""},{"location":"ui-trees/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add trees object
    var trees = scene.rexUI.add.trees(config);\n
"},{"location":"ui-trees/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add trees object
    var trees = scene.rexUI.add.trees(config);\n
"},{"location":"ui-trees/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Trees } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add trees object
    var trees = new Trees(scene, config);\nscene.add.existing(trees);\n
"},{"location":"ui-trees/#add-instance","title":"Add instance","text":"

Trees contains tree-node instance, each tree contains tree instance and node instance.

"},{"location":"ui-trees/#add-trees-object","title":"Add trees object","text":"
var trees = scene.rexUI.add.trees({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n\norientation: 0,\n// rtl: false,\n\n// space: { left: 0, right:0, top:0, bottom:0, item:0 },\n\ntree: {\n// background: function(scene {isLeaf}) { return gameObject; },\n// background: backgroundStyle,\n\n// toggleButton: function(scene, {isLeaf}) {\n//     gameObject\n//         .on('expand.start', function (gameObject) {\n//          })\n//          .on('collapse.start', function (gameObject) {\n//          })\n//     return gameObject;\n// }\n// toggleButton : triangleStyle,\n\n// nodeBackground: function(scene {isLeaf}) { return gameObject; },\n// nodeBackground: backgroundStyle,\n\n// nodeBody: function(scene {isLeaf}) { return gameObject; },\n// nodeBody: simpleLabelStyle,\n\n// transition: {\n//     duration: 200,\n//     expandCallback: undefined,\n//     collapseCallback: undefined,\n// },\n\n// orientation: 'y',\n\n//space: {\n//    indent: 0,\n//    indentLeft: 0, indentRight: 0, indentTop: 0, indentBottom: 0,\n//\n//    nodeLeft: 0, nodeRight: 0, nodeTop: 0, nodeBottom: 0,\n//    toggleButton: 0,\n//},\n\n// align: {\n//     title: 'left',\n//     child: 'left',\n// },\n\n// expand: {\n//     title: true,\n//     child: true,\n// },\n\n// expanded: true,\n},\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this trees. Default value is (0.5, 0.5).
  • orientation :
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Put icon at left side, and text at right side.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Put icon at top side, and text at bottom side.
  • rtl :
    • true : Layout children from right to left.
    • false : Layout children from left to right. Default behavior.
  • space : Pads spaces.
    • space.left, space.right, space.top, space.bottom : Space of bounds.
    • space.item : Space between 2 children game objects.
  • tree : Default configuration of node, optional.
    • tree.background :
      • Callback
        function(scene, {isLeaf}) {\nreturn gameObject;\n}\n
        • isLeaf :
          • false : This node is a tree-node.
          • true : This node is a leaf-node.
      • Style of Background : Create Round-rectangle, Bar-rectangle, Nine-slice, or Image as background element.
      • undefined : Don't create any game object.
    • tree.toggleButton
      • Callback
        function(scene, {isLeaf}) {\ngameObject\n.on('expand.start', function (gameObject) {\n})\n.on('collapse.start', function (gameObject) {\n})\nreturn gameObject;\n}\n
        • isLeaf :
          • false : This node is a tree-node.
          • true : This node is a leaf-node.
        • Events 'expand.start' and 'collapse.start' will be fired when expanding or collapsing child nodes of this tree.
      • Style of triangle, default behavior.
        {\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n
    • tree.nodeBackground
      • Callback
        function(scene, {isLeaf}) {\nreturn gameObject;\n}\n
        • isLeaf :
          • false : This node is a tree-node.
          • true : This node is a leaf-node.
      • Style of Background : Create Round-rectangle, Bar-rectangle, Nine-slice, or Image as background element.
      • undefined : Don't create any game object.
    • tree.nodeBody
      • Callback
        function(scene, {isLeaf}) {\nreturn gameObject;\n}\n
        • isLeaf :
          • false : This node is a tree-node.
          • true : This node is a leaf-node.
      • Style of simple label : Create Simple-label as node body element. Default behavior.
    • tree.transition : Configuration of expanding/collapsing transition.
      • tree.transition.duration : Duration of expanding/collapsing transition.
      • tree.transition.expandCallback : Callback invoked when expading child. Default behavior is scale-up.
      • tree.transition.collapseCallback : Callback invoked when collapsing child. Default behavior is scale-down.
    • tree.space : Pads spaces of tree.
      • tree.space.indent, tree.space.indentLeft, tree.space.indentRight, tree.space.indentTop, tree.space.indentBottom : Space of node's bounds.
      • tree.space.nodeLeft, tree.space.nodeRight, tree.space.nodeTop, tree.space.nodeBottom : Space of node child's bounds.
      • tree.space.toggleButton : Space between toggle button and next child.
    • tree.align.title, tree.align.child : Alignment of title, child game objects.
      • undefined, or 'left', or 'top' : Align game objects at left, or top. Default behavior.
      • 'center' : Align game objects at center.
      • 'right', or 'bottom' : Align game objects at right, or bottom.
    • tree.expand.title, tree.expand.child : Expand width/height of title, child game objects.
      • true : Expand width/heigh. Default behavior.
      • false : Use origin width/height.
    • tree.expanded :
      • true : Expand this tree node. Default behavior.
      • false : Collapse this tree node.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire trees events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-trees/#add-tree-object","title":"Add tree object","text":"

var tree = trees.addTree();\n// var tree = trees.addTree(nodeKey);\n
var subTree = tree.addTree();\n// var subTree = tree.addTree(nodeKey);\n

or

var tree = trees.addTree({\n// nodeKey: UUID()\n\n// background: backgroundGameObject,\n// background: function(scene {isLeaf}) { return gameObject; },\n// background: backgroundStyle,\n\ntoggleButton: toggleButtonGameObject,\n// toggleButton: function(scene {isLeaf}) { \n//      gameObject\n//          .on('expand.start', function (gameObject) {\n//           })\n//           .on('collapse.start', function (gameObject) {\n//           })\n//     return gameObject; \n// },\n// toggleButton : triangleStyle,\n\n// nodeBackground: nodeBackgroundGameObject,\n// nodeBackground: function(scene {isLeaf}) { return gameObject; },\n// nodeBackground: backgroundStyle,\n\nnodeBody: nodeBodyGameObject,\n// nodeBody: function(scene {isLeaf}) { return gameObject; },\n// nodeBody: simpleLabelStyle,\n\n// transition: {\n//     duration: 200,\n//     expandCallback: undefined,\n//     collapseCallback: undefined,\n// },\n\n// orientation: 'y',\n\n// space: {\n//     indent: 0,\n//     indentLeft: 0, indentRight: 0, indentTop: 0, indentBottom: 0,\n// \n//     nodeLeft: 0, nodeRight: 0, nodeTop: 0, nodeBottom: 0,\n//     toggleButton: 0,\n// },\n\n// align: {\n//     title: 'left',\n//     child: 'left',\n// },\n\n// expand: {\n//     title: true,\n//     child: true,\n// },\n\n// expanded: true,\n})\n
var subTree = tree.addTree(config);\n

  • nodeKey : Store reference of this tree instance by this unique string. Get tree back by trees.getTree(nodeKey)
    • An unique string, does not contain .
    • undefined : Create unique string by UUID
  • background :
    • A game object
    • Callback
      function(scene, {isLeaf}) {\nreturn gameObject;\n}\n
      • isLeaf :
        • false : This node is a tree-node.
        • true : This node is a leaf-node.
    • Style of Background : Create Round-rectangle, Bar-rectangle, Nine-slice, or Image as background element.
    • undefined : Don't create any game object.
  • toggleButton
    • A game object
    • Callback
      function(scene, {isLeaf}) {\ngameObject\n.on('expand.start', function (gameObject) {\n})\n.on('collapse.start', function (gameObject) {\n})\nreturn gameObject;\n}\n
      • isLeaf :
        • false : This node is a tree-node.
        • true : This node is a leaf-node.
      • Events 'expand.start' and 'collapse.start' will be fired when expanding or collapsing child nodes of this tree.
    • Style of triangle, default behavior.
      {\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n
  • nodeBackground
    • A game object
    • Callback
      function(scene, {isLeaf}) {\nreturn gameObject;\n}\n
      • isLeaf :
        • false : This node is a tree-node.
        • true : This node is a leaf-node.
    • Style of Background : Create Round-rectangle, Bar-rectangle, Nine-slice, or Image as background element.
    • undefined : Don't create any game object.
  • nodeBody
    • A game object
    • Callback
      function(scene, {isLeaf}) {\nreturn gameObject;\n}\n
      • isLeaf :
        • false : This node is a tree-node.
        • true : This node is a leaf-node.
    • Style of simple label : Create Simple-label as node body element. Default behavior.
"},{"location":"ui-trees/#add-node-object","title":"Add node object","text":"
  • Add default node game object
    var node = tree.addNode();\n// var node = tree.addNode(nodeKey);\n
    • nodeKey : Store reference of this tree instance by this unique string. Get tree back by trees.getTree(nodeKey)
      • An unique string, does not contain .
      • undefined : Create unique string by UUID
  • Add custom node game object
    var node = tree.addNode(gameObject);\n// var node = tree.addNode(gameObject, nodeKey);\n
"},{"location":"ui-trees/#insert-tree-object","title":"Insert tree object","text":"

var tree = trees.insertTree(index);\n// var tree = trees.insertTree(index, nodeKey);\n// var tree = trees.insertTree(index, config);\n
var subTree = tree.insertTree(index);\n// var subTree = tree.insertTree(index, nodeKey);\n// var subTree = tree.insertTree(index, config);\n

"},{"location":"ui-trees/#insert-node-object","title":"Insert node object","text":"
  • Insert default node game object
    var node = tree.insertTree(index);\n// var node = tree.insertTree(index, nodeKey);\n
  • Insert custom node game object
    var node = tree.insertTree(index, gameObject);\n// var node = tree.insertTree(index, gameObject, nodeKey);\n
"},{"location":"ui-trees/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTrees extends RexPlugins.UI.Trees {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var trees = new MyTrees(scene, config);\n
"},{"location":"ui-trees/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

trees.layout();\n

See also - dirty

Note

Layout topmost trees when expanding/collapsing start.

"},{"location":"ui-trees/#expandcollapse-tree","title":"Expand/collapse tree","text":"
  • Expand, will re-layout from topmost trees
    tree.expand();\n// tree.expand(duration);\n
    tree.expand(0);  // Immediately, won't invoke expandCallback\n
  • Collapse, will re-layout from topmost trees
    tree.collapse();\n// tree.collapse(duration);\n
    tree.collapse(0);  // Immediately, won't invoke collapseCallback\n
  • Toggle, will re-layout from topmost trees
    tree.toggle();\n// tree.toggle(duration);\n
    tree.toggle(0);  // Immediately, won't invoke expandCallback/collapseCallback\n
  • Set expanded state without re-layouting
    tree.setExpandedState(expanded);  // true, or false\n
  • Get expanded state
    var expanded = tree.expanded;\n
    • expanded : Initial value is undefined
"},{"location":"ui-trees/#remove-tree-or-node","title":"Remove tree or node","text":""},{"location":"ui-trees/#remove-tree","title":"Remove tree","text":"
  • Remove tree without destroying
    trees.removeTree(tree);\n
    tree.removeTree(subTree);\n
    tree.removeTree(nodeKey);\n
  • Remove tree and destroying
    trees.removeTree(tree, true);\n
    tree.removeTree(subTree, true);\n
    tree.removeTree(nodeKey, true);\n
  • Remove all trees without destroying
    trees.removeAllNodes();\n
    tree.removeAllNodes();\n
  • Remove all trees and destroying
    trees.removeAllNodes(tree);\n
    tree.removeAllNodes(tree);\n
"},{"location":"ui-trees/#remove-subtree-or-node","title":"Remove subTree or node","text":"
  • Remove subTree or node without destroying
    tree.removeNode(subTree);\n
    tree.removeNode(node);\n
    tree.removeNode(nodeKey);\n
  • Remove subTree or node and destroying
    trees.removeNode(subTree, true);\n
    tree.removeNode(node, true);\n
    tree.removeNode(nodeKey, true);\n
  • Remove all sub-trees and nodes without destroying
    tree.removeAllNodes();\n
  • Remove all sub-trees and nodes and destroying
    tree.removeAllNodes(tree);\n
"},{"location":"ui-trees/#get-sub-tree-or-node","title":"Get sub-tree or node","text":"
  • Get sub-tree
    var tree = trees.getTree(nodeKey);\n
    var tree = subTree.getTree(nodeKey);\n
  • Get sub-tree/node
    var tree = trees.getNode(nodeKeys);\n
    var tree = subTree.getNode(nodeKeys);\n
    • nodeKeys : nodeKeys connected by ., e.x. key0.key1.key2...
  • Get all child nodes in this tree
    var nodes = tree.getNodes();\n// var nodes = tree.getNodes(out);\n
  • Get all child nodes including all descendant nodes
    var nodes = tree.getAllNodes();\n// var nodes = tree.getAllNodes(out);\n
"},{"location":"ui-trees/#get-parent-or-root-tree","title":"Get parent or root tree","text":"
  • Get parent (tree)
    var patent = tree.getTreePatent();\n
    var patent = node.getTreePatent();\n
  • Get root (tree)
    var root = tree.getTreeRoot();\n
    var root = node.getTreeRoot();\n
"},{"location":"ui-trees/#get-element","title":"Get element","text":"
  • Get element in a tree
    • Background game object
      var background = tree.getElement('background');\n
    • Toggle button game object
      var toggleButton = trees.getElement('toggleButton');\n
    • Node-body game object
      var nodeBody = trees.getElement('nodeBody');\n
    • Children-node list game objects
      var childrenNodes = trees.getElement('childrenNodes');\n
  • Get by name
    var gameObject = trees.getElement('#' + name);\n// var gameObject = trees.getElement('#' + name, recursive);\n
    or
    var gameObject = trees.getByName(name);\n// var gameObject = trees.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-trees/#other-properties","title":"Other properties","text":"

Trees is extended from trees object, base trees object, container-lite. Tree is extended from folder.

"},{"location":"ui-trees/#set-children-interactive","title":"Set children interactive","text":"

Applies click, tap, press, swipe behaviors on this trees, to detect input events of children.

tree.setChildrenInteractive({\n// dropZone: false,\n\n// click: {mode: 'release', clickInterval: 100},\n\n// over: undefined,\n\n// press: {time: 251, threshold: 9},\n\n// tap: {time: 250, tapInterval: 200, threshold: 9, tapOffset: 10, \n//       taps: undefined, minTaps: undefined, maxTaps: undefined,},\n\n// swipe: {threshold: 10, velocityThreshold: 1000, dir: '8dir'},\n\n// inputEventPrefix: 'child.',\n})\n
  • dropZone :
    • true : Enable drop Zone on scrollable area.
    • false : Do nothing.
"},{"location":"ui-trees/#events","title":"Events","text":"
  • Pointer-down
    trees.on('child.down', function(child, pointer, event) {        }, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
  • Pointer-up
    trees.on('child.up', function(child, pointer, event) {\n// ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
  • Pointer-over
    trees.on('child.over', function(child, pointer, event) {\n// ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
  • Pointer-out
    trees.on('child.out', function(child, pointer, event) {\n// ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
  • Click
    trees.on('child.click', function(child, pointer, event) {\n// ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
    • pointer : Pointer object.
  • Press
    trees.on('child.pressstart', function(child, pointer) { // ...\n}, scope);\n
    trees.on('child.pressend', function(child, pointer) { // ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
  • Tap
    trees.on(tapEventName, function(child, pointer) { // ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
    • tapEventName : 'child.1tap', 'child.2tap', 'child.3tap', etc ...
  • Swipe
    trees.on(swipeEventName, function(child, pointer) { // ...\n}, scope);\n
    • child : Tree or leaf-node.
      • Pointer on tree's title : child.isTree
      • Pointer on leaf-node : child.isNode
    • swipeEventName : 'child.swipeleft', 'child.swiperight', 'child.swipeup', 'child.swipedown'.
"},{"location":"ui-trees/#events_1","title":"Events","text":"
  • On tree expand-start
    trees.on('expand.start', function(tree){\n\n})\n
  • On tree expand-complete
    trees.on('expand.complete', function(tree){\n\n})\n
  • On tree collapse-start
    trees.on('collapse.start', function(tree){\n\n})\n
  • On tree collapse-complete
    trees.on('collapse.complete', function(tree){\n\n})\n
"},{"location":"ui-tweaker/","title":"Tweaker","text":""},{"location":"ui-tweaker/#introduction","title":"Introduction","text":"

Fine-tuning properties of target object. Reference

  • Author: Rex
  • Game object
"},{"location":"ui-tweaker/#live-demos","title":"Live demos","text":"
  • Tweaker
  • Bind target
  • Horizontal tweaker
  • Columns
  • Wrap
  • Buttons
  • Add rows
  • Edit item
"},{"location":"ui-tweaker/#usage","title":"Usage","text":"

Sample code

"},{"location":"ui-tweaker/#install-plugin","title":"Install plugin","text":""},{"location":"ui-tweaker/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.scenePlugin('rexuiplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuiplugin.min.js', 'rexUI', 'rexUI');\n
  • Add tweaker object
    var tweaker = scene.rexUI.add.tweaker(config);\n
"},{"location":"ui-tweaker/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin.js';\nvar config = {\n// ...\nplugins: {\nscene: [{\nkey: 'rexUI',\nplugin: UIPlugin,\nmapping: 'rexUI'\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add tweaker object
    var tweaker = scene.rexUI.add.tweaker(config);\n
"},{"location":"ui-tweaker/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import { Tweaker } from 'phaser3-rex-plugins/templates/ui/ui-components.js';\n
  • Add tweaker object
    var tweaker = new Tweaker(scene, config);\nscene.add.existing(tweaker);\n
"},{"location":"ui-tweaker/#add-tweaker-object","title":"Add tweaker object","text":"
var tweaker = scene.rexUI.add.tweaker({\n// x: 0,\n// y: 0,\n// anchor: undefined,\n// width: undefined,\n// height: undefined,\n// origin: 0.5\n// originX:\n// originY:\n// orientation: 0,\n\n// style: { ... }\nstyles : {\nitemWidth : 0,\nitemHeight: 0,\n\ninputRow: {\nbackground: {\n\n},\n\ntitle: {\n\n},\n\ninputText: {\n\n},\n\ninputTextArea: {\nheight:\n},\n\nlist: {\nlabel: {\n\n},\n\nbutton: {\n\n}\n},\n\nbutton: {\n\n},\n\nslider: {\ntrack: {\n\n},\n\nindicator: {\n\n},\n\nthumb: {\n\n}\n},\n\ncolorInput: {\ncolorPicker: {\n\n},\n\ncolorComponents: {\ninputText: {\n\n}\n}\n},\n\ncheckbox: {\n\n},\n\ntoggleSwitch: {\n\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n}\n},\n\nseparator: {\n\n},\n\nfolder: {\n},\n\ntab: {\n},\n\nscrollable: {\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0, item: 0\n},\n},\n\n\n// name: '',\n// draggable: false,\n// sizerEvents: false,\n// enableLayer: false,\n});\n
  • x, y : Position of this object, it is valid when this object is the top object.
  • anchor : See anchor.
    • left, right, centerX, x, top, bottom, centerY, y : Position based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
        • 'left'(=0%), 'center'(=50%), 'right'(=100%)
        • 'top'(=0%), 'center'(=50%), 'bottom'(=100%)
      • Offset : '+n', or '-n'.
    • width, height : Set size (invoke onResizeCallback) based on visible window, which composed of
      • Percentage of visible width/height : 'p%', p: 0 ~ 100.
      • Padding : '+n', or '-n'.
    • onResizeCallback : A default resize callback will be assigned interanlly.
  • width, height : Minimum width, minimum height.
  • origin, originX, originY : Set origin of this sizer. Default value is (0.5, 0.5).
  • orientation : Main orientation of the tweaker.
    • 'left-to-right', 'horizontal','h', 'x', or 0 : Arrange game objects from left ot right.
    • 'top-to-bottom', 'vertical','v', 'y', or 1 : Arrange game objects from top to bottom. Default value is 1.
  • styles, or style : Styles settings of input rows, separator, folder, tab, and scrollable. See Styles chapter for more detail.
    • style.itemWidth : Width of input row, used if orientation is set to 'y'(1).
    • styles.space : Pads spaces.
      • styles.space.left, styles.space.right, styles.space.top, styles.space.bottom : Space of bounds.
      • styles.space.item : Space between 2 input rows.
  • name : Set name of this game object.
  • draggable : Set true to drag top-most object.
  • sizerEvents : Set true to fire sizer events. Default value is false.
  • enableLayer :
    • false : Add child game objects into scene's display list. Default behavior.
    • true : Add child game objects into an internal layer game object. See also.
"},{"location":"ui-tweaker/#custom-class","title":"Custom class","text":"
  • Define class
    class MyTweaker extends RexPlugins.UI.Tweaker {\nconstructor(scene, config) {\nsuper(scene, config);\n// ...\nscene.add.existing(this);\n}\n// ...\n}\n
  • Create instance
    var tweaker = new MyTweaker(scene, config);\n
"},{"location":"ui-tweaker/#add-input-row","title":"Add input row","text":"

An input row can fine-tuning properties of target object.

"},{"location":"ui-tweaker/#text-input-row","title":"Text input row","text":"

object[key] is a text value.

tweaker.addInput(object, key, {    // view: 'string',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n\n// autoUpdate: true,\n// onValidate: undefined,\n// onValueChange: undefined,    \n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'string',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n\n// autoUpdate: true,\n// onValidate: undefined,\n// onValueChange: undefined,    \n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'string', if bindingTarget is not given.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.
  • autoUpdate :
    • true : Update binding key when user input. Default behavior.
    • false : Use onValueChange to set value of binding key when user input.
  • onValidate :
    • Callback invoked when new value input.
      function(newValue, oldValue, bindingTarget, bindingKey) { return true;\n}\n
      • true : Accept this new value.
      • false : Reject this new value.
    • undefined : Always accept new value changing. Default behavior.
  • onValueChange :
    • Callback invoked when binding value changing.
      function(newValue, oldValue, bindingTarget, bindingKey) { }\n
    • undefined : Ignore this feature. Default value.

See Style of text input

"},{"location":"ui-tweaker/#text-area-input-row","title":"Text-Area input row","text":"

object[key] is a text value.

tweaker.addInput(object, key, {    view: 'textarea',\n\n// height: undefined,\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n\n// autoUpdate: true,\n// onValidate: undefined,\n// onValueChange: undefined,    \n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\nview: 'textarea',\n\n// height: undefined,\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n\n// autoUpdate: true,\n// onValidate: undefined,\n// onValueChange: undefined,    \n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : 'textarea'.
  • height : Height of this input row.
    • undefined : Use children height.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.
  • autoUpdate :
    • true : Update binding key when user input. Default behavior.
    • false : Use onValueChange to set value of binding key when user input.
  • onValidate :
    • Callback invoked when new value input.
      function(newValue, oldValue, bindingTarget, bindingKey) { return true;\n}\n
      • true : Accept this new value.
      • false : Reject this new value.
    • undefined : Always accept new value changing. Default behavior.
  • onValueChange :
    • Callback invoked when binding value changing.
      function(newValue, oldValue, bindingTarget, bindingKey) { }\n
    • undefined : Ignore this feature. Default value.

See Style of text-area input

"},{"location":"ui-tweaker/#text-input-from-list","title":"Text input from list","text":"

object[key] is a text value.

tweaker.addInput(object, key, {\n// view: 'list',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0, /* icon: , iconFrame, .. */ },\n{text: text1, value: value1, /* icon: , iconFrame, .. */ },\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'list',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0, /* icon: , iconFrame, .. */ },\n{text: text1, value: value1, /* icon: , iconFrame, .. */ },\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'list', if bindingTarget is not given.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • options : Option list, each item contains
    • text : Display text.
    • value : Set key to this value.
    • icon, iconFrame, ... : See Reset display content of Label
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of list input

"},{"location":"ui-tweaker/#text-input-from-buttons","title":"Text input from buttons","text":"

object[key] is a text value.

tweaker.addInput(object, key, {\nview: 'buttons',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0},\n{text: text1, value: value1},\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\nview: 'buttons',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0},\n{text: text1, value: value1},\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'buttons'.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • options : Option list, each item contains
    • text : Display text.
    • value : Set key to this value.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of buttons input

"},{"location":"ui-tweaker/#number-input-row","title":"Number input row","text":"

object[key] is a number value.

tweaker.addInput(object, key, {\n// view: 'number',\n// int: undefined,\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'number',\n// int: undefined,\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'number', if bindingTarget is not given.
  • int : Set to true to truncate float number to integer number.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of text input

"},{"location":"ui-tweaker/#number-input-in-a-range","title":"Number input in a range","text":"

object[key] is a number value.

tweaker.addInput(object, key, {\n// view: 'range',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\nmin: minValue, max: maxValue,\n// step: undefined,\n\n// format: function(value) { return s; },\n// inputTextReadOnly: false,\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'range',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\nmin: minValue, max: maxValue,\n// step: undefined,\n\n// format: function(value) { return s; },\n// inputTextReadOnly: false,\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'range', if bindingTarget is not given.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • min, max : Minimum, maximun value of range.
  • step : Step/gap of slider, optional.
  • format : Callback to return formatted string for input text field.
    function(value) {\nreturn s;\n}\n
  • inputTextReadOnly :
    • false : Input text field is editable. Default behavior.
    • true : Input text field is read-only.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of range input

"},{"location":"ui-tweaker/#number-input-in-inc-dec-buttons","title":"Number input in inc-dec buttons","text":"

object[key] is a number value.

tweaker.addInput(object, key, {\nview: 'incdec',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// min: undefined, \n// max: undefined,\n// step: 1,\n\n// format: function(value) { return s; },\n// inputTextReadOnly: false,\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'incdec',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// min: undefined, \n// max: undefined,\n// step: 1,\n\n// format: function(value) { return s; },\n// inputTextReadOnly: false,\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'incdec', if bindingTarget is not given.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • step : Incremental or decremental value when clicking inc-button, or dec-button
  • min, max : Minimum, maximun value of range, optional.
  • format : Callback to return formatted string for input text field.
    function(value) {\nreturn s;\n}\n
  • inputTextReadOnly :
    • false : Input text field is editable. Default behavior.
    • true : Input text field is read-only.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of incdec input

"},{"location":"ui-tweaker/#number-input-from-list","title":"Number input from list","text":"

object[key] is a number value.

tweaker.addInput(object, key, {\n// view: 'list',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0},\n{text: text1, value: value1},\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'list',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0},\n{text: text1, value: value1},\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'list', if bindingTarget is not given.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • options : Option list, each item contains
    • text : Display text.
    • value : Set key to this value.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of list input

"},{"location":"ui-tweaker/#number-input-from-buttons","title":"Number input from buttons","text":"

object[key] is a number value.

tweaker.addInput(object, key, {\nview: 'buttons',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0},\n{text: text1, value: value1},\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\nview: 'buttons',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\noptions: [\n{text: text0, value: value0},\n{text: text1, value: value1},\n// ...\n],\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'buttons'.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • options : Option list, each item contains
    • text : Display text.
    • value : Set key to this value.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of buttons input

"},{"location":"ui-tweaker/#color-input","title":"Color input","text":"

object[key] is a number value.

tweaker.addInput(object, key, {\nview: 'color',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\nview: 'color',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'color'.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of color input

"},{"location":"ui-tweaker/#boolean-input-row","title":"Boolean input row","text":"

object[key] is a boolean value.

tweaker.addInput(object, key, {\n// view: 'boolean',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n

or

tweaker.addInput({\nbindingTarget: object,\nbindingKey: key,\n// view: 'boolean',\n// view: 'toggleSwitch',\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • bindingKey : Bind to target's property key. Necessary field
  • view : Set to 'boolean', or 'toggleSwitch', if bindingTarget is not given.
    • 'boolean' : Checkbox input. Default behavior.
    • 'toggleSwitch' : Toggle switch input.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of boolean input

"},{"location":"ui-tweaker/#value-callbacks-row","title":"Value callbacks row","text":"
tweaker.addInput({\nbindingTarget: object,\n\nonGetValue(bindingTarget) {\n\n},\n\nonSetValue(bindingTarget, value) {\n\n},\n\nview: ,\n\n// Other properties..\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\n// title: undefined,\n\n// orientation: 'x',\n\n// monitor: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target object.
    • Can bind target later via tweaker.setBindingTarget(object).
  • onGetValue : Callback to get dispaly value
    function(bindingTarget) {\nreturn value;\n}\n
  • onSetValue : Callback to set value to bindingTarget
    function(bindingTarget, value) {        }\n
  • view : Any kind of view listed before.
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label. Default value is equal to key.
  • monitor :
    • false : Don't update input text every tick from target. Default behavior.
    • true : Update input text from current object, in postupdate event of scene.
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

Note

No bindingKey parameter in this case.

"},{"location":"ui-tweaker/#add-button","title":"Add button","text":"
tweaker.addButton({\n// bindingTarget: object,\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\ntitle: undefined,\n\nlabel: undefined,\n\ncallback: function(target) {},\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target will pass to callback. Optional.
    • Can bind target later via tweaker.setBindingTarget(object).
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label.
  • label : Display text of button, a string or a plain object.
    {\ntext: '',\n\nicon: undefined, iconFrame: undefined,\niconSize: undefined,\n\naction: undefined, actionFrame: undefined,\nactionSize: undefined,\n\n}\n
  • callback : Callback when clicking button
    function(target) { }\n
  • key : Add this child into childMap, which could be read back by tweaker.getElement(key).
    • undefined : Don't add this child. Default value.

See Style of botton

"},{"location":"ui-tweaker/#add-buttons","title":"Add buttons","text":"
tweaker.addButtons({\n// bindingTarget: object,\n\n// icon: undefined,\n// iconFrame: undefined,\n// iconSize: undefined,\n\ntitle: undefined,\n\nbuttons:[\n{\nlabel: undefined,\ncallback: function(target) {},\n},\n{\nlabel: undefined,\ncallback: function(target) {},\n},\n// ...\n],\n\nwrap: false,\n\n// key: undefined,\n})\n
  • bindingTarget : Binding target will pass to callback. Optional.
    • Can bind target later via tweaker.setBindingTarget(object).
  • icon, iconFrame : Texture key, frame name of icon on title-label.
  • iconSize : Fixed icon size
  • title : Display text of title-label.
  • buttons : Array of button label and button callback
    {\nlabel: undefined,\ncallback: function(target) {},\n}\n
    • label : Display text of button, a string or a plain object. ```javascript { text: '',

      icon: undefined, \niconFrame: undefined,\niconSize: undefined,\n\naction: undefined, \nactionFrame: undefined,\nactionSize: undefined,\n

      } `` -callback: Callback when clicking button

      function(target) { }\n
      -wrap: Layout mode of buttons. -true: [fixwidth-sizer](ui-fixwidthsizer.md) layout. -false: [sizer](ui-sizer.md) layout. Default behavior. -key: Add this child into childMap, which could be read back bytweaker.getElement(key). -undefined` : Don't add this child. Default value.

See Style of botton

"},{"location":"ui-tweaker/#add-separator","title":"Add separator","text":"
tweaker.addSeparator();\n

See Style of separator

"},{"location":"ui-tweaker/#add-folder","title":"Add folder","text":"

Folder contains collapsible child tweaker game object.

var childTweaker = tweaker.addFolder({\ntitle: titleA,\n\n// expanded: true,\n});\n\n// childTweaker.addInput(...)\n
  • childTweaker : Child tweaker game object. Add input rows by addInput method.
  • title Title of folder. Click title can collapse or expand child tweaker game object.
  • expanded :
    • true : Expand child tweaker game object at beginning. Default behavior.
    • false : Collapse child tweaker game object at beginning.

See Style of folder

"},{"location":"ui-tweaker/#add-tab","title":"Add tab","text":"

Tab containes pages. Each page is a tweaker game object.

var childrenTweakers = tweaker.addTab({\npages: [\n{\ntitle: titleA, // show: false\n},\n{\ntitle: titleB\n// show: false\n},\n// ...\n]\n});\n\n// childrenTweakers[0].addInput(...)\n// childrenTweakers[1].addInput(...)\n
  • childrenTweakers : Array of children tweaker game object. Add input rows by addInput method.
  • pages : Array of page setting.
    {\ntitle: titleA,\nshow: false,\n}\n
    • title : Display text of page title
    • show : Set to true to show this page at beginning

See Style of tab

"},{"location":"ui-tweaker/#add-columns","title":"Add columns","text":"

Multiple columns in a row. Each column is a tweaker game object.

var childrenTweakers = tweaker.addColumns(amount);\n\n// childrenTweakers[0].addInput(...)\n// childrenTweakers[1].addInput(...)\n

or

var childrenTweakers = tweaker.addColumns({\n// title: title,\n\ncolumns: [\n{\n// width: 0,\n// expand: true\n},\n{\n// width: 0,\n// expand: true\n},\n]\n});\n\n// childrenTweakers[0].addInput(...)\n// childrenTweakers[1].addInput(...)\n
  • childrenTweakers : Array of children tweaker game object. Add input rows by addInput method.
  • amount : A number, amount of columns. Will use default column config.
  • columns : Array of column config, each column config contains
    • width : Minimum width of this column, default value is 0, will set proportion to 1.
    • expand : Expand height of this column, default value is true.

See Style of columns

"},{"location":"ui-tweaker/#add-wrap","title":"Add wrap","text":"

A tweaker panel which Wrap input rows into multiple lines.

var childTweaker = tweaker.addWrap({\n// title: titleA,\n\nitemWidth: 0,\nitemHeight: 0,\n});\n\n// childTweaker.addInput(...)\n
  • childTweaker : Child tweaker game object. Add input rows by addInput method.
  • title Title of folder. Click title can collapse or expand child tweaker game object.
  • itemWidth, itemHeight : Size of input row.

See Style of wrap

"},{"location":"ui-tweaker/#add-scrollable","title":"Add scrollable","text":"

Scrollable(Panel) contains child tweaker game object and slider.

var childTweaker = tweaker.addScrollable({\n// title: title,\n\n// height: 0\n});\n\n// childTweaker.addInput(...)\n
  • childTweaker : Child tweaker game object. Add input rows by addInput method.
  • title Title of scrolable.
    • A string : Title string.
    • undefined : Hide this title game object.
  • height :
    • A number : Height of this Scrollable(Panel).
    • undefined, or 0 : Expand this scrollable(Panel).

See Style of scrollable

"},{"location":"ui-tweaker/#add-rows","title":"Add rows","text":"

Add mutiple rows (input row, button, buttons, separator, folder, tab) in a single method

tweaker.addRows(properties, target);\n// tweaker.addRows(properties, target, monitor);\n
  • properties : A list of properties, each property could be one of
    • Input row
      {\n$key: '',\n// $target:\n// More properties...\n}\n
      • $key : Assign this value to bindingKey
      • $target : Assign this value to bindingTarget
        • undefined : Use target parameter from addRows method. Default behavior
      • More properties. See
        • Text input row,
        • Text area input row,
        • Text input from list
        • Text input from buttons
        • Number input row
        • Number input in a range
        • Number input from list
        • Number input from buttons
        • Color input row
        • Boolean input row
        • Value callback row
    • Button
      {\n$type: 'button', title: '', label: '',\ncallback(target) {\n}\n}\n
    • Buttons
    • Separator
      { $type: 'separator' }\n
    • Folder
      {\n$type: 'folder', title: '',\n// $target: \n$properties: [\n// ...\n]\n}\n
      • $target : Override target value pass to remainder $properties.
        • undefined : Use previous target value. Default behavior.
    • Tab
      {\n$type: 'tab',\n// $target:\npages: [\n{\ntitle: '',\n$properties: [\n// ...\n]\n},\n{\ntitle: '',\n$properties: [\n// ...\n]\n},\n// ... More pages\n]\n}\n
      • $target : Override target value pass to remainder $properties.
        • undefined : Use previous target value. Default behavior.
    • Columns
      {\n$type: 'columns',\n// $target:\ncolumns: [\n{\n// width: 0,\n// expand: true,\n$properties: [\n// ...\n]\n},\n{\n// width: 0,\n// expand: true,\n$properties: [\n// ...\n]\n},\n// ... More columns\n]\n}\n
      • $target : Override target value pass to remainder $properties.
        • undefined : Use previous target value. Default behavior.
    • Wrap
      {\n$type: 'wrap', title: '',\n// $target: \n$properties: [\n// ...\n]\n}\n
      • $target : Override target value pass to remainder $properties.
        • undefined : Use previous target value. Default behavior.
    • Scrollable
      {\n$type: 'scrollable', title: undefined,\n// $target: \n$properties: [\n// ...\n]\n}\n
      • $target : Override target value pass to remainder $properties.
        • undefined : Use previous target value. Default behavior.
  • monitor :
    • false : Don't update input text every tick from target.
    • true : Update input text from current object, in postupdate event of scene. Default behavior.
"},{"location":"ui-tweaker/#layout-children","title":"Layout children","text":"

Arrange position of all elements.

tweaker.layout();\n

See also - dirty

"},{"location":"ui-tweaker/#styles","title":"Styles","text":""},{"location":"ui-tweaker/#style-of-text-input","title":"Style of text input","text":"

Style of text-area input is defined in

  • styles.inputRow.title
  • styles.inputRow.inputText
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\ninputText: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\nfocusStyle: {\n// color:\n// color2:\n// horizontalGradient:\n\n// stroke:\n// strokeThickness:\n\n// cornerRadius:\n// cornerIteration:\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\ncursorStyle: {\n// bold:\n// italic:\n// fontSize:\n// fontFamily:\n// color:\n// stroke:\n// strokeThickness:\n// shadowColor:\n// shadowOffsetX:\n// shadowOffsetY:\n// shadowBlur:\n// backgroundColor:\n// backgroundHeight:\n// backgroundBottomY:\n// offsetX:\n// offsetY:\n}\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-text-area-input","title":"Style of text-area input","text":"

Style of text-area input is defined in

  • styles.inputRow.title
  • styles.inputRow.inputTextArea
  • styles.inputRow.inputText
  • styles.inputRow.slider
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\ninputTextArea: {\nheight: undefined,\n\ntext: {\n\n},\n\nslider: {\n// ...\n}\n},\n\ninputText: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\nfocusStyle: {\n// color:\n// color2:\n// horizontalGradient:\n\n// stroke:\n// strokeThickness:\n\n// cornerRadius:\n// cornerIteration:\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\ncursorStyle: {\n// bold:\n// italic:\n// fontSize:\n// fontFamily:\n// color:\n// stroke:\n// strokeThickness:\n// shadowColor:\n// shadowOffsetX:\n// shadowOffsetY:\n// shadowBlur:\n// backgroundColor:\n// backgroundHeight:\n// backgroundBottomY:\n// offsetX:\n// offsetY:\n}\n},\n\nslider: {\ntrack: {\nheight: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nindicator: {\nheight: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nthumb: {\nwidth: 0, height: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n}\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n}\n}\n}\n

Style of text-area is defined at styles.inputRow.inputTextArea :

  • Define style of input text at styles.inputRow.inputTextArea.text, if not given, it will use styles.inputRow.inputText.
  • Define style of slider at styles.inputRow.inputTextArea.slider, if not given, it will use styles.inputRow.slider.
"},{"location":"ui-tweaker/#style-of-list-input","title":"Style of list input","text":"

Style of text/number list input is defined in

  • styles.inputRow.title
  • styles.inputRow.list
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nlist: {\nlabel: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n\n},\n\nbutton: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n\n'hover.color': undefined,\n'hover.alpha': undefined,\n'hover.strokeColor': undefined,\n'hover.strokeAlpha': undefined,\n'hover.strokeWidth': undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nlist: {\nalignParent: 'text',\nalignSide: 'left',\nexpandDirection: 'down',\n}\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-buttons-input","title":"Style of buttons input","text":"

Style of buttons input is defined in

  • styles.inputRow.title
  • styles.inputRow.button
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nbutton: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n},\n\nexpand: true\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-range-input","title":"Style of range input","text":"

Style of range input is defined in

  • styles.inputRow.title
  • styles.inputRow.slider
  • styles.inputRow.inputText
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nslider: {\ntrack: {\nheight: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nindicator: {\nheight: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nthumb: {\nwidth: 0, height: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n}\n},\n\ninputText: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\nfocusStyle: {\n// color:\n// color2:\n// horizontalGradient:\n\n// stroke:\n// strokeThickness:\n\n// cornerRadius:\n// cornerIteration:\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\ncursorStyle: {\n// bold:\n// italic:\n// fontSize:\n// fontFamily:\n// color:\n// stroke:\n// strokeThickness:\n// shadowColor:\n// shadowOffsetX:\n// shadowOffsetY:\n// shadowBlur:\n// backgroundColor:\n// backgroundHeight:\n// backgroundBottomY:\n// offsetX:\n// offsetY:\n}\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\nrange: {\nslider: 0,\ninputText: 0,\n}\n}\n\n}\n}\n}\n
  • Set proportion.range.slider and proportion.range.inputText to layout slider and inputText.
"},{"location":"ui-tweaker/#style-of-inc-dec-input","title":"Style of inc-dec input","text":"

Style of range input is defined in

  • styles.inputRow.title
  • styles.inputRow.incDec
  • styles.inputRow.inputText
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nincDec: {\nincButton: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nicon: {\nkey:,\nframe:,\n},\n\ntext: null,\naction: null,\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\ndecButton: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nicon: {\nkey:,\nframe:,\n},\n\ntext: null,\naction: null,\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\ninputTextIndex: 0, // 0,1,2\n},\n\n\ninputText: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\nfocusStyle: {\n// color:\n// color2:\n// horizontalGradient:\n\n// stroke:\n// strokeThickness:\n\n// cornerRadius:\n// cornerIteration:\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\ncursorStyle: {\n// bold:\n// italic:\n// fontSize:\n// fontFamily:\n// color:\n// stroke:\n// strokeThickness:\n// shadowColor:\n// shadowOffsetX:\n// shadowOffsetY:\n// shadowBlur:\n// backgroundColor:\n// backgroundHeight:\n// backgroundBottomY:\n// offsetX:\n// offsetY:\n}\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\nrange: {\nslider: 0,\ninputText: 0,\n}\n}\n\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-color-input","title":"Style of color input","text":"

Style of color input is defined in

  • styles.inputRow.title
  • styles.inputRow.inputText
  • styles.inputRow.colorInput
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\ncolorInput: {\nswatch: {\nradius: 0,\nsize: undefined,\n},\n\ninputText: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\nfocusStyle: {\n// color:\n// color2:\n// horizontalGradient:\n\n// stroke:\n// strokeThickness:\n\n// cornerRadius:\n// cornerIteration:\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\ncursorStyle: {\n// bold:\n// italic:\n// fontSize:\n// fontFamily:\n// color:\n// stroke:\n// strokeThickness:\n// shadowColor:\n// shadowOffsetX:\n// shadowOffsetY:\n// shadowBlur:\n// backgroundColor:\n// backgroundHeight:\n// backgroundBottomY:\n// offsetX:\n// offsetY:\n}\n},                // inputText: false,\n\ncolorPicker: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n}\n},\n\ncolorComponents: {\ninputText: {\nbackground: {\ncolor: null,\ncolor2: null,\nhorizontalGradient: true,\n\nstroke: null,\nstrokeThickness: 2,\n\ncornerRadius: 0,\ncornerIteration: null\n},\nfocusStyle: {\n// color:\n// color2:\n// horizontalGradient:\n\n// stroke:\n// strokeThickness:\n\n// cornerRadius:\n// cornerIteration:\n},\n\nstyle: {\nbold: false,\nitalic: false,\nfontSize: '16px',\nfontFamily: 'Courier',\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadowColor: null,\nshadowOffsetX: 0,\nshadowOffsetY: 0,\nshadowBlur: 0,\nbackgroundColor: null,\nbackgroundHeight: undefined,\nbackgroundBottomY: undefined,\noffsetX: 0,\noffsetY: 0\n},\ncursorStyle: {\n// bold:\n// italic:\n// fontSize:\n// fontFamily:\n// color:\n// stroke:\n// strokeThickness:\n// shadowColor:\n// shadowOffsetX:\n// shadowOffsetY:\n// shadowBlur:\n// backgroundColor:\n// backgroundHeight:\n// backgroundBottomY:\n// offsetX:\n// offsetY:\n}\n\n}\n}\n\n// colorComponents: false,\n\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-boolean-input","title":"Style of boolean input","text":"

Style of boolean input is defined in

  • styles.inputRow.title
  • styles.inputRow.checkbox, or styles.inputRow.toggleSwitch
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\n// For checkbox view\ncheckbox: {\n// size: undefined,\n\ncolor: 0x005cb2,\nboxFillAlpha: 1,\nuncheckedColor: null,\nuncheckedBoxFillAlpha: 1,\n\nboxLineWidth: 4,\nboxStrokeColor: 0x005cb2,\nboxStrokeAlpha: 1,\nuncheckedBoxStrokeColor: 0x005cb2,\nuncheckedBoxStrokeAlpha: 1,\n\ncheckerColor: 0xffffff,\ncheckerAlpha: 1,\n\ncircleBox: false\n\nanimationDuration: 150,\n\nreadOnly: false,\n},\n\n// For toggle switch view\ntoggleSwitch: {\n// size: undefined,\n\ncolor: 0x005cb2,\ntrackFillAlpha: 1,\nfalseValueTrackColor: undefined,\nfalseValueTrackFillAlpha: 1,\n\nthumbColor: 0xffffff,\nthumbAlpha: 1,\n\ntrackWidth: 0.9,\ntrackHeight: 0.5,\ntrackCornerRadius: (trackHeight * 0.5),\n\nthumbHeight: (trackHeight * 0.9),\nthumbWidth: (thumbHeight),\nthumbCornerRadius: (thumbHeight * 0.5),\n\nthumbLeft: 0.3,\nthumbRight: (1 - thumbLeft),\nrtl: false,\n\nanimationDuration: 150,\n\nreadOnly: false,\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-botton","title":"Style of botton","text":"

Style of button is defined in

  • styles.inputRow.title
  • styles.inputRow.button
  • styles.inputRow.background
{\n// style: {...}\nstyles: {\ninputRow: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nbutton: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom: 0,\ntitle: 0\n},\n\nproportion: {\ntitle: 0, inputField: 0,\n}\n\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-separator","title":"Style of separator","text":"

Style of separator is defined in

  • styles.separator
{\n// style: {...}\nstyles: {\nseparator: {\nheight: 0,\n\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-folder","title":"Style of folder","text":"

Style of folder is defined in

  • styles.folder
{\n// style: {...}\nstyles: {\nfolder: {\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n},\n\nexpandedIcon: {\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n},\n\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, }\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-tab","title":"Style of tab","text":"

Style of tab is defined in

  • styles.tab
{\n// style: {...}\nstyles: {\ntab: {\ntab: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n\n'active.color': undefined,\n'active.alpha': undefined,\n'active.strokeColor': undefined,\n'active.strokeAlpha': undefined,\n'active.strokeWidth': undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n}\n},\n\nwrapTabs: false,\n\ntabs: {\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, item: 0,\n}\n},\n\npages: {\nfadeIn: 0,\n}\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-columns","title":"Style of columns","text":"

Style of columns is defined in

  • styles.columns
{\n// style: {...}\nstyles: {\ncolumns: {\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n},\n\nexpandedIcon: {\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n},\n\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\n//background: [\n//    {\n//        radius: 0,\n//        // radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n//\n//        color: undefined,\n//        alpha: undefined,\n//        strokeColor: undefined,\n//        strokeAlpha: undefined,\n//        strokeWidth: undefined,\n//    }\n//],\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, column: 0,\n}\n}\n}\n}\n
"},{"location":"ui-tweaker/#style-of-wrap","title":"Style of wrap","text":"

Style of wrap is defined in

  • styles.wrap
{\n// style: {...}\nstyles: {\nwrap: {\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n},\n\nexpandedIcon: {\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n},\n\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nspace: {\nitem: 0, line: 0\n},\n\nalign: 'justify-cneter'\n}\n}\n}\n
  • align : Align children of a line.
    • 0, 'left' : Align children of a line to left/top side.
    • 1, 'right' : Align children of a line to right/bottom side.
    • 2, 'center' : Align children of a line to ceter.
    • 3, 'justify', 'justify-left' : If remainder space is less or equal than 25%, then justify children. Else align children to left/top side.
    • 4, 'justify-right' : If remainder space is less or equal than 25%, then justify children. Else align children to right/bottom side.
    • 5, 'justify-cneter' : If remainder space is less or equal than 25%, then justify children. Else align children to center.
"},{"location":"ui-tweaker/#style-of-scrollable","title":"Style of scrollable","text":"

Style of scrollable is defined in

  • styles.scrollable
{\n// style: {...}\nstyles: {\nscrollable: {\ntitle: {\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\ntext: {\nfontFamily: 'Courier',\nfontSize: '16px',\nfontStyle: '',\nbackgroundColor: null,\ncolor: '#fff',\nstroke: '#fff',\nstrokeThickness: 0,\nshadow: {\noffsetX: 0,\noffsetY: 0,\ncolor: '#000',\nblur: 0,\nstroke: false,\nfill: false\n},                  padding: {\nleft: 0,\nright: 0,\ntop: 0,\nbottom: 0,\n},\n// more text styles\n},\n\niconSize: undefined,\niconWidth: undefined, iconHeight: undefined,\n\nspace: {\nleft: 0, right: 0, top: 0, bottom:0, icon: 0, text: 0\n},\n\nexpandedIcon: {\ncolor: undefined,\nalpha: 1,\n\nstrokeColor: undefined,\nstrokeAlpha: 1,\nstrokeWidth: 1,\narrowOnly: false,\n\neaseDuration: 0,\n}\n},\n\nbackground: {\nradius: 0,\n// radius: {tl: {x,y}, tr: {x,y}, bl: {x,y}, br: {x,y}}\n\ncolor: undefined,\nalpha: undefined,\nstrokeColor: undefined,\nstrokeAlpha: undefined,\nstrokeWidth: undefined,\n},\n\nslider: {\ntrack: { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n},\n\nthumb: { width: 1, height: 1,\nradius: 0, color: undefined, alpha: 1,\nstrokeColor: undefined, strokeAlpha: 1, strokeWidth: 2,\nshape: undefined\n},\n\n// hideUnscrollableSlider: false,\n// adaptThumbSize: false,\n// minThumbSize: undefined,\n},\n\nspace: {\npanel:0, }\n}\n}\n}\n
"},{"location":"ui-tweaker/#bind-target","title":"Bind target","text":"

All input rows will bind to this new target, and update display status.

tweaker.setBindingTarget(object);\n
"},{"location":"ui-tweaker/#events","title":"Events","text":"
  • On value change of any bindingKey
    tweaker.on('valuechange', function(newValue, oldValue, bindingTarget, bindingKey) {\n\n})\n
"},{"location":"ui-tweaker/#get-element","title":"Get element","text":"
  • Get by key
    var gameObject = tweaker.getElement(key);\n
    • key : Add by key parameter in tweaker.addInput(config) method
      tweaker.addInput({\nkey: ...\n})\n
  • Get by name
    var gameObject = tweaker.getElement('#' + name);\n// var gameObject = pages.getElement('#' + name, recursive);\n
    or
    var gameObject = tweaker.getByName(name);\n// var gameObject = tweaker.getByName(name, recursive);\n
    • recursive : Set true to search all children recursively.
"},{"location":"ui-tweaker/#other-properties","title":"Other properties","text":"

See sizer object, base sizer object, container-lite.

"},{"location":"uniqueitemlist/","title":"Unique item list","text":""},{"location":"uniqueitemlist/#introduction","title":"Introduction","text":"

List of unique items. Support array and set methods.

  • Author: Rex
  • Data structure
"},{"location":"uniqueitemlist/#usage","title":"Usage","text":"

Sample code

"},{"location":"uniqueitemlist/#install-plugin","title":"Install plugin","text":""},{"location":"uniqueitemlist/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexuniqueitemlistplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexuniqueitemlistplugin.min.js', true);\n
  • Add list object
    var listA = scene.plugins.get('rexuniqueitemlistplugin').add(config);\n
"},{"location":"uniqueitemlist/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import UniqueItemListPlugin from 'phaser3-rex-plugins/plugins/uniqueitemlist-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexUniqueItemList',\nplugin: UniqueItemListPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add list object
    var listA = scene.plugins.get('rexUniqueItemList').add(config);\n
"},{"location":"uniqueitemlist/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import UniqueItemList from 'phaser3-rex-plugins/plugins/uniqueitemlist.js';\n
  • Add list object
    var listA = new UniqueItemList();\n
"},{"location":"uniqueitemlist/#create-instance","title":"Create instance","text":"
var listA = scene.plugins.get('rexUniqueItemList').add({\n// items: undefined,\n// autoCleanup: true\n});\n
  • items : Initial items.
  • autoCleanup : Set true to remove item when item is destroyed (from item's 'destroy' event)

or

var listA = scene.plugins.get('rexUniqueItemList').add(items);\n
"},{"location":"uniqueitemlist/#items","title":"Items","text":"
  • Get first item
    var item = listA.getFirst();\n
  • Get last item
    var item = listA.getLast();\n
  • Get item at index
    var item = listA.get(index);\n
  • Get a random item
    var item = listA.getRandom();\n
  • Get items
    var items = listA.getItems();\n
  • Clone items to a new array
    var items = listA.cloneItems();\n
"},{"location":"uniqueitemlist/#item-count","title":"Item count","text":"
  • Get item count
    var count = listA.length;\n
  • List is empty
    var isEmpty = listA.isEmpty();\n
"},{"location":"uniqueitemlist/#contains","title":"Contains","text":"
  • Has item
    var hasItem = listA.contains(item);\n
  • Has any item
    var hasAny = listA.any(listB);\n
  • Has all items
    var hasAll = listA.all(listB);\n
"},{"location":"uniqueitemlist/#array-operations","title":"Array operations","text":""},{"location":"uniqueitemlist/#add","title":"Add","text":"
  • Add to last
    listA.add(item);\n
    or
    listA.addLast(item);\n
  • Add to first
    listA.addFirst(item);\n
  • Insert to index
    listA.add(item, index);\n
  • Insert, or move to index
    listA.add(item, iindex, true);\n
  • Add items
    listA.addMultiple(items);\n
  • Clone list
    var newList = listA.clone();\n// listA.clone(listB)\n
"},{"location":"uniqueitemlist/#remove","title":"Remove","text":"
  • Remove item
    listA.remove(item);\n
  • Remove first
    listA.removeFirst();\n
  • Remove last
    listA.removeLast();\n
  • Remove item at index
    listA.remove(undefined, index);\n
  • Remove items
    listA.removeMultiple(items);\n
  • Remove all items
    listA.clear();\n
  • Destroy all items
    listA.clear(true);\n
"},{"location":"uniqueitemlist/#pop","title":"Pop","text":"
  • Pop first item
    var item = listA.pop();\n
    or
    var item = listA.popFirst();\n
  • Pop last item
    var item = listA.popLast();\n
  • Pop item at index
    var item = listA.pop(index);\n
  • Pop a random item
    var item = listA.popRandom();\n
"},{"location":"uniqueitemlist/#slice","title":"Slice","text":"
  • Extract items from startIndex to endIndex (item of endIndex is included)
    var newList = listA.slice(startIndex, endIndex);\n// listA.slice(startIndex, endIndex, listB);\n
"},{"location":"uniqueitemlist/#sort","title":"Sort","text":"
  • Sort
    list.sort(function(itemA, itemB) {\nif (itemA > itemB) {\nreturn 1;\n} else if (itemA < itemB) {\nreturn -1;\n} else {\nreturn 0;\n}\n})\n
  • Reverse
    listA.reverse();\n
  • Shuffle
    listA.shuffle();\n
"},{"location":"uniqueitemlist/#set-operations","title":"Set operations","text":"
  • C = A | B
    var listC = listA.union(listB);\n// listA.union(listB, listC);\n
    • listC : Result unique-item-list. Can be listA, or listB.
  • C = A & B
    var listC = listA.intersect(listB);\n// listA.intersect(listB, listC);\n
    • listC : Result unique-item-list. Can be listA, or listB.
  • C = A - B
    var listC = listA.difference(listB);\n// listA.difference(listB, listC);\n
    • listC : Result unique-item-list. Can be listA, or listB.
"},{"location":"uniqueitemlist/#call-method","title":"Call method","text":"

Apply method of each item.

listA.call(fnName, arg0, arg1, arg2, ...);\n
  • fnName : Method name of item.
  • arg0, arg1, arg2 : Arguments of fnName method.

Warning

Don't add or remove any item during this method.

listA.call(function(item, i) {\n// ....\n}, scope);\n
  • callback : A function object.
    function(item, i) {\n\n}\n
"},{"location":"uuid/","title":"UUID","text":""},{"location":"uuid/#introduction","title":"Introduction","text":"

Creates and returns an RFC4122 version 4 compliant UUID, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"uuid/#usage","title":"Usage","text":"
var uuid = Phaser.Utils.String.UUID();\n
"},{"location":"vector2/","title":"Vector2","text":""},{"location":"vector2/#introduction","title":"Introduction","text":"

A representation of a vector in 2D space ({x, y}), built-in object of phaser.

  • Author: Richard Davey
"},{"location":"vector2/#usage","title":"Usage","text":""},{"location":"vector2/#create-object","title":"Create object","text":"
var vector = new Phaser.Math.Vector2();\n// var vector = new Phaser.Math.Vector2(x, y);\n// var vector = new Phaser.Math.Vector2({x, y});\n
"},{"location":"vector2/#clone","title":"Clone","text":"
var newVector = vector.clone();\n
"},{"location":"vector2/#set-components","title":"Set components","text":"
  • Set (x, y)
    vector.set(x, y);\n// vector.setTo(x, y);\n
    or
    vector.copy({x, y});\n// vector.setFromObject({x, y});\n
  • Set angle
    vector.setAngle(angle);\n
    • angle : Angle in radians.
  • Rotate
    vector.rotate(delta);\n
    • delta : The angle to rotate by, in radians.
  • Project
    vector.project(srcVector2);\n
  • Set length
    vector.setLength(length);\n
  • Set from polar coordinate
    vector.setToPolar(azimuth, radius);\n
    • azimuth : The angular coordinate, in radians.
    • radius : The radial coordinate (length). Default is 1.
  • Reset to (0, 0)
    vector.reset();\n
"},{"location":"vector2/#get-componments","title":"Get componments","text":"
  • X, Y
    var x = vector.x;\nvar y = vector.y;\n
  • Angle
    var angle = vector.angle(); // angle in radians\n
  • Length
    var length = vector.length();\n
    or
    var lengthSq = vector.lengthSq(); // squared\n
"},{"location":"vector2/#methods","title":"Methods","text":"
  • Scale
    vector.scale(value);\n
  • Limit the length
    vector.limit(value);\n
  • Normalize
    vector.normalize();\n
  • Negate
    vector.negate();\n
  • Rotate perpendicular
    vector.normalizeRightHand();\nvector.normalizeLeftHand();\n
  • Reflect
    • Reflect this Vector off a line defined by a normal.
      vector.reflect(normal);\n
      • normal : A vector perpendicular to the line.
    • Reflect this Vector across another.
      vector.mirror(axis);\n
      • axis : A vector to reflect across.
"},{"location":"vector2/#vector-methods","title":"Vector methods","text":"
  • Add
    vector.add(src); // src: {x, y}\n
  • Subtract
    vector.subtract(src); // src: {x, y}\n
  • Multiply
    vector.multiply(src); // src: {x, y}\n
  • Divide
    vector.divide(src); // src: {x, y}\n
  • Dot
    var value = vector.dot(src); // src: {x, y}\n
  • Cross
    var value = vector.cross(src); // src: {x, y}\n
  • Fuzzy Equal
    var equal = vector.fuzzyEquals(src); // src: {x, y}\n// var equal = vector.fuzzyEquals(src, epsilon);\n
"},{"location":"vector2/#points-method","title":"Points method","text":"
  • Distance between 2 points.
    var distance = vector.distance(src);\n
    or
    var distanceSq = vector.distanceSq(src); // squared\n
  • Linearly interpolate between 2 points.
    vector.lerp(src, t); // src: {x, y}\n
    • t : The interpolation percentage, between 0 and 1.
"},{"location":"vector2/#constant","title":"Constant","text":"
  • Zero (0,0)
    var vector = Phaser.Math.Vector2.ZERO;\n
  • One (1,1)
    var vector = Phaser.Math.Vector2.ONE;\n
  • Right (1,0)
    var vector = Phaser.Math.Vector2.RIGHT;\n
  • Left (-1,0)
    var vector = Phaser.Math.Vector2.LEFT;\n
  • Up (0,-1)
    var vector = Phaser.Math.Vector2.UP;\n
  • Down (0,1)
    var vector = Phaser.Math.Vector2.DOWN;\n
"},{"location":"video/","title":"Video","text":""},{"location":"video/#introduction","title":"Introduction","text":"

Handling playback of a video file, video stream or media stream.

  • Author: Richard Davey
"},{"location":"video/#usage","title":"Usage","text":""},{"location":"video/#load-video","title":"Load video","text":"
scene.load.video(key, url, noAudio);\n

Reference: load video

Cross-origin

Can't load video cross-origin via scene.load.video(...). Using scene.add.video(x, y).loadURL(urls, noAudio, crossOrigin) to load video cross-origin.

"},{"location":"video/#add-video-object","title":"Add video object","text":""},{"location":"video/#reference-video-from-video-cache","title":"Reference video from Video Cache","text":"
var video = scene.add.video(x, y, key);\n
  • key : Key of the Video this Game Object will play, as stored in the Video Cache.
"},{"location":"video/#load-video-from-url","title":"Load video from URL","text":"
  1. Add video object
    var video = scene.add.video(x, y);\n
  2. Play video from URL
    video.loadURL(url);\n// video.loadURL(urls, noAudio, crossOrigin);\n
    • noAudio : Does the video have an audio track? If not you can enable auto-playing on it.
      • false : Has audio track. Default behavior.
    • crossOrigin : The value to use for the crossOrigin property in the video load request.
      • undefined : crossorigin will not be set in the request. Default behavior.
      • 'anonymous'
      • 'use-credentials'
"},{"location":"video/#load-video-from-mediastream","title":"Load video from MediaStream","text":"
video.loadMediaStream(stream);\n// video.loadMediaStream(stream, noAudio, crossOrigin);\n
  • stream : The MediaStream object.
  • noAudio : Does the video have an audio track? If not you can enable auto-playing on it.
    • false : Has audio track. Default behavior.
  • crossOrigin : The value to use for the crossOrigin property in the video load request.
    • undefined : crossorigin will not be set in the request. Default behavior.
    • 'anonymous'
    • 'use-credentials'
navigator.mediaDevices.getUserMedia({ video: true, audio: false })\n.then(function(stream) {\nvideo.loadMediaStream(stream, true);\nvideo.play();\n})\n.catch(function(err) {\n\n})\n
  • navigator.mediaDevices.getUserMedia
"},{"location":"video/#get-first-frame","title":"Get first frame","text":"
video.getFirstFrame();\n
"},{"location":"video/#size","title":"Size","text":"
  • Initial size : 256x265 (video.setSize(256, 256))
  • Size after playing : Size of video from metadata
"},{"location":"video/#play","title":"Play","text":"
video.play();\n// video.play(loop, markerIn, markerOut);\n
  • loop : Should the video loop automatically when it reaches the end? Please note that not all browsers support seamless video looping for all encoding formats.
  • markerIn, markerOut : Optional in/out marker time, in seconds, for playback of a sequence of the video.

Play video first time

Call video.play() when playing video first time.

Note

If you need audio in your videos, then you'll have to consider the fact that the video cannot start playing until the user has interacted with the browser, into your game flow.

"},{"location":"video/#pause","title":"Pause","text":"
  • Pause
    video.setPaused();\n// video.setPaused(true);\n
  • Resume
    video.setPaused(false);\n

Play video after paused

Call video.setPaused(false) to resume playing.

"},{"location":"video/#stop","title":"Stop","text":"

Stops the video playing and clears all internal event listeners.

video.stop();\n
"},{"location":"video/#is-playing","title":"Is playing","text":"
  • Is playing
    var isPlaying = video.isPlaying();  // (not PAUSE) and (not not ENDED)\n
  • Is paused
    var isPaused = video.isPaused();\n
"},{"location":"video/#playback-time","title":"Playback time","text":"
  • Get
    var playbackTime = video.getCurrentTime();\n
    or
    var t = video.getProgress(); // t: 0~1\n
  • Set
    • Set to
      video.setCurrentTime(playbackTime);  // time in seconds\n
      or
      video.seekTo(t); // t: 0~1\n
      • Is seeking
        var isSeeking = video.isSeeking();\n
    • Forward
      video.setCurrentTime('+' + time);  // time in seconds\n// video.setCurrentTime('+2');\n
    • Backeard
      video.setCurrentTime('-' + time);  // time in seconds\n// video.setCurrentTime('-2');\n
"},{"location":"video/#playback-rate","title":"Playback rate","text":"
  • Get
    var rate = video.getPlaybackRate();\n
  • Set
    video.setPlaybackRate(rate);\n
"},{"location":"video/#duration","title":"Duration","text":"
var duration = video.getDuration();  // time in seconds\n
"},{"location":"video/#volume","title":"Volume","text":"
  • Get
    var volume = video.getVolume();  // volume: 0~1\n
  • Set
    video.setVolume(volume);  // volume: 0~1\n
"},{"location":"video/#mute","title":"Mute","text":"
  • Get
    var muted = video.isMuted();  // muted: true/false\n
  • Set
    video.setMute(muted);  // muted: true/false\n
"},{"location":"video/#loop","title":"Loop","text":"
  • Get
    var loop = video.getLoop();  // loop: true/false\n
  • Set
    video.setLoop(loop);  // loop: true/false\n
"},{"location":"video/#video-key","title":"Video key","text":"
  • Get
    var key = video.getVideoKey();\n
  • Change video key (video source)
    video.changeSource(key);\n// video.changeSource(key, autoplay, loop, markerIn, markerOut);\n
    • autoplay : Should the video start playing immediately, once the swap is complete?
    • loop : Should the video loop automatically when it reaches the end? Not all browsers support seamless video looping for all encoding formats.
    • markerIn, markerOut : Optional in/out marker time, in seconds, for playback of a sequence of the video.
"},{"location":"video/#marks","title":"Marks","text":"
  • Add mark
    video.addMarker(key, markerIn, markerOut);\n
    • key : A unique name to give this marker.
    • markerIn, markerOut : The time, in seconds, representing the start/end of this marker.
  • Play mark
    video.playMarker(key, loop);\n
  • Remove mark
    video.removeMarker(key);\n
"},{"location":"video/#snapshot","title":"Snapshot","text":"
  1. Allocate a canvas texrure
    video.saveSnapshotTexture(key);\n
    • key : Texture key.
  2. Take a snapshot
    var canvasTexture = video.video.snapshot();\n// var canvasTexture = video.snapshot(width, height);\n
    or
    var canvasTexture = video.snapshotArea(x, y, srcWidth, srcHeight);\n// var canvasTexture = video.snapshotArea(x, y, srcWidth, srcHeight, destWidth, destHeight);\n
    • x, y : The horizontal/vertical location of the top-left of the area to grab from.
    • srcWidth, srcHeight : The width/height of area to grab from the video.
    • destWidth, destHeight : The destination width/height of the grab, allowing you to resize it.
    • canvasTexture : Canvas texture object.
      • Get key of texture
        var key = canvasTexture.key;\n
"},{"location":"video/#save-texture","title":"Save texture","text":"

The saved texture is automatically updated as the video plays. If you pause this video, or change its source, then the saved texture updates instantly.

var texture = video.saveTexture(key);\n// var texture = video.saveTexture(key, flipY);\n
  • flipY : Set to true if use it as the input for a Shader.
"},{"location":"video/#events","title":"Events","text":"
  • The media source doesn't represent a supported media format.
    video.on('unsupported', function(video, error){\n\n}, scope);\n
  • A Video is unlocked by a user gesture.
    video.on('unlocked', function(video, error){\n\n}, scope);\n
  • A Video tries to play a source that does not exist, or is the wrong file type.
    video.on('error', function(video, error){\n\n}, scope);\n
  • A Video has access to the metadata.
    video.on('metadata', function(video){\n\n}, scope);\n
  • A Video has exhausted its allocated time while trying to connect to a video source to start playback.
    video.on('timeout', function(video){\n\n}, scope);\n
  • A Video begins playback.
    video.on('play', function(video){\n\n}, scope);\n
  • First started or restarted.
    video.on('playing', function(video){\n\n}, scope);\n
  • The video has finished loading enough data for its first frame.
    video.on('textureready', function(video){\n\n}, scope);\n
  • A Video finishes playback by reaching the end of its duration, or markerOut.
    video.on('complete', function(video){\n\n}, scope);\n
  • A Video that is currently playing has looped.
    video.on('loop', function(video){\n\n}, scope);\n
  • A Video begins seeking to a new point in its timeline.
    video.on('seeking', function(video){\n\n}, scope);\n
  • A Video completes seeking to a new point in its timeline.
    video.on('seeked', function(video){\n\n}, scope);\n
  • Enough of the video source has been loaded, that the browser is able to render a frame from it.
    video.on('created', function(video, width, height){\n\n}, scope);\n
  • Stalled by stalled, suspend, waiting DOM event.
    video.on('stalled', function(video, width, height){\n\n}, scope);\n
  • A Video is stopped from playback via a call to the Video.stop method,
    video.on('stop', function(video){\n\n}, scope);\n
"},{"location":"video/#other-properties","title":"Other properties","text":"

See game object

"},{"location":"video/#create-mask","title":"Create mask","text":"
var mask = video.createBitmapMask();\n

See mask

"},{"location":"video/#shader-effects","title":"Shader effects","text":"

Support preFX and postFX effects

"},{"location":"viewport-coordinate/","title":"Viewport-coordinate","text":""},{"location":"viewport-coordinate/#introduction","title":"Introduction","text":"

Attach vpx, vpy properties to a game object, to set position according to proportion (vpx, vpy) of viewport, a rectangle).

  • Author: Rex
  • Method only
"},{"location":"viewport-coordinate/#live-demos","title":"Live demos","text":"
  • Resize
"},{"location":"viewport-coordinate/#usage","title":"Usage","text":"

Sample code

"},{"location":"viewport-coordinate/#install-plugin","title":"Install plugin","text":""},{"location":"viewport-coordinate/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexviewportcoordinateplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexviewportcoordinateplugin.min.js', true);\n
  • Attach vpx, vpy properties.
    scene.plugins.get('rexviewportcoordinateplugin').add(gameObject, viewport, vpx, vpy);\ngameObject.vpx = 0.5;\ngameObject.vpy = 0.5;\n
"},{"location":"viewport-coordinate/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ViewportCoordinatePlugin from 'phaser3-rex-plugins/plugins/viewportcoordinate-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexViewportCoordinate',\nplugin: ViewportCoordinatePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Attach vpx, vpy, vpxOffset, vpyOffset properties.
    scene.plugins.get('rexViewportCoordinate').add(gameObject, viewport, vpx, vpy);\ngameObject.vpx = 0.5;\ngameObject.vpy = 0.5;\ngameObject.vpxOffset = 0;\ngameObject.vpyOffset = 0;\n
"},{"location":"viewport-coordinate/#import-method","title":"Import method","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import method
    import AddViewportCoordinateProperties from 'phaser3-rex-plugins/plugins/viewportcoordinate.js';\n
  • Attach vpx, vpy, vpxOffset, vpyOffset properties.
    AddViewportCoordinateProperties(gameObject, viewport, vpx, vpy);\ngameObject.vpx = 0.5;\ngameObject.vpy = 0.5;\ngameObject.vpxOffset = 0;\ngameObject.vpyOffset = 0;\n
"},{"location":"viewport-coordinate/#attach-properties","title":"Attach properties","text":"
scene.plugins.get('rexViewportCoordinate').add(gameObject, viewport, vpx, vpy, transformCallback);\n
  • vpx, vpy : Proportion of viewport.
  • vpxOffset, vpyOffset : Offset of position.
  • viewport : Viewport in rectangle
  • transformCallback : Transform callback.
    • undefined : Use default transform callback.
      function(vpx, vpy, vpxOffset, vpyOffset, viewport, out) {\ngameObject.x = viewport.x + (viewport.width * vpx) + vpxOffset;\ngameObject.y = viewport.y + (viewport.height * vpy) + vpyOffset;\n}\n

Changing

  • gameObject.vpx, gameObject.vpy, gameObject.vpxOffset, gameObject.vpyOffset
  • x, y, width, height of viewport (a rectangle)

Will change position (x , y) of game object.

"},{"location":"virtualjoystick/","title":"Virtual joystick","text":""},{"location":"virtualjoystick/#introduction","title":"Introduction","text":"

Simulate cursor keys according to touch events.

  • Author: Rex
  • Member of scene
"},{"location":"virtualjoystick/#live-demos","title":"Live demos","text":"
  • Virtual joystick
  • Two joySticks
  • Joystick and button
  • Toggle visible
  • Drag vector to cursor keys
"},{"location":"virtualjoystick/#usage","title":"Usage","text":"

Sample code

"},{"location":"virtualjoystick/#install-plugin","title":"Install plugin","text":""},{"location":"virtualjoystick/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexvirtualjoystickplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexvirtualjoystickplugin.min.js', true);\n
  • Create instance
    var joyStick = scene.plugins.get('rexvirtualjoystickplugin').addPlayer(scene, config);\n
"},{"location":"virtualjoystick/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import VirtualJoystickPlugin from 'phaser3-rex-plugins/plugins/virtualjoystick-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexVirtualJoystick',\nplugin: VirtualJoystickPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var joyStick = scene.plugins.get('rexVirtualJoystick').addPlayer(scene, config);\n
"},{"location":"virtualjoystick/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import VirtualJoystick from 'phaser3-rex-plugins/plugins/virtualjoystick.js';\n
  • Create instance
    var joyStick = new VirtualJoystick(scene, config);\n
"},{"location":"virtualjoystick/#create-instance","title":"Create instance","text":"
var joystick = scene.plugins.get('rexVirtualJoystick').add(scene, {\nx: x,\ny: y,\nradius: 100,\nbase: baseGameObject,\nthumb: thumbGameObject,\n// dir: '8dir',\n// forceMin: 16,\n// fixed: true,\n// enable: true\n});\n
  • base : Base game object.
    • Create a circle shape object if no base game object passed.
  • thumb : Thumb game object.
    • Create a circle shape object if no thumb game object passed.
  • x, y : Position of base game object
  • radius : Circle hit-area of base game object
  • dir :
    • 'up&down', or 0 : Simulate up or down cursor keys only.
    • 'left&right', or 1 : Simulate left or right cursor keys only.
    • '4dir', or 2 : Simulate up, down, left or right cursor keys.
    • '8dir', or 3 : Simulate up, up-left, up-right, down, down-left, down-right, left, or right cursor keys.
  • forceMin : Cursor keys will be pressed when force is larger then this value.
    • force : Distance between position of base game object to touch pointer
  • fixed : Set true to fix to camera, i.e set scrollFactor to 0 for base and thumb game object. Default value is true.
  • enable : Set false to disable cursor keys simulation
"},{"location":"virtualjoystick/#state-of-cursor-keys","title":"State of cursor keys","text":"
var cursorKeys = joystick.createCursorKeys();\n\nvar leftKeyDown = cursorKeys.left.isDown;\nvar rightKeyDown = cursorKeys.right.isDown;\nvar upKeyDown = cursorKeys.up.isDown;\nvar downKeyDown = cursorKeys.down.isDown;\n

Or

var leftKeyDown = joystick.left;\nvar rightKeyDown = joystick.right;\nvar upKeyDown = joystick.up;\nvar downKeyDown = joystick.down;\nvar noKeyDown = joystick.noKey;\n
"},{"location":"virtualjoystick/#force-angle","title":"Force & Angle","text":"

Force : Distance between position of base game object to touch pointer.

var force = joystick.force;\nvar forceX = joystick.forceX;\nvar forceY = joystick.forceY;\n\nvar angle = joystick.angle;  // degree between -180 to 180\nvar rotation = joystick.rotation; // radians\n
"},{"location":"virtualjoystick/#visible","title":"Visible","text":"

Visible of base game object.

  • Get : Return visible of base game object
    var visible = joystick.visible;\n
  • Set : Set visible to base game object and thumb game object
    joystick.visible = visible;\njoystick.setVisible(visible);\njoystick.toggleVisible();\n
    Joystick will be disabled when invisible.
"},{"location":"virtualjoystick/#enable","title":"Enable","text":"
  • Get
    var enable = joystick.enable;\n
  • Set
    joystick.setEnable(enable);  // enable: true, or false\n//joystick.enable = enable;\n
  • Toggle
    joystick.toggleEnable();\n
"},{"location":"virtualjoystick/#position","title":"Position","text":"

Position of base game object.

  • Get
    var x = joystick.x;\nvar y = joystick.y;\n
  • Set
    joystick.setPosition(x ,y);\n// joystick.x = x;\n// joystick.y = y;\n
"},{"location":"virtualjoystick/#scroll-factor","title":"Scroll factor","text":"
  • Fix to camera
    joystick.setScrollFactor(0);\n
"},{"location":"virtualjoystick/#touch-pointer","title":"Touch pointer","text":"
  • Position
    var x = joystick.pointerX;\nvar y = joystick.pointerY;\n
  • Pointer
    var pointer = joystick.pointer;\n
"},{"location":"virtualjoystick/#destroy","title":"Destroy","text":"

Destroy base & thumb game object.

joystick.destroy();\n
"},{"location":"virtualjoystick/#events","title":"Events","text":"
  • On joystick updated :
    joystick.on('update', function(){});\n
  • On pointer-down
    joystick.on('pointerdown', function(pointer){});\n
  • On pointer-up
    joystick.on('pointerup', function(pointer){});\n
"},{"location":"virtualjoystick/#elements","title":"Elements","text":"
  • Base Game object:
    var baseGO = joystick.base;\n
  • Thumb Game object:
    var thumb = joystick.thumb;\n
"},{"location":"virtualjoystick/#vector-to-cursor-keys","title":"Vector to cursor keys","text":"

A controller to represent cursor keys by (drag) vector

"},{"location":"virtualjoystick/#create-controller","title":"Create controller","text":"
var controller = scene.plugins.get('rexVirtualJoyStick').addVectorToCursorKeys({\n// dir: '8dir',\n// forceMin: 16,\n// enable: true\n})\n

or

// import VirtualJoystick from 'phaser3-rex-plugins/plugins/vectortocursorkeys.js';\nvar controller = new VirtualJoystick(undefined, config);\n
  • dir :
    • 'up&down', or 0 : Simulate up or down cursor keys only.
    • 'left&right', or 1 : Simulate left or right cursor keys only.
    • '4dir', or 2 : Simulate up, down, left or right cursor keys.
    • '8dir', or 3 : Simulate up, up-left, up-right, down, down-left, down-right, left, or right cursor keys.
  • forceMin : Cursor keys will be pressed when force is larger then this value.
    • force : Distance between position of base game object to touch pointer
  • enable : Set false to disable cursor keys simulation.
"},{"location":"virtualjoystick/#set-vector","title":"Set vector","text":"
  • Set vector
    controller.setVector(x0, y0, x1, y1);\n
  • Clear vector
    controller.clearVector();\n
"},{"location":"virtualjoystick/#state-of-cursor-keys_1","title":"State of cursor keys","text":"
var cursorKeys = controller.createCursorKeys();\n\nvar leftKeyDown = cursorKeys.left.isDown;\nvar rightKeyDown = cursorKeys.right.isDown;\nvar upKeyDown = cursorKeys.up.isDown;\nvar downKeyDown = cursorKeys.down.isDown;\n
"},{"location":"virtualjoystick/#force-angle_1","title":"Force & Angle","text":"
var force = controller.force;\nvar forceX = controller.forceX;\nvar forceY = controller.forceY;\n\nvar angle = controller.angle;  // degree between -180 to 180\nvar rotation = controller.rotation; // radians\n
"},{"location":"waitevents/","title":"Wait events","text":""},{"location":"waitevents/#introduction","title":"Introduction","text":"

Wait fired events or callbacks.

  • Author: Rex
"},{"location":"waitevents/#usage","title":"Usage","text":"

Sample code

"},{"location":"waitevents/#install-plugin","title":"Install plugin","text":""},{"location":"waitevents/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexwaiteventsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexwaiteventsplugin.min.js', true);\n
  • Create instance
    var waitEvents = scene.plugins.get('rexwaiteventsplugin').add(completeCallback, completeCallbackScope);\n
"},{"location":"waitevents/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import WaitEventsPlugin from 'phaser3-rex-plugins/plugins/waitevents-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexWaitEvents',\nplugin: WaitEventsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Create instance
    var waitEvents = scene.plugins.get('rexWaitEvents').add(completeCallback, completeCallbackScope);\n
"},{"location":"waitevents/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import WaitEvents from 'phaser3-rex-plugins/plugins/waitevents.js';\n
  • Create instance
    var waitEvents = new WaitEvents(completeCallback, completeCallbackScope);\n
"},{"location":"waitevents/#create-instance","title":"Create instance","text":"
var waitEvents = scene.plugins.get('rexWaitEvents').add(completeCallback, completeCallbackScope);\n
  • completeCallback, completeCallbackScope : Callback when all waitting events are fired.
"},{"location":"waitevents/#set-complete-callback","title":"Set complete callback","text":"
waitEvents.setCompleteCallback(completeCallback, completeCallbackScope);\n
  • completeCallback, completeCallbackScope : Callback when all waitting events are fired.
"},{"location":"waitevents/#add-waiting-event","title":"Add waiting event","text":""},{"location":"waitevents/#callback","title":"Callback","text":"
var callback = waitEvents.waitCallback();\n
  • callback : A function object which invoked when waitting event finished.

For example, invokes completeCallback when all timers are time-out.

scene.time.delayedCall(500, waitEvents.waitCallback());\nscene.time.delayedCall(1000, waitEvents.waitCallback());\nscene.time.delayedCall(1500, waitEvents.waitCallback());\n
"},{"location":"waitevents/#callback-from-event-emitter","title":"Callback from event emitter","text":"
waitEvents.waitEvent(eventEmitter, eventName);\n
"},{"location":"waitevents/#remove-waiting-event","title":"Remove waiting event","text":"
callback();\n

or

waitEvents.remove(callback);\n
  • callback : A function object created via waitEvents.waitCallback()
"},{"location":"waitevents/#clear-all-waiting-events","title":"Clear all waiting events","text":"
waitEvents.clear();\n
"},{"location":"waitevents/#no-wait-event","title":"No wait event","text":"
var noWaitEvent = waitEvents.noWaitEvent;\n
"},{"location":"webfontloader/","title":"Webfont loader","text":""},{"location":"webfontloader/#introduction","title":"Introduction","text":"

Load web font by google webfont loader in payload or preload stage.

  • Author: Rex
  • Custom File of loader
"},{"location":"webfontloader/#live-demos","title":"Live demos","text":"
  • Webfont loader
"},{"location":"webfontloader/#usage","title":"Usage","text":"

Sample code

"},{"location":"webfontloader/#install-plugin","title":"Install plugin","text":""},{"location":"webfontloader/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    var sceneConfig = {\n// ....\npack: {\nfiles: [{\ntype: 'plugin',\nkey: 'rexwebfontloaderplugin',\nurl: 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/    rexwebfontloaderplugin.min.js',\nstart: true\n}]\n}\n};\nclass MyScene extends Phaser.Scene {\nconstructor() {\nsuper(sceneConfig)\n}\n// ....\n\npreload() {\n// rexwebfontloaderplugin will be installed before preload(), but not added to loader yet\n// Call addToScene(scene) to add this await loader to loader of this scene\nthis.plugins.get('rexwebfontloaderplugin').addToScene(this);\n\nthis.load.rexWebFont(config);\n}\n}\n
"},{"location":"webfontloader/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import WebFontLoaderPlugin from 'phaser3-rex-plugins/plugins/webfontloader-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexWebFontLoader',\nplugin: WebFontLoaderPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • In preload stage
    scene.load.rexWebFont(config);\n
"},{"location":"webfontloader/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import WebFontLoader from 'phaser3-rex-plugins/plugins/webfontloader.js';\n
  • Start loading task
    WebFontLoader.call(scene.load, config);\n
"},{"location":"webfontloader/#load-webfont","title":"Load webfont","text":"

In preload stage:

this.load.rexWebFont({\ngoogle: {\nfamilies: ['Bangers']\n},\n// testString: undefined,\n// testInterval: 20,\n});\n
  • testString : To test if the font is loaded completed or not.
    • undefined : No testing. Default value.
    • A string : A test string for all fonts
    • An object, {fontFamily: testString} : Test string for a specific font family.
  • testInterval : Retry interval.

or load font in pack

var sceneConfig = {\nkey: '...',\npack: {\nfiles: [{\ntype: 'rexWebFont',\nkey: 'webfont',\nconfig: {\ngoogle: {\nfamilies: ['Bangers']\n},\n// testString: undefined,\n// testInterval: 20,\n}\n}\n]\n}\n};\n

Configuration of loading fonts

  • Google webfont
    WebFontConfig = {\ngoogle: {\nfamilies: ['Droid Sans', 'Droid Serif:bold']\n}\n};\n
  • Custom font
    WebFontConfig = {\ncustom: {\nfamilies: ['My Font', 'My Other Font:n4,i4,n7'],\nurls: ['/fonts.css']\n}\n};\n
    and fonts.css
    @font-face {\nfont-family: 'My Font';\nsrc: ...;\n}\n@font-face {\nfont-family: 'My Other Font';\nfont-style: normal;\nfont-weight: normal; /* or 400 */\nsrc: ...;\n}\n@font-face {\nfont-family: 'My Other Font';\nfont-style: italic;\nfont-weight: normal; /* or 400 */\nsrc: ...;\n}\n@font-face {\nfont-family: 'My Other Font';\nfont-style: normal;\nfont-weight: bold; /* or 700 */\nsrc: ...;\n}\n
"},{"location":"webfontloader/#events","title":"Events","text":"
  • fontactive event

    this.load.on('webfontactive', function(fileObj, familyName){});\n
  • fontinactive event

    this.load.on('webfontinactive', function(fileObj, familyName){});\n
"},{"location":"webfontloader/#test-string","title":"Test string","text":"

Add string parameter testString into config, to test if the font is loaded completed or not.

  1. Fill 0 within an internal canvas.
  2. Draw testString.
  3. Check if any pixel has non-zero value.
"},{"location":"wrap/","title":"Wrap","text":""},{"location":"wrap/#introduction","title":"Introduction","text":"

Wrap the given value between min and max, built-in method of phaser.

  • Author: Richard Davey
"},{"location":"wrap/#usage","title":"Usage","text":"
var result = Phaser.Math.Wrap(value, min, max);\n
  • value : The value to wrap.
"},{"location":"xor/","title":"XOR","text":""},{"location":"xor/#introduction","title":"Introduction","text":"

Encrypt or decrypt string by XOR algorithm.

  • Author: Rex
  • Methods
"},{"location":"xor/#usage","title":"Usage","text":"

Sample code

"},{"location":"xor/#install-plugin","title":"Install plugin","text":""},{"location":"xor/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexxorplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexxorplugin.min.js', true);\n
  • Encrypt, or decrypt
    var encResult = scene.plugins.get('rexxorplugin').Encrypt(src, pwd);\nvar decResult = scene.plugins.get('rexxorplugin').Decrypt(encResult, pwd);\n
"},{"location":"xor/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import XORPlugin from 'phaser3-rex-plugins/plugins/xor-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexXOR',\nplugin: XORPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Encrypt, or decrypt
    var encResult = scene.plugins.get('rexXOR').Encrypt(src, pwd);\nvar decResult = scene.plugins.get('rexXOR').Decrypt(encResult, pwd);\n
"},{"location":"xor/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import XOR from 'phaser3-rex-plugins/plugins/xor.js';\n
  • Encrypt, or decrypt
    var encResult = XOR.Encrypt(src, pwd);\nvar decResult = XOR.Decrypt(encResult, pwd);\n
"},{"location":"xor/#encrypt","title":"Encrypt","text":"
var encResult = scene.plugins.get('rexXOR').Encrypt(src, pwd);\n
"},{"location":"xor/#decrypt","title":"Decrypt","text":"
var decResult = scene.plugins.get('rexXOR').Decrypt(encResult, pwd);\n
"},{"location":"ymlachievements/","title":"YAML Achievements","text":""},{"location":"ymlachievements/#introduction","title":"Introduction","text":"

Achievements in a YAML table.

  • Author: Rex
  • Member of scene
"},{"location":"ymlachievements/#usage","title":"Usage","text":"

Sample code

"},{"location":"ymlachievements/#install-plugin","title":"Install plugin","text":""},{"location":"ymlachievements/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexymlachievementsplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexymlachievementsplugin.min.js', true);\n
  • Add conditions-table object
    var achievements = scene.plugins.get('rexymlachievementsplugin').add();\n
"},{"location":"ymlachievements/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import AchievementsPlugin from 'phaser3-rex-plugins/plugins/ymlachievements-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexAchievements',\nplugin: AchievementsPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add conditions-table object
    var achievements = scene.plugins.get('rexAchievements').add();\n
"},{"location":"ymlachievements/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import Achievements from 'phaser3-rex-plugins/plugins/ymlachievements.js';\n
  • Add conditions-table object
    var achievements = new Achievements();\n
"},{"location":"ymlachievements/#create-instance","title":"Create instance","text":"
var achievements = scene.plugins.get('rexAchievements').add();\n
"},{"location":"ymlachievements/#load-table-from-yaml-string","title":"Load table from YAML string","text":"
achievements.loadYML(ymlString);\n

For exameple

Lv1 :\nAch1 : (A >= 10) && (A < 20)\nAch2 : (A >= 20) && (A < 50)\nAch3 : A >= 50\n

Equations will be parsed by expression-parser.

"},{"location":"ymlachievements/#test","title":"Test","text":"
  1. Run test
    var achievements.runTest(levelName, values);\n
    • levelName : Level name, in 1st column of achievements table.
    • values : Inputs in Key-value pairs
  2. Get obtained states
    var states = achievements.getObtainedState(levelName);\n
    • states : Obtained states of levelName
      {\nachievementName: {\nwasObtained: boolean,\njustObtained: boolean\n}\n}\n
      • wasObtained : Obtained this achievement achievementName before last testing.
      • justObtained : Obtained this achievement achievementName at last testing.

or

var states = achievements.getTestResults(levelName, values);\n
"},{"location":"ymlachievements/#get-obtained-states","title":"Get obtained states","text":"
  • Get obtained states of an achievement in a level
    var state = achievements.getObtainedState(levelName, achievementName);\n
    • state : Obtained states of achievementName, in level levelName
      {\nwasObtained: boolean,\njustObtained: boolean\n}\n
      • wasObtained : Obtained this achievement achievementName before last testing.
      • justObtained : Obtained this achievement achievementName at last testing.
  • Get obtained states of a level
    var state = achievements.getObtainedState(levelName);\n
    • states : Obtained states of levelName
      {\nachievementName: {\nwasObtained: boolean,\njustObtained: boolean\n}\n}\n
  • Get obtained states of all levels
    var state = achievements.getObtainedState();\n// var state = achievements.getObtainedStates();\n
    • states : Obtained states of all levels
      {\nlevelName: {\nachievementName: {\nwasObtained: boolean,\njustObtained: boolean\n}\n}\n}\n
  • For each obtained state in a level
    achievements.forEachObtainedState(levelName, function(levelName, achievementName, state) {\n\n}, scope)\n
    • state : Obtained states of achievementName, in level levelName
      {\nwasObtained: boolean,\njustObtained: boolean\n}\n
"},{"location":"ymlachievements/#get-name","title":"Get name","text":"
  • Name of levels
    var names = achievements.getLevelNames();\n// var names = achievements.getLevelNames(out);\n
  • Name of achievements in a level
    var names = achievements.getAchievementNames(levelName);\n// var names = achievements.getAchievementNames(levelName, out);\n
"},{"location":"ymlachievements/#save-load-obtained-states","title":"Save & load obtained states","text":"
  • Get obtained states
    var states = achievements.getObtainedStates();\n
  • Load obtained states
    achievements.loadObtainedStates(states);\n
"},{"location":"ymlachievements/#set-obtained-state","title":"Set obtained state","text":"
  • Set wasObtained, justObtained properties to true.
    achievements.setObtainedState(levelName, achievementName);\n
  • Set wasObtained, justObtained properties to false.
    achievements.clearObtainedState(levelName, achievementName);\n// achievements.setObtainedState(levelName, achievementName, false);\n
"},{"location":"ymlconditionstable/","title":"YAML Conditions table","text":""},{"location":"ymlconditionstable/#introduction","title":"Introduction","text":"

Check conditions to find passed tests listed in a YAML table.

  • Author: Rex
  • Member of scene
"},{"location":"ymlconditionstable/#usage","title":"Usage","text":"

Sample code

"},{"location":"ymlconditionstable/#install-plugin","title":"Install plugin","text":""},{"location":"ymlconditionstable/#load-minify-file","title":"Load minify file","text":"
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexymlconditionstableplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexymlconditionstableplugin.min.js', true);\n
  • Add conditions-table object
    var conditionstable = scene.plugins.get('rexymlconditionstableplugin').add();\n
"},{"location":"ymlconditionstable/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import ConditionsTablePlugin from 'phaser3-rex-plugins/plugins/ymlconditionstable-plugin.js';\nvar config = {\n// ...\nplugins: {\nglobal: [{\nkey: 'rexConditionsTable',\nplugin: ConditionsTablePlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
  • Add conditions-table object
    var conditionstable = scene.plugins.get('rexConditionsTable').add();\n
"},{"location":"ymlconditionstable/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Import class
    import ConditionsTable from 'phaser3-rex-plugins/plugins/ymlconditionstable.js';\n
  • Add conditions-table object
    var conditionstable = new ConditionsTable();\n
"},{"location":"ymlconditionstable/#create-instance","title":"Create instance","text":"
var table = scene.plugins.get('rexConditionsTable').add();\n
"},{"location":"ymlconditionstable/#load-table-from-yaml-string","title":"Load table from YAML string","text":"
table.loadYML(ymlString);\n

For exameple

Test1 : (A >= 10) && (A <= 20)\nTest2 : B == 3\n

Equations will be parsed by expression-parser.

"},{"location":"ymlconditionstable/#test","title":"Test","text":""},{"location":"ymlconditionstable/#get-test-results","title":"Get test results","text":"
var results = table.getTestResults(context);\n
  • context : Inputs in Key-value pairs
  • results : {name: boolean}, use OR operation to combine result of tests with the same name.
"},{"location":"ymlconditionstable/#get-first-pass-test-name","title":"Get first pass test name","text":"
var testName = table.anyPassTest(context);\n
  • context : Inputs in Key-value pairs
"},{"location":"youtubeplayer/","title":"Youtube player","text":""},{"location":"youtubeplayer/#introduction","title":"Introduction","text":"

Play youtube video on iframe.

  • Author: Rex
  • DOM Game object
"},{"location":"youtubeplayer/#live-demos","title":"Live demos","text":"
  • Youtube player
"},{"location":"youtubeplayer/#usage","title":"Usage","text":"

Sample code

"},{"location":"youtubeplayer/#install-plugin","title":"Install plugin","text":""},{"location":"youtubeplayer/#load-minify-file","title":"Load minify file","text":"
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Load plugin (minify file) in preload stage
    scene.load.plugin('rexyoutubeplayerplugin', 'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexyoutubeplayerplugin.min.js', true);\n
  • Add youtube player object
    var youtubePlayer = scene.add.rexYoutubePlayer(x, y, width, height, config);\n
"},{"location":"youtubeplayer/#import-plugin","title":"Import plugin","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Install plugin in configuration of game
    import YoutubePlayerPlugin from 'phaser3-rex-plugins/plugins/youtubeplayer-plugin.js';\nvar config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\nplugins: {\nglobal: [{\nkey: 'rexYoutubePlayer',\nplugin: YoutubePlayerPlugin,\nstart: true\n},\n// ...\n]\n}\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Add youtube player object
    var youtubePlayer = scene.add.rexYoutubePlayer(x, y, width, height, config);\n
"},{"location":"youtubeplayer/#import-class","title":"Import class","text":"
  • Install rex plugins from npm
    npm i phaser3-rex-plugins\n
  • Enable dom element in configuration of game
    var config = {\nparent: divId,\n// fullscreenTarget: divId, // For fullscreen\ndom: {\ncreateContainer: true\n},\ninput: {\nmouse: {\ntarget: divId\n},\ntouch: {\ntarget: divId\n},\n},\n// ...\n};\nvar game = new Phaser.Game(config);\n
    • Set parent to divId
    • Set dom.createContainer to true.
  • Import class
    import YoutubePlayer from 'phaser3-rex-plugins/plugins/youtubeplayer.js';\n
  • Add youtube player object
    var youtubePlayer = new YoutubePlayer(scene, x, y, width, height, config);\nscene.add.existing(youtubePlayer);\n
"},{"location":"youtubeplayer/#add-youtube-player-object","title":"Add youtube player object","text":"
  • Youtube player on DOM
    var player = scene.add.rexYoutubePlayer(x, y, width, height, config);\n// var player = scene.add.rexYoutubePlayer(x, y, config);\n// var player = scene.add.rexYoutubePlayer(config);\n

Default configuration

{\nx: 0,\ny: 0,\nwidth: undefined,\nheight: undefined,\n\nvideoId: '',\nautoPlay: true,\ncontrols: false,\nkeyboardControl: true,\nmodestBranding: false,\nloop: false,\n}\n
  • x, y : Position
  • width, height : Size of element
  • videoId : The YouTube video ID that identifies the video that the player will load.
  • autoPlay : Automatically start to play when the player loads.
  • controls : Whether the video player controls are displayed.
  • keyboardControl : Set false to disable keyboard controls.
  • modestBranding : Set false to prevent the YouTube logo from displaying in the control bar.
  • loop : Play video when ended.
"},{"location":"youtubeplayer/#custom-class","title":"Custom class","text":"
  • Define class
    class MyYoutubePlayer extends YoutubePlayer {  // or YoutubePlayerCanvas\nconstructor(scene, x, y, width, height, config) {\nsuper(scene, x, y, width, height, config) {\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {\n//     super.preUpdate(time, delta)\n// }\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var player = new MyYoutubePlayer(scene, x, y, width, height, config);\n
"},{"location":"youtubeplayer/#load","title":"Load","text":"
player.load(videoId);\n// player.load(videoId, autoPlay);\n
"},{"location":"youtubeplayer/#play","title":"Play","text":"
player.play();\n
"},{"location":"youtubeplayer/#pause","title":"Pause","text":"
player.pause();\n
"},{"location":"youtubeplayer/#playback-time","title":"Playback time","text":"
  • Get
    var playbackTime = player.playbackTime; // time in seconds\n
    var t = player.t; // t: 0~1\n
  • Set
    player.setPlaybackTime(time); // time in seconds\n// player.playbackTime = time;\n
    player.setT(t); // t: 0~1\n// player.t = t;\n
"},{"location":"youtubeplayer/#duration","title":"Duration","text":"
var duration = player.duration;  // time in seconds\n
"},{"location":"youtubeplayer/#volume","title":"Volume","text":"
  • Get
    var volume = player.volume;  // volume: 0~1\n
  • Set
    player.setVolume(volume);  // volume: 0~1\n// player.volume = volume;\n
"},{"location":"youtubeplayer/#mute","title":"Mute","text":"
  • Get
    var muted = player.muted;  // muted: true/false\n
  • Set
    player.setMute(muted);  // muted: true/false\n// player.muted = muted;\n
"},{"location":"youtubeplayer/#loop","title":"Loop","text":"
  • Get
    var loop = player.loop;  // loop: true/false\n
  • Set
    player.setLoop(loop);  // loop: true/false\n// player.loop = loop;\n
"},{"location":"youtubeplayer/#resize","title":"Resize","text":"
player.resize(width, height);\n
"},{"location":"youtubeplayer/#status","title":"Status","text":"
  • Is playing
    var isPlaying = player.isPlaying;\n
  • Is paused
    var isPaused = player.isPaused;\n
  • Has end
    var hasEnded = player.hasEnded;\n
  • Video state
    var videoState = player.videoState;\n
    or
    var videoStateString = player.videoStateString;\n
    • -1 : unstarted
    • 0 : ended
    • 1 : playing
    • 2 : paused
    • 3 : buffering
    • 5 : cued
"},{"location":"youtubeplayer/#events","title":"Events","text":"
  • Youtube player api ready
    player.on('ready', function(player){ }, scope);\n
  • State change
    player.on('statechange', function(player){ }, scope);\n
    • State : player.videoState
  • Unstarted
    player.on('unstarted', function(player){ }, scope);\n
  • Playing
    player.on('playing', function(player){ }, scope);\n
  • Pause
    player.on('pause', function(player){ }, scope);\n
  • Ended
    player.on('ended', function(player){ }, scope);\n
  • Buffering
    player.on('buffering', function(player){ }, scope);\n
  • Video cued
    player.on('cued', function(player){ }, scope);\n
  • Error
    player.on('error', function(player, errorMessage){ }, scope);\n

No Playback time changed event

Get playback time every tick might cause playing video lagging.

"},{"location":"youtubeplayer/#other-properties","title":"Other properties","text":"

See dom game object, game object

"},{"location":"youtubeplayer/#interactive-with-other-game-objects","title":"Interactive with other game objects","text":"

See dom-element's Interactive with other game objects

"},{"location":"zone/","title":"Zone","text":""},{"location":"zone/#introduction","title":"Introduction","text":"

Non-rendering rectangular game object for creating drop zones and input hit areas, built-in game object of phaser.

  • Author: Richard Davey
"},{"location":"zone/#usage","title":"Usage","text":""},{"location":"zone/#add-zone-object","title":"Add zone object","text":"
var zone = scene.add.zone(x, y, width, height);\n

Add zone from JSON

var zone = scene.make.zone({\nx: 0,\ny: 0,\n//width: 1,\n//height: 1,\n// origin: {x: 0.5, y: 0.5},\n});\n
"},{"location":"zone/#custom-class","title":"Custom class","text":"
  • Define class
    class MyZone extends Phaser.GameObjects.Zone {\nconstructor(scene, x, y, width, height) {\nsuper(scene, x, y, width, height);\n// ...\nscene.add.existing(this);\n}\n// ...\n\n// preUpdate(time, delta) {}\n}\n
    • scene.add.existing(gameObject) : Adds an existing Game Object to this Scene.
      • If the Game Object renders, it will be added to the Display List.
      • If it has a preUpdate method, it will be added to the Update List.
  • Create instance
    var zone = new MyZone(x, y, width, height);\n
"},{"location":"zone/#input-hit-zone","title":"Input hit zone","text":"
zone.setInteractive();\n

See touch events

"},{"location":"zone/#drop-zones","title":"Drop zones","text":"
  • Default drop zone
    zone.setDropZone();\n
  • Rectangle drop zone
    zone.setRectangleDropZone(width, height);\n
  • Circular drop zone
    zone.setCircleDropZone(radius);\n
  • Custom drop zone
    zone.setDropZone(shape, callback);\n
    • callback
      function(shape, x, y, gameObject) {\nreturn hit;  // true/false\n}\n

See drop zone

"},{"location":"zone/#other-properties","title":"Other properties","text":"

See game object

"}]} \ No newline at end of file diff --git a/docs/site/sitemap.xml.gz b/docs/site/sitemap.xml.gz index 45e0bc815f157f5c234bd28d7a3ac5fc315d7415..607debd9e311eab00601db66cebe9ebb2c30665b 100644 GIT binary patch delta 16 XcmeAc>lR~|@8;lW7y7Z0orN0!CPD;U delta 16 XcmeAc>lR~|@8;mx`}_Mwb{1{`EiDCl diff --git a/docs/site/ui-trees/index.html b/docs/site/ui-trees/index.html index 21a7add9fa..c7e1594d45 100644 --- a/docs/site/ui-trees/index.html +++ b/docs/site/ui-trees/index.html @@ -10207,7 +10207,7 @@

Trees

Introduction

-

A container with trees and leaf-nodes

+

A container with trees and leaf-nodes.

  • Author: Rex
  • Game object
  • @@ -11009,22 +11009,22 @@

    EventsEvents

    • On tree expand-start -
      trees.on('tree.expand.start', function(tree){
      +    
      trees.on('expand.start', function(tree){
       
       })
       
    • On tree expand-complete -
      trees.on('tree.expand.complete', function(tree){
      +    
      trees.on('expand.complete', function(tree){
       
       })
       
    • On tree collapse-start -
      trees.on('tree.collapse.start', function(tree){
      +    
      trees.on('collapse.start', function(tree){
       
       })
       
    • On tree collapse-complete -
      trees.on('tree.collapse.complete', function(tree){
      +    
      trees.on('collapse.complete', function(tree){
       
       })